9 Hole Challenge

65

27

The 9 Hole Challenge

  • 9 code golfing challenges of varying difficulty.
  • Penalties for using the same language more than once.
  • The question will be updated with pars, hole champions and trophy winners.

    This comes from a competition I have with some friends, it's not the usual format, but I hope some of you will appreciate the different spin on it. Challenges, rules and trophies below.

Holes

  1. Greenway (24)

    f(c:string, n:integer)
    Prints a line containing n instances of c.

  2. Somewhere in the Rough (73)

    f(t:string, s:string, n:integer) -> i
    Where i is the index of the nth instance of s in t.

  3. Curry for Dinner (6235)

    f(x:function, y: function) -> g Where g is a function that will call y, n times; where n is the return value of x

  4. Spew (92)

    f(p:string) Writes to file at p and fills it with a randomly sized rectangle of random characters (ascii).

  5. Treasure Hunt (75)

    f(p:string, c:char) -> (x, y) Reads file at p which contains a grid of symbols and returns the x and y coordinates of the first instance of that symbol within the grid, assume it exists.

  6. Bridge on the River Kwai (179)

    f(l:list[int]) Prints difference bridges diagram for l. E.g for [1,7,3,17,1]

     /+6\ /-4\ /+14\  /-16\
    1    7    3     17     1
    

    Make sure that the spaces are created according to the size of the number above. For a 3 digit long number, you are going to need 4 spaces between the digits on the line below.

    Catch: Somewhere, your code must spell trousers (Must have at least 1 non-alphanumeric delimiters. E.g. tr(ou,se)(rs)

  7. Time Flies When You're Playing Golf (1157)

    f(p:string) -> [h, m] Reads file at p which contains an ASCII representation of an analogue clock, where the hour hand is represented with one lines, and the minutes by two. Output a list containing two elements: the hours and minutes shown on the clock. If only one hand is visible, assume both point to that position.

    Here are all the possible combinations for a hand.

    \ | /
     \|/
    --o--
     /|\
    / | \
    

    These positions, respectively are (12, 1, 3, 5, 6, 7, 9, 11). Assume that the other characters within the clock face are spaces.

  8. Timber! ()

    f(p:string) -> b:boolean Where p is the path to a file with an ascii building in. Blocks with white space underneath them will fall. (Except from slashes, which stay in place if there is a stable block in the opposite direction to the way they face). If the building is structurally integral return true, otherwise return false. All non whitespace blocks are counted as being solid and other than slashes, they all fall.

    Structurally safe

    ____
    |/\|
    |  |
    

    Not Safe

    |__
      | 
      |
    

    Safe version

    |__
    \\| 
      |
    
  9. Slacker News (218)

    f(s:string, r:string, p:string) Gets the titles of the top 20 stories on Hacker News and changes all instances of s to r, then writes the new titles to a html file at p, where each title is contained within a h1 element.

    The outputted file should something like this

    <h1>Some title</h1></h1>Some other title</h1>...etc

    Catch:

    • You may not use the HN api.
    • You may not use Regex.
    • You may not use angle braces anywhere in your code.

Scoring

  • Character count is the length of the function that will compile & run correctly. However you still need to submit the full code, including imports.
  • +10% for every repeated language in your submission. (E.g. If you use Ruby for 3 solutions, then your final score will be multiplied by 1.2). Different versions of the same language count still count as the same language.
  • Par will be average score for each hole.
  • Submit your solutions in one answer.
  • Your overall score is your character count + your language penalty, then round it up.

Trophies

  • Gold Jacket - (@Sprigyig - 1290) Lowest overall score
  • Shooter - (@Sprigyig - 9) Most languages used
  • Bunker - Most above par score on any hole
  • Snakes on a Plane - (@AsksAnyway - 1727) Highest python character submission in a single solution
  • Good Parts - (@AsksAnyway - 255) Highest JS character count in a single solution
  • Shakey Steve - Shortest solution that uses interfaces
  • You're Not From Round Here - Shortest unique language solution that's language has the shortest wikipedia page.
  • Happy Gilmoore - (@AsksAnyway - 31) Shortest solution that has the word 'alligator' in the code.
  • Unicycling Dwarf Magic - The default extensions of your 9 submission source files are a perfect anagram of a word in the Oxford Dictionary.

You are only eligible for a trophy once you have completed all 9 holes


Submissions

  1. @Sprigyig 1290
  2. @Firefly 1320
  3. @grc 1395
  4. @Trevor M 1465
  5. @C Gearhart 1654
  6. @Guy Sirton 1719
  7. @AsksAnyway 4651

Dan Prince

Posted 2013-12-29T19:52:05.340

Reputation: 1 467

Question was closed 2016-04-22T22:44:16.457

Are languages without functions excluded from the challenge? Or can we also write STDIN to STDOUT programs instead of functions? – Martin Ender – 2015-01-31T16:10:37.900

I'm closing this question because multi-part challenges with little interaction between subchallenges became off topic by community consensus.

– Dennis – 2016-04-22T22:44:16.457

I assume "angle braces" refers to what I call "brackets," right? [] – apnorton – 2013-12-29T20:14:28.410

2@anorton < & > – Dan Prince – 2013-12-29T20:15:21.743

@DanPrince Ah! Glad I asked. :) One other question: must the file contain a test case (e.g. actually calling the function f), or just the definition of the function itself? – apnorton – 2013-12-29T20:16:54.577

1An analog clock has 12 positions for each hand, but you only give us 8. How does that work? – Kevin – 2013-12-29T20:17:13.057

@Kevin You don't have to account for the other positions. That diagram shows you all the possible configurations of either hand. – Dan Prince – 2013-12-29T20:29:48.293

@anorton, just the function definition. – Dan Prince – 2013-12-29T20:33:22.653

1@DanPrince Do you want the / position to refer to 1 o'clock or 2 o'clock? (and similarly for all the rest of the diagonals) – apnorton – 2013-12-29T20:33:24.313

1@anorton 1/5, 5/25, 7/35, 11/55 – Dan Prince – 2013-12-29T20:38:34.897

This challenge is awesome x 9. However I think it's too bad that there are penalties for using many times the same language. Can you please precise what you mean in the trophies "Snakes on a Plane", "Good Parts" (do we need to write a lot of code to win those?) and "Unicycling Dwarf Magic" (what are extensions?). Thanks – xem – 2013-12-29T20:50:15.053

The 10% penalty applies to the entire score, or only to those submissions that use that language? Also, are these additive (100, 110, 120...), or multiplicative (100, 110, 121...)? Can you show a narrated example? – John Dvorak – 2013-12-29T20:50:54.213

@xem extensions should refer to py, c, java, etc, which are the default file name extensions for Python, C, and Java (respectively). – apnorton – 2013-12-29T20:51:29.413

As for the curry challenge, I take it y will take no arguments, but what should g return? – John Dvorak – 2013-12-29T20:55:47.677

1Continuing on Jan's comment: I assume we only have to provide f, but not x or y. Thus, g could return anything. – apnorton – 2013-12-29T20:57:03.043

@xem, the you'll end up with a bad score if you write too much code, so the idea is to write an optimally bad amount of code, and still do well on the other challenges.

