Zack Shapiro
Zack Shapiro

Reputation: 6998

How do I loop through a set of numbers, do some addition and append to an array?

My goal here is to create an array with the sum totals of every combination of 2 numbers on a set of dice. I'm creating the beginning of a loop that adds die1[0] to die2[0..5] before going through die1[1] + die2[0..5] and so on.

I've got this code below and I'm doing something wrong. I want to be able to call specific numbers in the array, such as dieSums[4], and get one number. Any idea what i'm doing incorrectly here?

die1 = [1,2,3,4,5,6] 
die2 = [1,2,3,4,5,6]

dieSums = []

count = 0
while count <= 5 do   
  dieSums << die1[0] + die2[count]   
  count += 1   
  puts dieSums[5]    
end

Upvotes: 3

Views: 2385

Answers (3)

tokland
tokland

Reputation: 67900

As a side note: notice that you are over-complicating the problem (because you think in imperative terms, take a look at Functional programming). The sum of all possible values for two dice:

>> die = [1,2,3,4,5,6]
>> die.product(die).map { |v1, v2| v1 + v2 }
=> [2, 3, 4, 5, 6, 7, 3, 4, 5, 6, 7, 8, 4, 5, 6, 7, 8, 9, 5, 6, 7, 8, 9, 10, 6, 7, 8, 9, 10, 11, 7, 8, 9, 10, 11, 12]
  • Call uniq at the end if you don't want repeated values.
  • Use repeated_combination(2) instead of product if you don't care about the order.
  • Note that die.product(die) = die.repeated_permutation(2))

Finding all the sums for N dice is almost as simple:

>> die.repeated_permutation(5).map { |values| values.inject(:+) }

Upvotes: 2

sarnold
sarnold

Reputation: 104080

A while loop, as you've written it, isn't very Rubyonic. (Rubinic?) A more idiomatic way to iterate over the elements of an array:

#!/usr/bin/ruby

die1 = [1,2,3,4,5,6]
die2 = [1,2,3,4,5,6]

dieSums = []

die1.each do |d1|
    die2.each do |d2|
        dieSums << d1 + d2
    end
end
puts dieSums[5]

Of course, die1 and die2 are identical in this case, so you could replace die2 with die1 and it'd all work out.

Upvotes: 4

Mischa
Mischa

Reputation: 43308

You are calling puts dieSums[5] inside the loop. dieSums[5] won't exist until the last iteration. It'll work if you call it outside the loop:

die1 = [1,2,3,4,5,6] 
die2 = [1,2,3,4,5,6]

dieSums = []

count = 0
while count <= 5 do   
  dieSums << die1[0] + die2[count]   
  count += 1
end

puts dieSums[5] #=> 7

Upvotes: 3

Related Questions