Skip to content

Instantly share code, notes, and snippets.

@latentflip
Forked from morganp/golf.rb
Created May 23, 2011 18:26
Show Gist options
  • Save latentflip/987222 to your computer and use it in GitHub Desktop.
Save latentflip/987222 to your computer and use it in GitHub Desktop.
L/SH/ScotRug Code Golf
g=Golf=Hash
def g.method_missing s, a
k=[]
case s.to_s[-1]
when ?1
a.reduce :*
when ?2
a.split.sort_by{|i| i[1] }*' '
when ?3
h1 1..a
when ?4
a.map { |i| i.
sub(/(man.*)/,'hat(\1)').
sub(/(dog.*)\)/,'\1(bone))').
sub 'cat','dead'
}
when ?5
a.size.times { |i| k += a.each_cons(i+1).to_a }
k
when ?6
f="fizz"
b="buzz"
(1..a).map { |s| s%3 > 0 ? s%5 > 0 ? s : b : s%15>0 ? f : f+b }
when ?7
*r=0
l,x=a
m=l
a.map {|a|
x ? x=$_ : (m+=1) == a ? r[-1]=[l,a]*'-' : r<<l=m=a
}
r
when ?8
*i=0,1
a.times { i << i[-1]+i[-2] }
i[1..-2]
when ?9
b = open(a).map {|e| e.chomp.split ', '}
g = z b
while (c,d = g.minmax_by {|e,s| s.size})[0][1].size*2 < b.size
b.select {|e,| e==c[0]}.map &:shift
b -= [k]
g = z b
end
d[0]
when ?z
a.group_by {|e,| e}
end
end
@latentflip
Copy link
Author

566

  • Hole 9:
array -= [[]]

is more efficient than

array.reject! &:empty?

@morganp
Copy link

morganp commented May 23, 2011

Hole 6 if used x<1 instead of ==0 would not have had to rearrange order.

@latentflip
Copy link
Author

@morganp Heh, good spot. D'oh.

@latentflip
Copy link
Author

549

Seriously, make this end.

@morganp
Copy link

morganp commented May 23, 2011

A step to far, but I guess all is fair in golf.

@latentflip
Copy link
Author

Added hole7 from @andrewmcdonough's repo in and back up to 617.

  • My favourite bits are:
l,*x=a;
m=l

and

r<<l=m=a
  • Also refactored method missing to check the last char instead of using a regex. Nicely obfuscates it since you have to use ?1 instead of /1/

@latentflip
Copy link
Author

615

  • Lose the brackets in final sub method on hole 4

@latentflip
Copy link
Author

614

  • Hole7: We can use
$_ #The last input line of string by gets or readline.

instead of nil since we aren't using gets/readline.

@latentflip
Copy link
Author

613

  • Pull multiple <variable>=[] into a single k=[] at top of method.

@morganp
Copy link

morganp commented May 24, 2011

I updated my rake file to this

RSpec::Core::RakeTask.new(:spec) do |spec|
  spec.rspec_opts = ["--fail-fast"]
  spec.pattern = 'spec/**/*_spec.rb'
end

So will only show first fail, faster to work through the first build. Relies on RSpec 2.1 though.

@latentflip
Copy link
Author

612

  • Hole7: Since we are just setting x to anything, we don't need the *. - with thanks to @jonmountjoy

@latentflip
Copy link
Author

606

  • Fun with parallel assignments
*e=0          #=> e = [0]
*e=0,1        #=> e = [0,1]
e, = [1,2,3]  #=> e = 1

@latentflip
Copy link
Author

602 is about as good as it gets for this route I think

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment