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

112

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

Ruby 7-liner:

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

Ruby bring tears to my eyes <3

Took me more than 1 hour though, I did it in JS first, which yield a much less efficient result. I won't post the JS code because the things I did to get to the result are horrific and should not be seen by mortals. Ok here it is. I know, it's bad.

Edit 1: Optimised it a bit with something I saw someone doing below, adding the permanent '9' at the end of each string.

Edit 2: Yes! As mentioned below, you can make it shorter, 4 easily readable lines:

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

Also, added underscores for convention, sorry, too much JS lately.

Also, obligatory thanks for the gold, although I feel I didn't deserved it, too many mistakes, the code could have been 4 lines from the start!

Edit 3: Ok, since someone asked, here is a version without eval, using String#to_i

['+', '-', ''].repeated_permutation(8).each do |perm|
  sum_text = ('1'..'8').zip(perm).flatten.join + '9'
  puts "#{sum_text} = 100" if sum_text.split(/(?=[+-])/).map(&:to_i).reduce(&:+) == 100
end

Edit 4: Ok, here is a version without any kind of string manipulation, all integers, no one can complain now. And still in technically 4 lines! Because I expanded the chain, so it could be just 1 line. Although I cheated with a ; inside one inject. So let's call it 4 1/2 lines and call it a day:

# The operators are:
# 0 = no operator
# 1 = + operator
# 2 = - operator
[0, 1, 2].repeated_permutation(8).each do |perm|
  sum_array = perm
    .zip(2..9) # [[0, 2], [1, 3], [0, 4], [2, 5]] etc, equivalent to 2+34-5 
    .inject([[0, 1]]) {|arr, (op, num)| op == 0 ? arr.last.push(num) : arr.push([op,num]); arr } # [[0, 2], [1, 3, 4], [2, 5]]  etc
    .map{|arr| ((arr.shift == 2) ? -1 : 1) * arr.reverse.each_with_index.inject(0){ |sum, (n, i)| sum += n * (10**i) } } # [2, 34, -5] etc
  puts "#{sum_array.join} = 100" if sum_array.reduce(&:+) == 100
end

15

u/mattgrande May 08 '15

repeated_permutation

Wow, I've never seen that function before. Now I'm going to be looking to use it all over the place...

7

u/anopheles0 May 08 '15

I think we can call that one cheating. I bet you guys didn't even write your own sort routines!

2

u/wbeyda May 08 '15

Ruby guys write something? pfft surely there is a gem for it.

4

u/Zequez May 08 '15

Me neither, found it Googling haha, and seems pretty handy, yes.

2

u/honorary_ant May 08 '15

Your coworkers that also have never seen it before will surely thank you ;)

3

u/PaintItPurple May 08 '15

Why wouldn't they? There is nothing about Zequez's code that's particularly subtle or counterintuitive. The fact that you have to read the documentation on repeated_permutation once if it isn't obvious to you what it does isn't a big deal.

4

u/Memitim May 08 '15

Whoa! You want me to reference documentation now? What is this, a prison camp?

4

u/[deleted] May 08 '15

I was hitting 20 lines and still not getting the correct results. The repeated_permutation is made of magic. Thanks for telling about it :)

→ More replies (5)

3

u/JustinsWorking May 08 '15 edited May 08 '15

I got a rather clean JS solution I thought I'd throw up incase anybody was curious. (not using eval)

function oneToNine(){
  function calc(sum, c, n){
    if(n >= 11){
      if(sum.reduce(function(a, b) {return a + b;}) == 100){
        console.log(sum);
      }
      return;
    }
    calc(sum.concat(c), n, n + 1);
    
    if(n > 2){
      calc(sum.concat(-1 * c), n, n + 1);
    }
     
    if(n < 10){
      calc(sum, c*10 + n, n + 1);
    }
  }
  calc([], 1, 2);
}

or if you want to be one of those dorks that makes things as small as possible

(function(){
  function calc(sum, c, n){
    if(n >= 11){
      (sum.reduce(function(a, b) {return a + b;}) == 100) ? console.log(sum) : false;
      return;
    }
    calc(sum.concat(c), n, n + 1);
    (n > 2) ? calc(sum.concat(-1 * c), n, n + 1) : false;
    (n < 10)? calc(sum, c*10 + n, n + 1) : false;
  }
  calc([], 1, 2);
})();

If you really needed to speed it up you could keep a running tally of the sum's as you iterate through... But I didn't bother. Fun problem :)

