Take the 2-minute tour ×
Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. It's 100% free, no registration required.

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
share|improve this question
2  
@anorton < & > –  Dan Prince Dec 29 '13 at 20:15
1  
An analog clock has 12 positions for each hand, but you only give us 8. How does that work? –  Kevin Dec 29 '13 at 20:17
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) –  anorton Dec 29 '13 at 20:33
1  
@anorton 1/5, 5/25, 7/35, 11/55 –  Dan Prince Dec 29 '13 at 20:38
2  
Will 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 Dec 30 '13 at 0:14
show 35 more comments

15 Answers 15

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]
share|improve this answer
    
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 Dec 30 '13 at 12:06
    
@Dhara It is for the Happy Gilmoore trophy: "Shortest solution that has the word 'alligator' in the code." –  PhiNotPi Dec 30 '13 at 12:35
    
#9 uses angle braces (i<i<42), or are they allowed as long as you only use them as operators? –  Christopher Creutzig Dec 30 '13 at 13:06
    
@ChristopherCreutzig Fixed thanks. –  AsksAnyway Dec 30 '13 at 13:17
add comment

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.

share|improve this answer
1  
Is there any reason why you haven't included imports/includes in the character count? Otherwise, great work! –  grc Dec 31 '13 at 0:47
1  
Oh 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 Dec 31 '13 at 1:05
    
For hole 1 f=str.__mul__ –  Snakes and Coffee Jan 12 at 22:27
    
@SnakesandCoffee that doesn't print it to stdout, unfortunately. :( –  FireFly Jan 12 at 22:34
add comment

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.

share|improve this answer
    
Very impressed with your Python, lots of tricks to learn from. –  AsksAnyway Dec 30 '13 at 13:09
1  
@AsksAnyway Thanks. Be sure to check this out if you haven't already. –  grc Dec 30 '13 at 14:04
1  
Umm, surely your (1) is in J, no? Maybe you forgot to update the heading/sample run. –  FireFly Dec 30 '13 at 15:01
    
@FireFly Yeah, my mistake. I updated the scoring and usage but forgot to change the actual solution. –  grc Dec 31 '13 at 0:32
add comment

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
share|improve this answer
    
Not only is this a great answer, it also makes for a great read. Good job! –  Dan Prince Dec 30 '13 at 13:45
    
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 Dec 31 '13 at 3:20
add comment

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
share|improve this answer
1  
Nice, but your #9 uses angle braces, which is against the rules for that hole. –  Richard Smith Dec 30 '13 at 0:57
    
@RichardSmith: Thanks... I'll have to fix that one. –  Guy Sirton Dec 30 '13 at 0:59
1  
Careful on hole #3, there is no guarantee that x() will return the same number on each function call! –  Tyzoid Dec 30 '13 at 6:12
    
@Tyzoid: I was considering capturing it... You're correct that's my assumption/interpretation of the spec. –  Guy Sirton Dec 30 '13 at 6:54
add comment

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!

share|improve this answer
add comment

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.

share|improve this answer
add comment

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";};
share|improve this answer
add comment

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'))
share|improve this answer
add comment

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')
share|improve this answer
add comment

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
share|improve this answer
    
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. –  hosch250 Dec 31 '13 at 1:59
    
@user2509848 I don't know 9 golf-able languages, so I'll have to be docked some. :( Thanks for the heads up, though! –  anorton Dec 31 '13 at 2:01
    
Ruby, Perl, Golfscript, and Mathematica are often winners –  hosch250 Dec 31 '13 at 2:02
    
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)). –  hosch250 Dec 31 '13 at 2:03
add comment

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

share|improve this answer
add comment

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.

share|improve this answer
add comment

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:]]
share|improve this answer
add comment

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
'
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.