JanDvorak there is a 10% penalty for each time you use a language beyond the first time. E.g. if you use golfscript 3 times, then you'll get a 20% multiplier on your overall score. – Dan Prince – 2013-12-29T21:00:52.513

So if I make my 9 short functions in JS, I'll have a 190% penalty but I'll be running for the "good parts" trophy? What does "highest" mean in this trophy definition? Does it refer to the number of characters or the number of functions? – xem – 2013-12-29T21:02:41.510

What counts as a block in the Timber challenge? Each ASCII character is a separate block? Straight lines? – John Dvorak – 2013-12-29T21:04:32.900

All non whitespace blocks are blocks (slashes are the only exception) – Dan Prince – 2013-12-29T21:05:08.640

@xem updated the question. – Dan Prince – 2013-12-29T21:06:24.223

Can we reorder the arguments? Namely, I'd like to get the arguments in Curry for Dinner in the opposite order. – John Dvorak – 2013-12-29T21:12:13.163

Think of it almost as a booby prize. The more trophies you get, the better right? But it's hard to get the JS/Python trophies and also get low character counts, so you'd have to write an 'optimally bad amount of code' – Dan Prince – 2013-12-29T21:12:50.393

1@JanDvorak, Sorry, but people have already started. I'm happy to clarify on rules/edge-cases, but not change the actual puzzles. – Dan Prince – 2013-12-29T21:14:28.323

@DanPrince 'not able to use angle braces', can we use the ascii values of said braces? (hole 9) – Tyzoid – 2013-12-29T21:23:12.740

@Tyzoid Of course. – Dan Prince – 2013-12-29T21:23:42.930

Is it okay to count JavaScript, TypeScript, CoffeeScript, ... as separate languages? (to avoid the penalty) – xem – 2013-12-29T22:00:44.427

2Will different versions or flavours of a language be considered "different" for scoring purposes? e.g. Python 2 vs Python 3? Visual Basic vs VB.Net vs VBScript? How about supersets or near-supersets like C vs C++? Sorry for the pedantry, but this is code-golf! :-) – Darren Stone – 2013-12-30T00:14:32.050

@xem You can use one compile-to variant of another language. E.g. JS + Coffee won't get you a penalty, but JS+Coffee+Livescript will. – Dan Prince – 2013-12-30T04:45:08.067

@DarrenStone versions don't. See above comment for flavours. I'd count the VB variants as the same, but C and C++ as different. – Dan Prince – 2013-12-30T04:48:03.427

1@DanPrince are the hands on you clock backwards? The minute hand is generally the larger of the two. (my implementation is trivially changed by this, but I'd like to get it right) – Tyzoid – 2013-12-30T06:06:14.040

@Tyzoid my bad. Typo. – Dan Prince – 2013-12-30T06:36:57.890

Task 4: define "grid", constraints on random range. Task 5: define "grid", what about multiple occurrences of the symbol? Task 6: are we required to reverse engineer this format? How flexible is it (with respect to signs, slashes, padding, etc)? Task 7: what does it mean to "output a list"? Return it? Print it? What assumptions can be made about the padding in the input file? – Peter Taylor – 2013-12-30T13:55:37.937

Task 8: what is the "root" of a slash? Which positions touch it? Task 9: What is "Hacker News"? What is the ordering on its stories? Must the output file be valid? If so, to which standard? Does "each title is contained within a h1 element" mean <h1>Title 1Title 2...Title 20</h1>? – Peter Taylor – 2013-12-30T13:57:29.913

Task 4: Rectangular data structure with a random height and width. Task 5: Any occurrence. Task 6: No you aren't. Look at the example diagram and extrapolate. Task 7: Return it. Task 8: Look at the example diagrams, the root is bottom. E.g. a \ attaches this way ->, whereas a / attaches this way <-. Task 9: Google it. No, but it must be able to display in a popular browser. No, it means each element in it's own h1 tag. – Dan Prince – 2013-12-30T14:05:05.993

You've managed to not answer most of the questions. – Peter Taylor – 2013-12-30T16:04:12.907

And everyone else has managed to do it without. This is a code golf. Use your imagination and sense of fun. – Dan Prince – 2013-12-30T16:32:45.227

Unicycling Dwarf Magic: Does it have to be ONE word? Is that even possible? :) – Christian Palmstierna – 2013-12-30T19:21:30.497

@CPX Seven source code extensions is possible, at least: hs lua b s el om py => blasphemously. If one allows .ii ("gcc pre-processed C++ source code") it's possible with 9. You don't happen to have a good list of programming language file extensions around, do you? – FireFly – 2013-12-30T20:19:04.833

Ok, it's definitely possible. I'll attempt a solution, but it'll take a while since I'll have to learn & find implementations for some... interesting languages. Here's a useful tip: the E programming language gets you a much-needed vowel.

– FireFly – 2013-12-30T21:21:26.690

1Can you clarify what you mean by "you only need to submit the function"? Can we exclude imports/includes from the character count? What about code outside the function, or even separate functions? – grc – 2013-12-31T01:54:00.443

This is OT to me as both not a good fit for the SE model (out-of-band trophies, multiple mostly independent sub-answers per answer) and likely to generate copypaste-debate as the per-language and per-task shortest converge. – J B – 2013-12-31T12:43:56.610

Answers

11

Score: 4651

2907 + 60% penalty

1. GolfScript - 14 characters

{*}:a;lligator

Usage: c n a e.g. "test" 3 a -> testtesttest

star Happy Gilmoore

2. Python - 72 characters

def f(t,s,n,p=-1):
 while n:p=t.find(s,p+1);n-=1 if p+1 else n
 return p

3. Javascript - 255 characters

/*
Curry for Dinner

f(x:function, y: function) -> g Where g is a function that will call y, n times; where n is the return value of x
*/
function f(x, y) {
    var g = function() {
        var n = x();
        for (var i = 0; i < n; ++i) {
            y();
        }
    };
    return g;
}

star Bunker star Good Parts

4. Python - 132 characters

from random import randrange as r
def f(p):l=range(r(9));open(p,'w').writelines([''.join([chr(r(94)+33)for _ in l])+'\n'for _ in l])

5. Python - 89 characters

def f(p,c):
 for y,d in enumerate(open(p).readlines()):
  x=d.find(c)
  if x+1:return x,y

6. Python - 189 characters

def f(l):
 for i in 0,1:
  for n,u in enumerate(l):
   o=l[n+1] if len(l)>n+1 else id 
   if i:print u,' '*4,
   elif o!=id:print' /'+('+' if o-u>0 else '')+str(o-u)+'sers'*0+'\\ ',
  print

7. Python - 1727 characters