→ More replies (1)

3

u/SleepyHarry May 08 '15 edited May 08 '15

Python one-liner:

print(*list(filter(lambda e: eval(e)==100, ("{}".join(map(str, range(1, 10))).format(*ops) for ops in __import__("itertools").product(('+', '-', ''), repeat=8)))), sep='\n')

I never said it'd be pretty

Also, inb4 PEP8

edited to make it just print rather than make a callable

3

u/ggPeti May 08 '15

Oneliner, broken out to multiple lines to show steps:

['+', '-', '']
  .repeated_permutation(8)
  .map(&(1..9).method(:zip))
  .map(&:flatten)
  .map(&:compact)
  .map(&:join)
  .map { |form| puts "#{form} == 100" if eval(form) == 100 }

2

u/msx May 08 '15

great job, even if i think that "eval" is kind of a shortcut. I think the evaluation code was intended to be part of the exercise. I'm also surprised that a function like repeated_permutation is available by default O_o Kudos to ruby for having such usefult methods.

I did it in java8, i cheated with the eval too by passing it to a ScriptEngine :P It took 30 minutes, it's much less pretty than your solution and also slow.

2

u/flatlander_ May 08 '15

Wow! That's awesome. Way cleaner than my python solution and beat me by 1 line!

from itertools import product

flatten = lambda l: [i for sublist in l for i in sublist]
stringify = lambda t: "".join(flatten([str(i) for i in flatten(t)])).replace(" ", "")
only_sum_100 = lambda l: [i for i in l if eval(i) == 100]

steps = [[x for x in product([str(j)], ["+", "-", " ")] for j in range(1,9)]
all_combos = [i for i in product(*[step for step in steps])]
all_possibilities = [stringify(combo) + "9" for combo in all_combos]

print only_sum_100(all_possibilities)
→ More replies (4)

2

u/MylekGrey May 09 '15 edited May 09 '15

Here is my short javascript solution. Instead of recursion I used division and modulus to crawl through all the permutations.

var op = ['+','-',''];
for (var j=0; j<Math.pow(3,8); j++) {
	var s = "";
	for (var i=1; i<10; i++) {
		s+=i;
		if (i<9) s+=op[Math.floor(j/Math.pow(3,i-1))%3];
	}
	if (eval(s) == 100) console.log(s + '=100');
}

2

u/hyperhopper May 09 '15

way easier javascript solution:

function solve (previous, collection) {
  if (collection.length === 1) {
    if (eval(previous + collection[0]) === 100) {
      console.log(previous + collection[0]);
    }
  } else {
    ['+', '-', ''].forEach(function (operator) {
      solve(previous + collection[0] + operator, collection.slice(1));
    })
  }
}
solve('', [1,2,3,4,5,6,7,8,9]);

2

u/hirolau May 10 '15

My version inspired by your repeated_permutation. Yes very long lines :D

[:+, :-, ''].repeated_permutation(8).map{|x| x.unshift(:+).zip('1'..'9').flatten.slice_before{|x|x.is_a? Symbol}}.each do |arr|
    puts arr.to_a.flatten.map(&:to_s).join if arr.reduce(0){|sum,(sym,*rest)|sum.send(sym,rest.join.to_i)} == 100
end

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.

1

u/musicmatze May 08 '15

A bit minified... but not golfed:

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

Using eval ... is a really bad idea... but well, I'm to tired right now to fix this up.

→ More replies (2)

1

u/BlackDeath3 May 08 '15

I know, it's bad

Oh, please. I took a couple of hours to crank out 50+ lines of ugly-ass Python. I'm not proud, but I won't make excuses. I'm sure I could optimize it (especially if I was more familiar with the language), but not today...

1

u/jjo241 May 08 '15

Here's a similar approach in Python - I don't know if there is a repeated_permutation function available.

#!/usr/bin/env python
queue = ['+', '-', ' ']
for i in range(7):
    x = [q + '+' for q in queue]
    y = [q + '-' for q in queue]
    z = [q + ' ' for q in queue]
    queue = x + y + z

for q in queue:
    s = '1'
    for a,b in zip(q, '23456789'):
        if a == ' ':
            s += b
        else:
           s += a + b
    if eval(s) == 100:
        print s

1

u/[deleted] May 08 '15

eval is cheating.

→ More replies (3)

0

u/[deleted] May 12 '15

[deleted]

→ More replies (1)
→ More replies (2)