2

I'm attempting to write a method that takes a value N and returns three integers N/2, N/3, and N/4 rounded down. It keeps taking them back until there is only zero.

def crazy_coins(n)
  coins = Array.new
  coins.push(n.to_a)
  generate = Proc.new { |x|
    temp = []
    count = 2
    while count < 5
      x = n/count
      temp << x
      count += 1    
    end
    return temp
  }
  coins.map!(&generate)
end

Outputs:

crazy_coins(5)
# => [[2, 1, 1]]

Successful output is supposed to resemble:

crazy_coins(5)

11
=> [2, 1, 1] 
=> [[1, 0, 0], [0, 0, 0], [0, 0, 0]]
=> [[[0, 0, 0], 0, 0], [0, 0, 0], [0, 0, 0]]

What might be the best way to call coins.map! again on each element (recursively perhaps) until all coins[i][j] == 0?

I tried calling coins[0].map!(&generate) but the result is [[2, 1, 1], [2, 1, 1], [2, 1, 1]] Why is it not replacing the existing values with a new array?

4
  • 1
    You've got it - the return statement in a proc will return from the context in which the proc is called, not just the proc itself. You actually don't need an explicit return statement at all - just put temp as the last statement in the proc and it will be returned. Commented Oct 23, 2013 at 9:16
  • ok nice thanks, that works but when attempting to call coins[0].map!(&generate) to try and replace the [[2, 1, 1]] values, the result is [[2, 1, 1], [2, 1, 1], [2, 1, 1]]..how come map! isnt replacing the single values with a new array? Commented Oct 23, 2013 at 9:26
  • 1
    map! is a method that changes the receiver. It isn't meant to return a new array. Commented Oct 23, 2013 at 10:44
  • I see so i have should make a new array from each [[2, 3, 3]]? Commented Oct 23, 2013 at 10:52

2 Answers 2

1

You just need to recurse on each generated element when it's not 0. Also, try to avoid iteration when collection composition is available.

def divisors(n)
  (2..4).map { |d| n/d }
end

def crazy_coins(a)
  Array(a).map { |e| e != 0 ? crazy_coins(divisors(e)) : e }
end

crazy_coins(5)
=> [[[[0, 0, 0], 0, 0], [0, 0, 0], [0, 0, 0]]]
crazy_coins(11)
=> [[[[[0, 0, 0], 0, 0], [0, 0, 0], [0, 0, 0]], [[0, 0, 0], [0, 0, 0], 0], [[0, 0, 0], 0, 0]]]
Sign up to request clarification or add additional context in comments.

Comments

0

Thanks to dbenhur I was able to finish the problem...dbenhur showed me the recursion but the end result of my program was to return the final amount of zero coins but I couldn't make it work with two methods...

Solution:

def crazy_coins(n)
  return 1 if n == 0

      # Recursive
  return crazy_coins(n / 2) + crazy_coins(n / 3) + crazy_coins(n / 4)
end

crazy_coins(5)
=> 11
=> [[[[0, 0, 0], 0, 0], [0, 0, 0], [0, 0, 0]]]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.