def f(p):
    lines = open(p).read().split('\n')

    # preprocess lines to ensure correct format
    if len(lines) < 5:
        for i, line in enumerate(list(lines)):
            if 'o' in line:
                if i == 0:
                    lines.insert(0, ' ' * 5)
                    lines.insert(0, ' ' * 5)
                elif i == 1:
                    lines.insert(0, ' ' * 5)
        while len(lines) < 5:
            lines.append(' ' * 5)

    # find characters that can only be the hour hand
    for i, line in enumerate(lines):
        if i == 0:
            if '\\' in line:
               hour = 11
            elif '|' in line:
                hour = 12
            elif '/' in line:
                hour = 1
        elif i == 2:
            if '--o' in line:
                hour = 9
            elif 'o--' in line:
                hour = 3
        elif i == 4:
            if '/' in line:
               hour = 7
            elif '|' in line:
                hour = 6
            elif '\\' in line:
                hour = 5

    # find characters that might represent the minute hand
    possible_minutes = []
    for i, line in enumerate(lines):
        if i == 1:
            if '\\' in line:
                possible_minutes.append(55)
            if '|' in line:
                possible_minutes.append(0)
            if '/' in line:
                possible_minutes.append(5)
        elif i == 2:
            if '-o' in line:
                possible_minutes.append(45)
            if 'o-' in line:
                possible_minutes.append(15)
        elif i == 3:
            if '/' in line:
                possible_minutes.append(35)
            if '|' in line:
                possible_minutes.append(30)
            if '\\' in line:
                possible_minutes.append(25)

    HOUR_MINUTES = {
        12: 0,
        1: 5,
        3: 15,
        5: 25,
        6: 30,
        7: 35,
        9: 45,
        11: 55,
    }

    # remove minute hand that is actually hour hand
    if len(possible_minutes) > 1:
        not_minute = HOUR_MINUTES[hour]
        if not_minute in possible_minutes:
            possible_minutes.remove(not_minute)

    assert(len(possible_minutes) == 1)
    minute = possible_minutes[0]

    h, m = hour, minute          
    return [h, m]

star Snakes on a Plane

8. Python - 226 characters

def f(p):
 e=set;q,t=e(),True
 for l in open(p).readlines():
  r,b,q=e(q),e(),e()
  for i,c in enumerate(l):
   if c.strip():b.add(i);q.add(i-1 if c == '/' else i+1 if c == '\\' else i)
  if not r.issubset(b):t=False
 return t

9. Python - 203 characters

import urllib
def f(s,r,p):f,l,g=open(p,'w'),'\74','\76';[f.write(l+'h1'+g+t.replace(s,r)+'h1'+g)for i,t in enumerate(urllib.urlopen('http://x.co/3WYln').read().split('title'+g))if(i in range(2,42))&i%2]

AsksAnyway

Posted 2013-12-29T19:52:05.340

Reputation: 281

What does the comment "#alligator" have to do with the code #1? It seems to be included in the word count for some reason. – Dhara – 2013-12-30T12:06:25.530

1@Dhara It is for the Happy Gilmoore trophy: "Shortest solution that has the word 'alligator' in the code." – PhiNotPi – 2013-12-30T12:35:55.470

#9 uses angle braces (i<i<42), or are they allowed as long as you only use them as operators? – Christopher Creutzig – 2013-12-30T13:06:54.437

@ChristopherCreutzig Fixed thanks. – AsksAnyway – 2013-12-30T13:17:17.497

7

Score: 1320

I've plenty to do to improve this score... Oh well, at least I avoided repeated-language penalties. :-)

1. Python (21 chars)

def f(c,n):print(c*n)

The "obvious" solution.

2. ECMAScript 6 (47 chars)

f=(t,s,n)=>t.split(s).slice(0,n).join(s).length

Finds the index in a bit of an unconventional way, by counting the length of the substring before it.

3. J (12 chars)

f=:2 :'v^:u'

The built-in conjunction ^: raises a function to a power (i.e. repeats a function a given number of times). That is, f^:3 y = f (f (f y))). However, it's overloaded to alos accept functions rather than integers, in which case it runs the function on the input to get the number of repetitions. Unfortunately we need to flip the operands for the task, otherwise we'd have the consise answer f=:^:.

4. C (95 chars)

#include <stdio.h>
#include <stdlib.h>

f(char*p){FILE*f=fopen(p,"a");for(int n=rand(),y=n*n;y--;y%n||putc(10,f))putc(rand()%94+32,f);}

This task leaves quite a bit of room for interpretation and abuse: is it okay to just output a random printable ASCII character and say it's a randomly-dimensioned rectangle with dimensions from the set {1}? Probably not. Anyway, I went with plain rand() but in reality you probably want to add %9 or something if you want to test it. On my linux box I didn't have to flush the file in order for it to be written (I guess it flushes automatically on program exit), but I'm pretty sure you have to flush it to be standards-compliant, so feel free to add fflush(f); to the count here.

5. Haskell (100 chars)

import Control.Arrow
import Data.List
import Data.Tuple
import Control.Applicative

h p c=head.filter(p c.snd).zip[1..]
g c=swap.(id***fst.h(==)c).h elem c.lines
f p c=g c<$>readFile p

I like the repeated pattern between finding the row and the column (abstracted via h).

6. Lua (261 chars)

function f(s,m,y,...)if s and m then for i,v in pairs(m)do
io.write(v,(" "):rep(#tostring(s[i])))end print()elseif s then
r=unpack f(s,{"",f(trouse,r(s))})f({f(nil,r(s))},s)elseif y then
return ("/%s%d\\"):format(m<y and"+"or"-",math.abs(m-y)),f(s,y,...)end end

Makes use of multiple return values and recursion to deal with computing the differences. It cost me a few characters to match the sample output exactly (adding the right amount of spaces everywhere).

7. Go (307 chars)

func f(p string)[]int{var l[]string
g,_:=os.Open(p)
H,M,s,m:=0,0,bufio.NewScanner(g),[][]int{{-1,-1,11},{-1,0,12},{-1,1,1},{0,-1,9},{0,1,3},{1,-1,7},{1,0,6},{1,1,5}}
for s.Scan(){l=append(l,s.Text())}
for _,a:=range m{if l[2+a[0]*2][2+a[1]*2]!=' '{M=a[2]}
if l[2+a[0]][2+a[1]]!=' '&&(H==0||M!=a[2]){H=a[2]}}
return[]int{H,M}}

Could probably be golfed a lot more; I barely know Go.

8. CoffeeScript (+ node.js) (223 chars)

f=(p)->
 a=require('fs').readFileSync(p).toString().split "\n"
 U=(i,j)->a[i]?[j]and a[i][j]==' '
 for l,i in a
  for c,j in l
   m =
    "/":[i+1,j-1]
    "\\":[i+1,j+1]
    a:[i+1,j]
   return if U.apply(0,m[c]or m.a)
 1

A bit of a cheap-shot since I already have JS. Oh well. Returns a falsy value (namely, undefined) or a truthy value (namely, 1) to indicate the answer.

9. Bash (254 chars)

f(){
curl https://news.ycombinator.com/rss|
awk -Ftitle '{OFS="h1\76\n\74h1";ORS="";print substr(OFS,4);print$2,$4,$6,$8,$10,$12,$14,$16,$18,$20,$22,$24,$26,$28,$30,$32,$34,$36,$38,$40;print substr(OFS,0,3)}'|
while read l;do echo ${l//$1/$2};done|
tee $3
}

(Newlines after pipes added for readability.) Working around the restrictions with the shell was fun. I realise there's probably a better way to do $2,$4,$6,..., but this was what I came up with anyway.

FireFly

Posted 2013-12-29T19:52:05.340

Reputation: 7 107

1Is there any reason why you haven't included imports/includes in the character count? Otherwise, great work! – grc – 2013-12-31T00:47:38.210

1Oh yeah, I forgot to mention that. Since the question emphasises that "you only need to submit the function" I was thinking it'd be fair to ignore the cost of including standard libraries. – FireFly – 2013-12-31T01:05:46.937

For hole 1 f=str.__mul__ – Snakes and Coffee – 2014-01-12T22:27:25.953

@SnakesandCoffee that doesn't print it to stdout, unfortunately. :( – FireFly – 2014-01-12T22:34:05.290

5

Score: 1,394.4

996 characters + 40% penalty

1. Greenway - Haskell, 19 chars

f c n=replicate n c

Usage:

> f "hello" 5
["hello","hello","hello","hello","hello"]

2. Rough - PHP, 72 chars

<?
function f($t,$s,$n){for($i=-1;$n--;$i=strpos($t,$s,++$i));return$i;}

3. Curry - JavaScript 1.8, 45 chars

f=function(x,y)function(){for(i=x();i--;)y()}

4. Spew - J, 43 chars

f=:3 :'((33+?(1+?2#100)$1#93){a.)fwrites y'

Usage:

f 'file.txt'

5. Treasure - J, 64 chars

f=:4 :0
a=.freads x
b=.1+a i.u:10
c=.a i.y
d=.<.c%b
e=.d,c-b*d
)

Usage:

'file.txt' f 'c'

6. Bridge - Python, 166 chars

def f(l):J=''.join;t=map;r=lambda n:' '*len(n);s=t(str,l);o=['/%+d\\'%(y-x)for x,y in zip(l,l[1:])];print J(t(J,zip(t(r,s),o)))+'\n'+J(t(J,zip(s,t(r,o)+['users'*0])))

7. Time - Python, 205 chars

def f(p):
 s=open(p).read();a=[s[:12],s[18:],s[11:15],s[15:18]];z=[0]*3
 for l in(0,1):
  for c in'/|\\':z[a[l].count(c)]=('|/'.find(c)+6*l)%12or 12
  z[a[2+l].count('-')]=3+6*l
 print[z[1]or z[2],z[2]*5%60]

Assumes lines are space padded to be five characters wide. Uses tabs for second indentation level.

8. Timber - Python, 190 chars

def f(p):g=open(p).readlines();C='\\/ ';return all(1-[x+2>len(g[y])or g[y][x+1]in C,x<1or g[y][x-1]in C,0,' '==g[y+1][x]][C.find(g[y][x])]for y in range(len(g)-1)for x in range(len(g[y])-1))

9. Slacker - Python, 192 chars

import urllib
def f(s,r,p):F=open(p,'w');d=urllib.urlopen('http://x.co/3WYmQ').read()[37:];o,c='\x3c\x3e';exec"d=d[d.find(o+'t')+7:];F.write(o+'h1'+c+d[:d.find(o)].replace(s,r)+o+'/h1'+c);"*20

Thanks to Tyzoid for the url shortener idea.

grc

Posted 2013-12-29T19:52:05.340

Reputation: 18 565

Very impressed with your Python, lots of tricks to learn from. – AsksAnyway – 2013-12-30T13:09:35.090

1

@AsksAnyway Thanks. Be sure to check this out if you haven't already.

– grc – 2013-12-30T14:04:09.513

1Umm, surely your (1) is in J, no? Maybe you forgot to update the heading/sample run. – FireFly – 2013-12-30T15:01:58.580

@FireFly Yeah, my mistake. I updated the scoring and usage but forgot to change the actual solution. – grc – 2013-12-31T00:32:58.023

4

Had fun touching a few languages for a little bit...

Character counts obtained after removing unnecessary spaces/newlines but submission mostly kept readable. Since the question is a mix of functions and programs I included only the body of the function where required... Also some liberty taken with what the meaning of "return" is...

Total ~1719

1- Python (~20)

def f(c, n):
    print c*n

2- C (~109)

int f(char*t,char*s,int n){int i;char*q=t;int l=strlen(s);for(i=0;i<n;++i){t=strstr(t, s)+l;}return(t-q-l);}

Readable version:

#include <string.h>

int f(const char *t, const char *s, int n)
{
  int i;
  char *start = t;
  int l = strlen(s);
  for(i = 0; i < n; ++i)
  {
    t = strstr(t, s) + l;
  }
  return(t - start - l);
}

3- Javascript (~56)

function(x, y) {return function() {for(i=0; i<x(); i++) y();}}

4- Rexx (~136)

f: Procedure
  Parse arg p
  w = random(1, 9)
  h = random(1, 9)
  Do y = 1 to h
    Do x = 1 to w
      Call CHAROUT p, d2c(random(32, 99))
    End
    Call LINEOUT p, ""
  End

5- Scala (~290)

def f(p: String, c: Char) {
  def sc(w: String, c: Char, x: Int, y:Int ): Boolean =
    {
      if(w.isEmpty) false else
      if(w.head==c) {println(x, y); true} else sc(w.tail, c, x+1, y)
    }
  def sr(w: Array[String], c: Char, x: Int, y: Int)
  {
    if(!sc(w.head, c, 0, y)) sr(w.tail, c, 0, y+1)
  }
  sr(io.Source.fromFile(p).mkString.split('\n'), c, 0, 0)
}

6- C++ (~355)

void b(list<int> l) // trouser+s
{
  auto i = l.begin();
  auto j = i;
  j++;
  list<int> d;
  while(j!=s.end()) d.push_back(*j++ - *i++);
  j = d.begin();
  ostringstream o[2];
  for(auto i : l)
  {
    while(o[0].tellp()!=o[1].tellp()) o[1] << " ";
    o[1] << i;
    if(j != d.end())
    {
      while(o[0].tellp()!=o[1].tellp()) o[0] << " ";
      o[0] << "/" << (*j>=0 ? "+" : "") << *j++ << "\\";
    }
  }
  cout << o[0].str() << endl << o[1].str() << endl;
}

7- Go (~301)

Note this requires the clock to be padded (i.e. all lines are same length).

func f(p string)(h int,m int) {
  var a=[8]int {0, 2, 4, 12, 16, 24, 26, 28}
  var b=[8]int {7, 8, 9, 13, 15, 19, 20, 21}
  var d=[8]int {11, 12, 1, 9, 3, 7, 6, 5}
  h=9
  c, e := ioutil.ReadFile(p)
  if e==nil {
    for i:=range a {
      if c[a[i]]>32 {
        m=i
      }
    }
    for i:= range b {
      if c[b[i]]>32 {
        if i!=m {
          h=i
        }
      }
    }
    if h==9 {
      h=m
    }
    h=d[h]
    m=d[m]*5%60
  }
  return
}

8- Ruby (~259)

def f(p)
  a,b = File.read(p).split(/\n/).reverse,Hash.new(1)
  a.each_with_index {
    |l,i|
    l.split("").each_with_index {|k,j|
      case k
        when ' '
          b[j] = 0
        when '/'
          b[j] = b[j]|b[j-1]
        when '\\'
           b[j] = b[j]|b[j+1]
      end
      unless k==' '
        if b[j]==0
          return 0
        end
      end
    }
  }
  return 1
end

9- bash/Unix hack (~193)

wget -qO - http://news.ycombinator.com/rss | tr "\074\076" "\n" | grep -B1 /title | awk 'NR % 3 == 1' | head -21 | tail -20 | sed 's/$1/$2/' | awk '{ print "\074h1\076" $0 "\074/h1\076"}' > $3

Guy Sirton

Posted 2013-12-29T19:52:05.340

Reputation: 551

1Nice, but your #9 uses angle braces, which is against the rules for that hole. – Rik Smith-Unna – 2013-12-30T00:57:51.387

@RichardSmith: Thanks... I'll have to fix that one. – Guy Sirton – 2013-12-30T00:59:02.400

1Careful on hole #3, there is no guarantee that x() will return the same number on each function call! – Tyzoid – 2013-12-30T06:12:41.887

@Tyzoid: I was considering capturing it... You're correct that's my assumption/interpretation of the spec. – Guy Sirton – 2013-12-30T06:54:51.203

4

Edit: Think I'll just submit this as is: 1290 total, no language repeats.

Greenway, C# 53

void g(string s,int n){while(n-->0)Console.Write(s);}

I decided to swap languages with #1 and #9. Totally worth 30 here for hundreds later.

Somewhere In The Rough, Python 59

I really shouldn't have used up such a good language on an easy problem. Also, how is this not part of any language's indexOf family of functions? I seem to always need this...

def f(t,s,n):return sum(map(len,t.split(s))[:n+1])+n*len(s)

Curry For Dinner, Lisp 61

I haven't touched lisp since that one week in college....

(defun f (c g)(loop for i from 1 to(funcall c)do(funcall g)))

Spew, Bash/shell utils 102

My bash-foo was never that good to begin with. I'll fiddle with this one later. BTW if you want it to finish faster, switch it over to /dev/urandom.

f(){
c=$(($RANDOM%9+9))
for i in $(seq $c);do
echo `tr -cd [:print:]</dev/random|head -c$c`>>$1
done
}

Treasure Hunt, C 113

Probably one of the more C friendly problems. I interpreted "return two integers" as take a return array pointer as an argument. Warnings? What warnings? An int* is just as good as a FILE* =p.

void f(int*p,int c,int*r){int*f,t;*r=r[1]=0;f=fopen(p,"r");while(c-(t=fgetc(f))){*r=t-'\n'?*r+1:0;r[1]+=*r?0:1;}

Bridge on the River Kwai, Perl 207

I started learning perl while writing this one. (Better late than never!) I came into this wanting to do regex heroics, so I form the string as both layers of the bridge together, then use regexes with space replacements to form the two different lines.

sub f{@trouse=0..$#_-1;foreach $i(@trouse){$r.=sprintf("%d/%+d\\",$_[$i],$_[$i+1]-$_[$i])}$r.=$_[$#_]."\n";print$r=~s/(^|\\)(\d+)(\/|$)/$1.' 'x length($2).$3/egr;print$r=~s/(\/[+-]\d+\\)/' 'x length($1)/egr}

Time Flies When You're Playing Golf, Java 297

You can only do so much to make java terse... It assumes the clock is space padded so each line is 5 spaces long.

public boolean p(int r,int m,String s){int c[]={1,1,0,-1,-1,-1,0,1};return s.charAt(6*c[(r+6)%8]*m+14+c[(r)%8]*m)!=' ';}
public int[]time(String c){int h=9,m=0,t[]={3,5,6,7,9,11,12,1};for(int i=0;i<8;i++)if(p(i,1,c))if(p(i,2,c))m=i;else h=i;if(h==9)h=m;m=(t[m]*5)%60;h=t[h];return new int[]{h,m};}

Timber! Javascript 201

It runs in chrome's console. I make no guarantees elsewhere =p. It requires that the lines be space padded out to the length of the longest line. I feel like this is a reasonable request of ASCII art.

function f(s) {s=s.split("\n")
d={};m={'/':-1,'\\':1};r=1
s.forEach(function(x){t={}
for(i=0;i<x.length;i++){if(x[i]!=' '){j=m[x[i]]?i+m[x[i]]:i
t[j]=1}}for(n in d){if(x[n]==' '){r=0}}d = t})
return r}

Slacker News, Ruby 197

def s(f,s,t)
l=60.chr
r=62.chr
IO.write(f,l+"h1"+r+URI.parse("https://news.ycombinator.com").read().split('mhead')[0,20].map{|x|x[0,x.length-19].split(r).last.sub(s,t)}.join(l+"/h1#{r+l}h1"+r))
end

Sprigyig

Posted 2013-12-29T19:52:05.340

Reputation: 51

Not only is this a great answer, it also makes for a great read. Good job! – Dan Prince – 2013-12-30T13:45:56.967

Thanks, I imagine it is a little less interesting now that I swapped ruby and C#. No more ranting on .Net's insane string split =) – Sprigyig – 2013-12-31T03:20:36.883

2

Not really here to golf, but here's some Tcl, since the language needs more love:

set holes {
    greenway
    rough
    curry
    spew
    hunt
    bridge
    time
    timber
    slacker
}

proc greenway {c n} {
    puts [string repeat $c $n]
}

proc rough {t s n} {
    set i [string first $s $t] ;# a bit wet
    while {[incr n -1]} {
        incr i [string first $s $t $i]
    }
    return $i
}

proc curry {x y} {
    set n [uplevel 1 $x]
    set body [string repeat "$y;" $n]
    return [list apply [list args $body]]
}

proc spew {p} {
    set w [expr {int(rand()*80)}]
    set h [expr {int(rand()*80)}]
    set f [open $p w]
    for {set y 0} {$y<$h} {incr y} {
        set ln ""
        for {set x 0} {$x<$h} {incr x} {
            append ln [format %c [expr {int(rand()*96+32)}]]
        }
        puts $f $ln
    }
    close $f
}

proc hunt {p c} {
    set f [open $p r]
    set y 0
    while {[gets $f line]>=0} {
        set x [string first $f $c]
        if {$x != -1} {
            return [list $x $y]
        }
        incr y
    }
}

proc bridge {l} {
    set l [lassign $l m]
    set top ""
    set btm $m
    foreach n $l {
        set t "/[expr {$n>$m?"+":""}][expr {$n-$m}]\\"
        append top "[string repeat \  [string length $m]]$t"
        append btm "[string repeat \  [string length $t]]$n"
        set m $n
    }
    # trousers
    return $top\n$btm
}

proc time {p} {
    set f [open $p r]
    while {[gets $f line] >= 0} {
        set line [format %-.5s $line]
        lappend c [split $line {}]
    }
    close $f
    foreach {x y h} {
        -1 -1  0
         0 -1  1
         1 -1  3
         1  0  5
         1  1  6
         0  1  7
        -1  1  9
        -1  0 11
    } { 
        set 2x x; incr 2x $x
        set 2y y; incr 2y $y
        if {[lindex $c $2y $2x] != " "} {
            set hh $h
        } elseif {[lindex $c $y $x] != " "} {
            set mm $h
        }
    }
    if {![info exists $mm]} {
        set mm $hh
    }
    set mm [expr {$mm*5}]
    if {$hh == 0} {set hh 12}
    list $hh $mm
}

proc timber {p} {
    set f [open $p r]
    set must {}
    while {[gets $f line] >= 0} {
        set line [format %-.5s $line]
        foreach i $must {
            if {[string index $line $must] eq " "} {
                close $f
                return false
            }
        }
        set must {}
        set i 0
        foreach c [split $line] {
            switch $c {
                "\\" {lappend must [expr {$i+1}]}
                "/"  {lappend must [expr {$i-1}]}
                " "  { }
                default  {lappend $must $i}
            }
            incr i
        }
    }
    close $f
    return true
}

proc slacker {s r p} {
    package require tdom
    set f [open $p w]
    set h [::http::geturl https://news.ycombinator.com/]
    set html [string trim [::http::data $h]]
    ::http::cleanup $h
    set dom [dom parse $html]
    lappend map , [string index $html 0]
    lappend map . [string index $html end]
    set root [$dom documentElement]
    foreach n [$root selectNodes {//td[@class=title]/a}] {
        set x [$n text]
        set x [string map [list $s $r] $x]
        puts $f [string map $map ",h1.$x,/h1."]
    }
    close $f
}

Mostly untested because writing these procs in half an hour is much more interesting than trying to properly engineer golf code. Enjoy!

wackadoo

Posted 2013-12-29T19:52:05.340

Reputation: 21

2

Only had time to work on 1/2 of these. You seem to want them in the form of a function and not a one liner. So all of these are functions. Testing code below the function. In Perl.

Greenway:

sub f{print$_[0]x$_[1]}

#test
&f("abc",5);

Rough:

sub f{$i=-1;$n=$_[2];do{$i=index$_[0],$_[1],$i+1;$n--}while($n>0 && $i>-1);print$i+1}

#test
&f("abcefgacefgabcefgabcefgabcefg","cef",4);

Curry:

use Sub::Curried;
curry f($x,$y){$q=0;foreach(1..&$x){$q=&$y};return $q;}

#test
sub fy { return 1;}
sub fx { return 10;}
print&f(\&fx,\&fy);

Spew:

use Crypt::PRNG qw(random_string_from irand);
sub f{open($o,">$_[0]");$m=(irand)%10+1;map{printf $o "%s\n",random_string_from(['A'..'z'],$m)}(1..$m)}

#test
&f('/tmp/t');

Treasure:

sub f{open($i,"<$_[0]");$x=$y=0;@l=<$i>;while($y<=$#l){$x=1+index$l[$#l-$y],$_[1];@a=($x,$y+1)if($x);$y++;}return\@a}

#test
@b=@{&f('/tmp/t','f')};
print join(",",@b);

I'll work on 6-9 tomorrow.

Joe

Posted 2013-12-29T19:52:05.340

Reputation: 61

2

WIP. Note, character counts may be off due to '\n' and wc

[1 Greenway] Mindf*ck, 54 characters

>>+[+>,-]<[<]>,<<++++++++[>>------<<-]>>[>[.>]<[<]>-]

Usage: Once the code is written, input your string, and terminate your string with a ^a (ctr+a), then immediately after, enter your number.

One caveat: the number given must only be from 0-9 (if you wish a larger one, the ascii value-48 of whatever character you input will be used as n)

Screenshot:

Screenshot

[3 Curry for Dinner] Javascript, 59 characters

function f(x,y){return function(){n=x();while(--n!=0)y();}}

[4 Spew] BASH, 56 characters

f(){ dd if=/dev/urandom of="$1" count=$((RANDOM%30+2));}

[7 Time Flies When You're Playing Golf] C, 334 Characters (412 with macro definition)

#define E(A) else if(s[A]==
#define G(A) else if(A)m=
#define M(A) &&m!=A)h=A
int (*f(char* s)){short h=0,m=0;if(s[0]=='\\')m=11;G(s[2]=='|')12;G(s[4]='/')1;G(s[11]=='-')9;G(s[15]=='-')3;G(s[22]=='/')7;G(s[24]=='|')6;G(s[26]=='\\')5;if(s[7]=='\\'M(11);E(8)'|'M(12);E(9)'/'M(1);E(12)'-'    M(9);E(14)'-'M(3);E(18)'/'M(7);E(19)'|'M(6);E(20)'\\'M(5);int* i=malloc(sizeof(int)*2);i[0]=(h==0)?m:h;i[1]=m*5;return i;}

Note: this function returns a pointer to a two dimensional integer array, formatted like so: {3, 55} (for a clock position of hour on 3, minute on 11)

[9 Slacker News] PHP, 246 characters

function f($a,$b,$c){$t=file_get_contents("http://x.co/3WQoY");$g=explode('d class="t',$t);$f=fopen($c,"w");for($i=1;++$i!=count($g)-10;){$e=explode("\x3e",$g[$i]);fwrite($f,"\x3ch1\x3e".str_replace($a,$b,s    ubstr($e[2],0,-3))."\x3c/h1\x3e\n");}}

Seperate/Original implementation in BASH+AWK, 218 characters

f(){ wget -qO- x.co/3WQoY|grep "e_"|awk '{n=split($0,a,"d class=\"t");for(q=1;++q!=n-10;){split(a[q],b,"\x3e");m=substr(b[3],0,index(b[3],"\x3c/")-1);gsub("'"$1\",\"$2"'",m);print "\x3ch1\x3e"m"\x3c/h1\x3e"    }}'>"$3";};

Tyzoid

Posted 2013-12-29T19:52:05.340

Reputation: 692

2

1654

1. Greenway (Haskell - 37)

f x y=do print(concat(replicate x y))

2. Somewhere in the Rough (Mathematica - 43)

f[t_,s_,n_]:=StringPosition[t, s][[n+1, 1]]

3. Curry for Dinner (Lisp - 58)

(defun f(x y)(lambda()(dotimes(c(funcall x))(funcall y))))

4. Spew (Matlab/Octave - 83)

function x(f)
    save f arrayfun(@char,randi(255,randi(255),randi(255)))
endfunction

5. Treasure Hunt (C - 176)

char* f(char* s,char c){FILE* n;char* r;int i=0,j=0,k=0;n=fopen(s,"r");while(!feof(n)){k=fgetc(n);if(k==(int)c)break;j++;if(k=='\n'){i++;j=0;}}sprintf(r,"%d %d",i,j);return r;}

6. Bridge on the River Kwai (Ruby - 192)

def f(l)
    trouse="\n%s"
    rs = l[0].to_s
    for i in 1..l.length-1
        s = "/%+d\\"%(l[i]-l[i-1])
        print " "*l[i-1].to_s().length+s
        rs += " "*s.length+"%d"%l[i]
    end
    puts trouse%rs
end

7. Time Flies When You're Playing Golf (Node.js - 406)

function f(n){var g,h,m,q;fs.readFile(n,'ascii',function(e,d){l=d.split('\n');g=function(x,y){try{return l[x][y].trim()&&1;}catch(e){return 0;}};h=g(0,0)*11||g(0,2)*12||g(0,4)*1||g(2,0)*9||g(2,4)*3||g(4,0)*7||g(4,2)*6||g(4,4)*5;m=(g(1,1)&&h!=11)*55||(g(1,2)&&h!=12)*0||(g(1,3)&&h!=1)*5||(g(2,1)&&h!=9)*45||(g(2,3)&&h!=3)*15||(g(3,1)&&h!=7)*35||(g(3,2)&&h!=6)*30||(g(3,3)&&h!=5)*25||h*5%60;return [h,m];});}

8. Timber! (Go - 329)

func f(p string)bool{
    x,_:=ioutil.ReadFile(p)
    b:=strings.Split(string(x),"\n")
    for j:=0;j<len(b)-2;j++{
        for i:=0;i<len(b[j]);i++{
            r,o:=1,0
            switch string(b[j][i]){
            case " ": continue
            case "/": r,o=0,-1
            case "\\": r,o=0,1
            }
            if i+o<len(b[j]) && b[j+r][i+o]==' ' {
                return false
            }
        }
    }
    return true
}

9. Slacker News (Python - 330)

def f(s,r,p):
    w=urllib2.urlopen('http://news.ycombinator.com')
    a=[l.get_text() for l in BS(w).body("a") if l.find_parent("td", class_="title")]
    t=lambda x:u"\x3c{}\x3e{}\x3c/{}\x3e".format(x,'{}',x)
    m=''.join(t("h1").format(l.replace(s,r)) for l in a[:20])
    with open(p,'w') as h:
        h.write(t("html").format(m).encode('utf8'))

C Gearhart

Posted 2013-12-29T19:52:05.340

Reputation: 21

1

I’m a cheater & I ain’t played all 9 holes … yet. Nonetheless, here’s my hole 8, “Timber” solution in Perl (149 char).

One of my coworkers put this up as as a challenge at work. We’ve been having fun with it, especially me, since I have the lowest par solution so far!

Our rules were that it had to be a stand alone script that outputted true or false followed by a newline to STDOUT, and that no “shebang” was OK.

Below is the “minified” solution. I also put up a “gist” of the same that includes non-“minified” code & (often tortuously long) explanations of the reasoning behind my approach.


$r=tru;open F,pop;while(<F>){y/0/6/;s/^|\s|$/0/g;s#\\(?=0)|(?<=0)/|[^\\/0]#6#g;@n=split//;for(0..@n){!$n[$_]&&$l[$_]==6?$r=fals:1}@l=@n;}print$r,'e
'

roosto

Posted 2013-12-29T19:52:05.340

Reputation: 111

0

I am too lazy to modify it according to the competition rules Meh, but it works fine...

from numpy import *
import sys

def greenway(c,n):
    print c*n

def somewhereintherough(t,s,n):
    i=-1
    count=0
    while(count<n):
        i = t.find(s,i+1)
        count+=1
    return i

def curryfordinner(x,y):
    def g():
        for i in range(x()):
            y()
    return g

def spew(p):
    f = open(p,'w')
    n = random.randint(1,28)  
    for i in range(n):
        if(i>0):
            f.write('\n')
        str1 = ''.join([chr(random.randint(32,126)) for _ in range(n)])
        f.writelines(str1)
    f.close()
    print "Grid size: ",n,'x',n

def treasurehunt(p,c):
    f = open(p,'r')    
    arr = f.readlines()
    n = len(arr)
    f.close()
    f = open(p,'r')
    found=False
    for i in range(n):
        line = f.readline()
        #print line
        loc = line.find(c)
        if(loc!=-1):
            print c,"found in",p,"at",i,loc
            found=True
            break
    if(not found):
        print c,"not in",p
    f.close()

def bridgeontheriverkwai(l):
    str_list = []
    for i in range(len(l)-1):
        sign = '+' if l[i+1]-l[i]>0 else '-'
        str_1 = '/'+sign+str(abs(l[i+1]-l[i]))+'\\'
        sys.stdout.write(' '*(len(str(l[i])))+str_1)
        str_list.append(str_1)
    print
    for i in range(len(l)):
        if i<len(l)-1:
            print str(l[i])+' '*(len(str_list[i])-1),
        else:
            print l[i]

def timeflieswhenyoureplayinggolf(p):
    f = open(p,'r')
    #clock = [[0]*5,[0]*5,[0]*5,[0]*5,[0]*5]
    line1 = f.readline()
    line2 = f.readline()
    line3 = f.readline()
    line4 = f.readline()
    line5 = f.readline()
    h = 0
    m = 0
    if line1.find('\\')!=-1:
        h = 11
        m = 55
    elif line1.find('|')!=-1:
        h = 12
        m = 0
    elif line1.find('/')!=-1:
        h = 1
        m = 5
    elif line5.find('/')!=-1:
        h = 7
        m = 35
    elif line5.find('|')!=-1:
        h = 6
        m = 30
    elif line5.find('\\')!=-1:
        h = 5
        m = 25
    elif line3[4]=='-':
        h = 3
        m = 15
    elif line3[0]=='-':
        h = 9
        m = 45

    if line2[1]=='\\' and h!=11:
        m = 55
    elif line2[3]=='/' and h!=1:
        m = 5
    elif line3[1]=='-' and h!=9:
        m = 45
    elif line3[3]=='-' and h!=3:
        m = 15
    elif line4[1]=='/' and h!=7:
        m = 35
    elif line4[3]=='\\' and h!=5:
        m = 25
    elif line2[2]=='|' and h!=12:
        m = 0
    elif line4[2]=='|' and h!=6:
        m = 30

    print h,m


def timber(p):
    f = open(p,'r')
    linecount=0
    line_size = 0
    line = f.readline()
    while(line):
        linecount+=1
        line_size = max(line_size,len(line)-1)
        line = f.readline()
    block = array([[0]*line_size]*linecount)
    f.seek(0)
    for i in range(linecount):
        line = f.readline()
        for j in range(len(line)-1):
            if(line[j]==' '):
                block[i][j]=0
            elif(line[j]=='/'):
                block[i][j]=1
            elif(line[j]=='\\'):
                block[i][j]=2
            else:
                block[i][j]=3
    f.close()
    for i in range(linecount):
        for j in range(line_size):
            if(block[i][j]==1 and j!=0 and block[i][j-1]==3):
                block[i][j]=4
        for j in range(line_size-1,0,-1):
            if(block[i][j]==2 and j!=line_size-1 and block[i][j+1]==3):
                block[i][j]=4
    for i in range(linecount):
        for j in range(line_size):
            if(block[i][j]==3 and i<linecount-1 and block[i+1][j]==0):
                print "Unsafe Structure"
                return
    print "Safe Structure"

def slackernews(s,r,p):
    import urllib2
    response = urllib2.urlopen('https://news.ycombinator.com')
    html = response.read()
    titles_list = []
    ix = -1
    count = 0
    index_list =  []
    while(count<21):
        ix = html.find("<td class=\"title\"",ix+1)
        index_list.append(ix)
        count+=1
    for i in range(len(index_list)-1):
        line = html[index_list[i]:index_list[i+1]]
        line = line[line.find("a href"):]
        start = line.find('>')
        end = line.find('<')
        titles_list.append(line[start+1:end])
    f = open(p,'w')
    for title in titles_list:
        title = title.replace(s,r)
        f.write('<h1>'+title+'</h1>')
    print "Done writing, Check : ",p
    f.close()


greenway('test!',2)
s='this is a cat. this is a dog. dog is an animal, animal is a beast in disguise.'
t='is'
ix=somewhereintherough(s,t,8)
print ix,s[ix:]
def x():
    return 4
def y():
    print ' !y_called! '
g = curryfordinner(x,y)
g()
spew('test.dat')
treasurehunt('test.dat','a')
bridgeontheriverkwai([-7,-22,6,9])
timeflieswhenyoureplayinggolf('clock.dat')
timber('block.dat')
slackernews('a','b','slacker.html')

hrs

Posted 2013-12-29T19:52:05.340

Reputation: 101

0

Another work in progress here, and I'm at work so I'll head back later.

Greenway in Ruby (14 characters, 24 with #alligator), call with f.(c, n)

f=->c,n{p c*n}#alligator

Screenshot

Greenway

Somewhere in the Rough in CoffeeScript (38 characters)

f=(t,s,n)->t.split(s,n).join(s).length

Screenshot

Somewhere in the Rough

Curry for Dinner in JavaScript (54 characters)

f=function(x,y){return function(){for(i=x();i--;)y()}}

Screenshot

Curry for Dinner

Spew in PHP (111 characters)

This requires short_open_tag in the PHP configuration file to be enabled. Otherwise the opening delimiter should be <?php, the @ symbols are used to silence PHP_NOTICE errors that are thrown for avoiding enclosing rand in quotes, and for not explicitly declaring the $s variable. This will generate a square grid of ascii characters between 4 and 30 characters on both axis.

<? @$r=rand;$x=$r(4,30);for($i=$x*$x;--$i;){@$s.=$i%$x!=0?chr($r(33,126)):"\n";}file_put_contents($argv[1],$s);

Screenshot

Spew

Daniel Morris

Posted 2013-12-29T19:52:05.340

Reputation: 1

What is that terminal your using? – Alexander Craggs – 2014-08-23T19:11:38.433

0

First code golf! (Still a work in progress...)

1. Greenway

Language: Python 3.2.3
File size: 23 bytes
Code:

def f(c,n): print(c*n)

3. Curry for Dinner

Language: Python 3.2.3
File size: 64 bytes
Code:

def f(x,y):
    def g():
        for i in [1]*x(): y()
    return g

apnorton

Posted 2013-12-29T19:52:05.340

Reputation: 101

You will be docked points for using the same language twice, if I understood correctly. If you are just doing it for fun, no problem. – None – 2013-12-31T01:59:42.363

@user2509848 I don't know 9 golf-able languages, so I'll have to be docked some. :( Thanks for the heads up, though! – apnorton – 2013-12-31T02:01:14.620

Ruby, Perl, Golfscript, and Mathematica are often winners – None – 2013-12-31T02:02:27.937

I only know C++, with some Java and less Python 3.2.3. Nothing else but HTML and CSS (which can't be used anyway (CSS)). – None – 2013-12-31T02:03:43.283

0

1. Greenway (Python 2: 20)

def a(x,n):print x*n

Example input: a("asdf",3) -> string(asdfasdfasdf)

2. Somewhere in the Rough (Python 2: 47)

def b(t,s,n):return len(s.join(t.split(s)[:n]))

Example input: b("1,2,333,4,5,6",",",3) -> int(7)

3. Curry for Dinner (Javascript: 61)

function c(a,b){d=a();return function(){while(d){d--;b()}};};

Example input: function z(){ return 3; }; function y(){ console.log( '1' ) }; myfunc = c(z,y); myfunc(); -> logs string(1) to the console... 3 times.

As per the specs, c returns a function, and doesn't actually execute that function itself.

4. Spew (C++11: 171)

#include<fstream>
using namespace std;void d(string f){ofstream o;int i=rand()%10;int j=rand()%10;o.open(f);for(int x=0;x<i;x++){for(int y=0;y<j;y++){o.put(rand()%256);}}}

Not actually tested this, but should work.

Sumurai8

Posted 2013-12-29T19:52:05.340

Reputation: 161

0

Some indentation is left intact for readability but it was taken out when counting characters. The total is around 1227. Or not, I forgot a problem. 1486 1465 characters.

1. MIPS ASM (55 chars)

#a0 : the address of the null terminated string.
#a1 : the repetition count.
f:
li $v0,4
syscall
addi $a1,$a1,-1
bne $a1,$0,f
jr $ra

2. Scheme (52 chars)

(define (f t s n)(list-ref(string-search-all s t)n))

3. F# (39 chars)

let f x y=fun()->for i in 1..x() do y()

4. Powershell (133 chars)

Function f($p){
$r=(Get-Random)%100
$z="";for($b=$r*$r;$b -gt 0;$b--){$z+=[char](33+(Get-Random)%94);if($b%$r -eq 1){"$z">>$p;$z=""}}
}

5. C++ (184 152 chars)

#include <istream>
#include <string>
int*f(std::string p,char c){int*x=new int[2]();std::ifstream i(p);for(;i>>p;x[1]++)if((x[0]=p.find(c))>0)return x;}

6. C# (291 282 chars)

static void f(List<int> l)
{
    var z = "";
    var o = l[0].ToString();
    for (int j = 1; j < l.Count;j++)
    {
        int p = l[j-1];
        int i = l[j];
        var q = "/"+(i-p<0?"":"+")+(i-p).ToString()+"\\";
        o += new String(' ',q.Length)+i.ToString();
        z+=new String(' ',p.ToString().Length)+q;
    }
    Console.Out.Write(z+"\n"+o);
}

7. Haskell (318 306 chars)

I was looking for an excuse to try out Haskell. I thought I was clever by generating the list of positions via combinations of numbers, but with the number of characters it took I could have hard coded the damn thing. Oh well. The code is atrocious but it was fun to write anyway.

edit: Fixed so it correctly returns minutes.

w i s=[s!!(j!!1)!!(j!!0)/=' '|j<-mapM(const i)[1,2],j/=[2,2]]
k[e,r](i,o,n)|i&&o=[e, n]|i&&not o=[n, r]|not$o||i=[e, r]
g s=let[h,m]=foldl k[0,0](zipWith3(\x y z->(x,y,z))(w[1,2,3]s)(w[0,2,4]s)[11,9,7,12,6,1,3,5])in let u=mod(m*5)60 in if h==0 then[m,u]else[h,u]
f p = do
  s<-readFile p
  return$g$lines s

8. Lua (259 chars)

I was surprised to find that strings didn't support array style indexing, so I had to rely on sub.

function f (p)
    s=' ' g=''
    for l in io.open(p):lines() do l=l..s:rep(#g-#l) for v=1,#g do
        d=({['/']=v-1,['\\']=v+1,[s]=0})[g:sub(v,v)] or -1
        if l:sub(v,v)==s and (d<0 or d>0 and g:sub(d,d)==s and l:sub(d,d)==s) then
            return false
        end
    end g=l end
    return true
end

9. Python (187 chars)

Thanks to grc/Tyroid for the url shortener.

import urllib2
def f(s,r,p):[open(p,'a').write('\074h1\076'+i.split("\074")[0].replace(s,r)+'\074/h1\076') for i in urllib2.urlopen("http://x.co/3WYmQ").read().split("\074title\076")[2:]]

TrevorM

Posted 2013-12-29T19:52:05.340

Reputation: 111