r/programming • • May 08 '15

Five programming problems every Software Engineer should be able to solve in less than 1 hour

https://blog.svpino.com/2015/05/07/five-programming-problems-every-software-engineer-should-be-able-to-solve-in-less-than-1-hour
2.5k Upvotes

2.1k comments sorted by

View all comments

Show parent comments

1

u/daybreaker May 08 '15

I can do it in 5 lines...

['+', '-', ''].repeated_permutation(8).each do |perm|
  sumText = ('1'..'8').zip(perm).flatten.join + '9'
  sum = eval(sumText)
  puts "#{sumText} = 100" if sum == 100
end    

:-P /codemaster

4

u/Zequez May 08 '15 edited May 08 '15

Ah dammit, that inline-if totally slipped me by. I have spent too much with JavaScript >_<.

You win this time daybreaker! YOU WIN THIS TIME!!! shakes fist in the air

Edit:

I mean, you can always do a one-liner:

['+', '-', ''].repeated_permutation(8).map{ |perm| ('1'..'8').zip(perm).flatten.join + '9' }.each{ |sumText|  puts "#{sumText} = 100" if eval(sumText) == 100 }

Or RUBIER:

['+', '-', ''].repeated_permutation(8).map{ |perm| ('1'..'8').zip(perm).flatten.join + '9' }.select{ |sumText| eval(sumText) == 100 }.each{ |sumText|  puts "#{sumText} = 100" }

Which expands to:

['+', '-', '']
  .repeated_permutation(8)
  .map{ |perm| ('1'..'8').zip(perm).flatten.join + '9' }
  .select{ |sumText| eval(sumText) == 100 }
  .each{ |sumText|  puts "#{sumText} = 100" }

Feels like cheating if it takes more than 100 chars! But it isn't! There are no rules! Yes! Besides, the Enumeration class doesn't execute until you reach the each, so you're not really iterating multiple times I think.