"grains of wheat on a chessboard" in Ruby -



"grains of wheat on a chessboard" in Ruby -

there 64 squares on chessboard. every square has double 1 before. write programme shows: - how many grains on each square, , - total number of grains

my code working first part, have problems declaring total. basic class/method declaration missing. helping.

class grains def square(n) array_of_grains = [] (0..63).each {|x| array_of_grains << 2**x} n = n-1 array_of_grains[n] end def total array_of_grains.each {|x| sum += x } end end

here's meta-answer, combining ideas here (upvotes around!) finish solution using class.

class grains attr_accessor :array_of_grains def initialize(n = 1) @array_of_grains = 63.times.with_object([n]) { |i,a| << 2 * a.last } end def square(n) array_of_grains[n - 1] end def total array_of_grains.reduce(:+) end end

usage:

board = grains.new board.square(3) #=> 4 board.total #=> 18446744073709551615

ruby

Comments

Popular posts from this blog

java Multi query from Mysql using netbeans -

c# - DotNetZip fails with "stream does not support seek operations" -

c++ - StartServiceCtrlDispatcher don't can access 1063 error -