Ruby Iterating through 2D arrays and Populating with random data Unicorn Meta Zoo #1: Why another podcast? Announcing the arrival of Valued Associate #679: Cesar Manara Data science time! April 2019 and salary with experience The Ask Question Wizard is Live!How to generate a random string in RubyHow to get a random number in RubyWhat is the “right” way to iterate through an array in Ruby?How to sum array of numbers in Ruby?How do you add an array to another array in Ruby and not end up with a multi-dimensional result?Check if a value exists in an array in RubyHow to generate a random number between a and b in Ruby?Get random item from JavaScript arrayUsing random number draws to repopulate an array for analysisPopulate multidimensional array with data

How do I check if a string is entirely made of the same substring?

Israeli soda type drink

Could moose/elk survive in the Amazon forest?

Second order approximation of the loss function (Deep learning book, 7.33)

Does Feeblemind produce an ongoing magical effect that can be dispelled?

What is a 'Key' in computer science?

Why did C use the -> operator instead of reusing the . operator?

Arriving in Atlanta after US Preclearance in Dublin. Will I go through TSA security in Atlanta to transfer to a connecting flight?

Additive group of local rings

What do you call the part of a novel that is not dialog?

Why did Israel vote against lifting the American embargo on Cuba?

Expansion//Explosion and Siren Stormtamer

Multiple options vs single option UI

Protagonist's race is hidden - should I reveal it?

How to get even lighting when using flash for group photos near wall?

My bank got bought out, am I now going to have to start filing tax returns in a different state?

Why didn't the Space Shuttle bounce back into space as many times as possible so as to lose a lot of kinetic energy up there?

How to keep bees out of canned beverages?

How can I wire a 9-position switch so that each position turns on one more LED than the one before?

Will I lose my paid in full property

A Paper Record is What I Hamper

What's parked in Mil Moscow helicopter plant?

Married in secret, can marital status in passport be changed at a later date?

Is Diceware more secure than a long passphrase?



Ruby Iterating through 2D arrays and Populating with random data



Unicorn Meta Zoo #1: Why another podcast?
Announcing the arrival of Valued Associate #679: Cesar Manara
Data science time! April 2019 and salary with experience
The Ask Question Wizard is Live!How to generate a random string in RubyHow to get a random number in RubyWhat is the “right” way to iterate through an array in Ruby?How to sum array of numbers in Ruby?How do you add an array to another array in Ruby and not end up with a multi-dimensional result?Check if a value exists in an array in RubyHow to generate a random number between a and b in Ruby?Get random item from JavaScript arrayUsing random number draws to repopulate an array for analysisPopulate multidimensional array with data



.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








0















I have to generate a dynamically sized 2D array with a predetermined value in the first index of each sub array, three random values in each of the three following indices (each falling in a different range), and finally, a calculated total of the three random indices. Here is what I have so far.



Sample code



print("Please enter the number of athletes competing in the triathalon: ")
field=gets.to_i

count=1
athlete = Array.new(5)
triathalon = Array.new(field)athlete
triathalon.each do
athlete.each do
athlete.insert(0,count)
athlete.insert(1,rand(30..89))
athlete.insert(2,rand(90..119))
athlete.insert(3,rand(120..360))
#calculate total time per athlete
athlete.insert(4,athlete[1]+athlete[2]+athlete[3])
count+=1
end
end









share|improve this question






















  • The code seems to hang during the generation process. Running it without the nested athlete.each loop results in a clean run, but only generating one repeated set of athlete data.

    – Gryphon59
    Mar 9 at 6:25

















0















I have to generate a dynamically sized 2D array with a predetermined value in the first index of each sub array, three random values in each of the three following indices (each falling in a different range), and finally, a calculated total of the three random indices. Here is what I have so far.



Sample code



print("Please enter the number of athletes competing in the triathalon: ")
field=gets.to_i

count=1
athlete = Array.new(5)
triathalon = Array.new(field)athlete
triathalon.each do
athlete.each do
athlete.insert(0,count)
athlete.insert(1,rand(30..89))
athlete.insert(2,rand(90..119))
athlete.insert(3,rand(120..360))
#calculate total time per athlete
athlete.insert(4,athlete[1]+athlete[2]+athlete[3])
count+=1
end
end









share|improve this question






















  • The code seems to hang during the generation process. Running it without the nested athlete.each loop results in a clean run, but only generating one repeated set of athlete data.

    – Gryphon59
    Mar 9 at 6:25













0












0








0








I have to generate a dynamically sized 2D array with a predetermined value in the first index of each sub array, three random values in each of the three following indices (each falling in a different range), and finally, a calculated total of the three random indices. Here is what I have so far.



Sample code



print("Please enter the number of athletes competing in the triathalon: ")
field=gets.to_i

count=1
athlete = Array.new(5)
triathalon = Array.new(field)athlete
triathalon.each do
athlete.each do
athlete.insert(0,count)
athlete.insert(1,rand(30..89))
athlete.insert(2,rand(90..119))
athlete.insert(3,rand(120..360))
#calculate total time per athlete
athlete.insert(4,athlete[1]+athlete[2]+athlete[3])
count+=1
end
end









share|improve this question














I have to generate a dynamically sized 2D array with a predetermined value in the first index of each sub array, three random values in each of the three following indices (each falling in a different range), and finally, a calculated total of the three random indices. Here is what I have so far.



Sample code



print("Please enter the number of athletes competing in the triathalon: ")
field=gets.to_i

count=1
athlete = Array.new(5)
triathalon = Array.new(field)athlete
triathalon.each do
athlete.each do
athlete.insert(0,count)
athlete.insert(1,rand(30..89))
athlete.insert(2,rand(90..119))
athlete.insert(3,rand(120..360))
#calculate total time per athlete
athlete.insert(4,athlete[1]+athlete[2]+athlete[3])
count+=1
end
end






ruby multidimensional-array random






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Mar 9 at 6:24









Gryphon59Gryphon59

31




31












  • The code seems to hang during the generation process. Running it without the nested athlete.each loop results in a clean run, but only generating one repeated set of athlete data.

    – Gryphon59
    Mar 9 at 6:25

















  • The code seems to hang during the generation process. Running it without the nested athlete.each loop results in a clean run, but only generating one repeated set of athlete data.

    – Gryphon59
    Mar 9 at 6:25
















The code seems to hang during the generation process. Running it without the nested athlete.each loop results in a clean run, but only generating one repeated set of athlete data.

– Gryphon59
Mar 9 at 6:25





The code seems to hang during the generation process. Running it without the nested athlete.each loop results in a clean run, but only generating one repeated set of athlete data.

– Gryphon59
Mar 9 at 6:25












1 Answer
1






active

oldest

votes


















1














One possible option is using Range and mapping the range using Enumerable#map.



For example given n = 3 athletes, basic example:



(1..n).map n #=> [[1], [2], [3]]


So, adding some of your specifications to the basic example:



n = 3
res = (1..n).map do |n|
r1 = rand(30..89)
r2 = rand(90..119)
r3 = rand(120..360)
score = r1 + r2 + r3
[n, r1, r2, r3, score]
end

#=> [[1, 38, 93, 318, 449], [2, 64, 93, 259, 416], [3, 83, 93, 343, 519]]





An alternative way of pushing the sum of element into the array is using Object#tap:

[5,10,15].tap #=> [5, 10, 15, 30]


So you could write:



[rand(30..89), rand(90..119), rand(120..360)].tap 


This allows to write a one liner (using Array#unshift):



(1..n).map n




Fixing your code

Visualise the setup:



field = 3 # no user input for example
p athlete = Array.new(5) #=> [nil, nil, nil, nil, nil]
p triathalon = Array.new(field)athlete.dup #=> [[nil, nil, nil, nil, nil], [nil, nil, nil, nil, nil], [nil, nil, nil, nil, nil]]


NOTE athlete.dup to avoid reference to the same object.



Once you see your objects (athlete and triathalon), you can realize that it is not required to iterate over the nested array, just access by index:



count=1
triathalon.each do |athlete|
athlete[0] = count
athlete[1] = rand(30..89)
athlete[2] = rand(90..119)
athlete[3] = rand(120..360)
athlete[4] = athlete[1] + athlete[2] + athlete[3]
count+=1
end


Improvement: to get rid of the counter use Enumerable#each_with_index.






share|improve this answer

























  • So, I tried your example code, and had the triathlon array print after the loop. It's generating #field number of identical arrays. If I use 3 as the user input for field, I'm getting 3 identical arrays. Sample output in next comment. Also, I appreciate the help.

    – Gryphon59
    Mar 9 at 8:48












  • Please enter the number of athletes competing in the triathalon: 3 [[3, 80, 102, 193, 375], [3, 80, 102, 193, 375], [3, 80, 102, 193, 375]]

    – Gryphon59
    Mar 9 at 8:48












  • My bad, in setting up the triathalon array it is required to duplicate the object to avoid create an array whit the reference to the same object. I edited. See: ruby-doc.org/core-2.6.1/…

    – iGian
    Mar 9 at 11:03












  • A small point regarding your last sentence: one could instead use Enumerator#each_index, writing triathalon.each.with_index(1) . The argument 1 causes the index (count) to begin at 1, a convenience.

    – Cary Swoveland
    Mar 9 at 18:04












Your Answer






StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55074646%2fruby-iterating-through-2d-arrays-and-populating-with-random-data%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









1














One possible option is using Range and mapping the range using Enumerable#map.



For example given n = 3 athletes, basic example:



(1..n).map n #=> [[1], [2], [3]]


So, adding some of your specifications to the basic example:



n = 3
res = (1..n).map do |n|
r1 = rand(30..89)
r2 = rand(90..119)
r3 = rand(120..360)
score = r1 + r2 + r3
[n, r1, r2, r3, score]
end

#=> [[1, 38, 93, 318, 449], [2, 64, 93, 259, 416], [3, 83, 93, 343, 519]]





An alternative way of pushing the sum of element into the array is using Object#tap:

[5,10,15].tap #=> [5, 10, 15, 30]


So you could write:



[rand(30..89), rand(90..119), rand(120..360)].tap 


This allows to write a one liner (using Array#unshift):



(1..n).map n




Fixing your code

Visualise the setup:



field = 3 # no user input for example
p athlete = Array.new(5) #=> [nil, nil, nil, nil, nil]
p triathalon = Array.new(field)athlete.dup #=> [[nil, nil, nil, nil, nil], [nil, nil, nil, nil, nil], [nil, nil, nil, nil, nil]]


NOTE athlete.dup to avoid reference to the same object.



Once you see your objects (athlete and triathalon), you can realize that it is not required to iterate over the nested array, just access by index:



count=1
triathalon.each do |athlete|
athlete[0] = count
athlete[1] = rand(30..89)
athlete[2] = rand(90..119)
athlete[3] = rand(120..360)
athlete[4] = athlete[1] + athlete[2] + athlete[3]
count+=1
end


Improvement: to get rid of the counter use Enumerable#each_with_index.






share|improve this answer

























  • So, I tried your example code, and had the triathlon array print after the loop. It's generating #field number of identical arrays. If I use 3 as the user input for field, I'm getting 3 identical arrays. Sample output in next comment. Also, I appreciate the help.

    – Gryphon59
    Mar 9 at 8:48












  • Please enter the number of athletes competing in the triathalon: 3 [[3, 80, 102, 193, 375], [3, 80, 102, 193, 375], [3, 80, 102, 193, 375]]

    – Gryphon59
    Mar 9 at 8:48












  • My bad, in setting up the triathalon array it is required to duplicate the object to avoid create an array whit the reference to the same object. I edited. See: ruby-doc.org/core-2.6.1/…

    – iGian
    Mar 9 at 11:03












  • A small point regarding your last sentence: one could instead use Enumerator#each_index, writing triathalon.each.with_index(1) . The argument 1 causes the index (count) to begin at 1, a convenience.

    – Cary Swoveland
    Mar 9 at 18:04
















1














One possible option is using Range and mapping the range using Enumerable#map.



For example given n = 3 athletes, basic example:



(1..n).map n #=> [[1], [2], [3]]


So, adding some of your specifications to the basic example:



n = 3
res = (1..n).map do |n|
r1 = rand(30..89)
r2 = rand(90..119)
r3 = rand(120..360)
score = r1 + r2 + r3
[n, r1, r2, r3, score]
end

#=> [[1, 38, 93, 318, 449], [2, 64, 93, 259, 416], [3, 83, 93, 343, 519]]





An alternative way of pushing the sum of element into the array is using Object#tap:

[5,10,15].tap #=> [5, 10, 15, 30]


So you could write:



[rand(30..89), rand(90..119), rand(120..360)].tap 


This allows to write a one liner (using Array#unshift):



(1..n).map n




Fixing your code

Visualise the setup:



field = 3 # no user input for example
p athlete = Array.new(5) #=> [nil, nil, nil, nil, nil]
p triathalon = Array.new(field)athlete.dup #=> [[nil, nil, nil, nil, nil], [nil, nil, nil, nil, nil], [nil, nil, nil, nil, nil]]


NOTE athlete.dup to avoid reference to the same object.



Once you see your objects (athlete and triathalon), you can realize that it is not required to iterate over the nested array, just access by index:



count=1
triathalon.each do |athlete|
athlete[0] = count
athlete[1] = rand(30..89)
athlete[2] = rand(90..119)
athlete[3] = rand(120..360)
athlete[4] = athlete[1] + athlete[2] + athlete[3]
count+=1
end


Improvement: to get rid of the counter use Enumerable#each_with_index.






share|improve this answer

























  • So, I tried your example code, and had the triathlon array print after the loop. It's generating #field number of identical arrays. If I use 3 as the user input for field, I'm getting 3 identical arrays. Sample output in next comment. Also, I appreciate the help.

    – Gryphon59
    Mar 9 at 8:48












  • Please enter the number of athletes competing in the triathalon: 3 [[3, 80, 102, 193, 375], [3, 80, 102, 193, 375], [3, 80, 102, 193, 375]]

    – Gryphon59
    Mar 9 at 8:48












  • My bad, in setting up the triathalon array it is required to duplicate the object to avoid create an array whit the reference to the same object. I edited. See: ruby-doc.org/core-2.6.1/…

    – iGian
    Mar 9 at 11:03












  • A small point regarding your last sentence: one could instead use Enumerator#each_index, writing triathalon.each.with_index(1) . The argument 1 causes the index (count) to begin at 1, a convenience.

    – Cary Swoveland
    Mar 9 at 18:04














1












1








1







One possible option is using Range and mapping the range using Enumerable#map.



For example given n = 3 athletes, basic example:



(1..n).map n #=> [[1], [2], [3]]


So, adding some of your specifications to the basic example:



n = 3
res = (1..n).map do |n|
r1 = rand(30..89)
r2 = rand(90..119)
r3 = rand(120..360)
score = r1 + r2 + r3
[n, r1, r2, r3, score]
end

#=> [[1, 38, 93, 318, 449], [2, 64, 93, 259, 416], [3, 83, 93, 343, 519]]





An alternative way of pushing the sum of element into the array is using Object#tap:

[5,10,15].tap #=> [5, 10, 15, 30]


So you could write:



[rand(30..89), rand(90..119), rand(120..360)].tap 


This allows to write a one liner (using Array#unshift):



(1..n).map n




Fixing your code

Visualise the setup:



field = 3 # no user input for example
p athlete = Array.new(5) #=> [nil, nil, nil, nil, nil]
p triathalon = Array.new(field)athlete.dup #=> [[nil, nil, nil, nil, nil], [nil, nil, nil, nil, nil], [nil, nil, nil, nil, nil]]


NOTE athlete.dup to avoid reference to the same object.



Once you see your objects (athlete and triathalon), you can realize that it is not required to iterate over the nested array, just access by index:



count=1
triathalon.each do |athlete|
athlete[0] = count
athlete[1] = rand(30..89)
athlete[2] = rand(90..119)
athlete[3] = rand(120..360)
athlete[4] = athlete[1] + athlete[2] + athlete[3]
count+=1
end


Improvement: to get rid of the counter use Enumerable#each_with_index.






share|improve this answer















One possible option is using Range and mapping the range using Enumerable#map.



For example given n = 3 athletes, basic example:



(1..n).map n #=> [[1], [2], [3]]


So, adding some of your specifications to the basic example:



n = 3
res = (1..n).map do |n|
r1 = rand(30..89)
r2 = rand(90..119)
r3 = rand(120..360)
score = r1 + r2 + r3
[n, r1, r2, r3, score]
end

#=> [[1, 38, 93, 318, 449], [2, 64, 93, 259, 416], [3, 83, 93, 343, 519]]





An alternative way of pushing the sum of element into the array is using Object#tap:

[5,10,15].tap #=> [5, 10, 15, 30]


So you could write:



[rand(30..89), rand(90..119), rand(120..360)].tap 


This allows to write a one liner (using Array#unshift):



(1..n).map n




Fixing your code

Visualise the setup:



field = 3 # no user input for example
p athlete = Array.new(5) #=> [nil, nil, nil, nil, nil]
p triathalon = Array.new(field)athlete.dup #=> [[nil, nil, nil, nil, nil], [nil, nil, nil, nil, nil], [nil, nil, nil, nil, nil]]


NOTE athlete.dup to avoid reference to the same object.



Once you see your objects (athlete and triathalon), you can realize that it is not required to iterate over the nested array, just access by index:



count=1
triathalon.each do |athlete|
athlete[0] = count
athlete[1] = rand(30..89)
athlete[2] = rand(90..119)
athlete[3] = rand(120..360)
athlete[4] = athlete[1] + athlete[2] + athlete[3]
count+=1
end


Improvement: to get rid of the counter use Enumerable#each_with_index.







share|improve this answer














share|improve this answer



share|improve this answer








edited Mar 9 at 11:03

























answered Mar 9 at 6:47









iGianiGian

5,1742725




5,1742725












  • So, I tried your example code, and had the triathlon array print after the loop. It's generating #field number of identical arrays. If I use 3 as the user input for field, I'm getting 3 identical arrays. Sample output in next comment. Also, I appreciate the help.

    – Gryphon59
    Mar 9 at 8:48












  • Please enter the number of athletes competing in the triathalon: 3 [[3, 80, 102, 193, 375], [3, 80, 102, 193, 375], [3, 80, 102, 193, 375]]

    – Gryphon59
    Mar 9 at 8:48












  • My bad, in setting up the triathalon array it is required to duplicate the object to avoid create an array whit the reference to the same object. I edited. See: ruby-doc.org/core-2.6.1/…

    – iGian
    Mar 9 at 11:03












  • A small point regarding your last sentence: one could instead use Enumerator#each_index, writing triathalon.each.with_index(1) . The argument 1 causes the index (count) to begin at 1, a convenience.

    – Cary Swoveland
    Mar 9 at 18:04


















  • So, I tried your example code, and had the triathlon array print after the loop. It's generating #field number of identical arrays. If I use 3 as the user input for field, I'm getting 3 identical arrays. Sample output in next comment. Also, I appreciate the help.

    – Gryphon59
    Mar 9 at 8:48












  • Please enter the number of athletes competing in the triathalon: 3 [[3, 80, 102, 193, 375], [3, 80, 102, 193, 375], [3, 80, 102, 193, 375]]

    – Gryphon59
    Mar 9 at 8:48












  • My bad, in setting up the triathalon array it is required to duplicate the object to avoid create an array whit the reference to the same object. I edited. See: ruby-doc.org/core-2.6.1/…

    – iGian
    Mar 9 at 11:03












  • A small point regarding your last sentence: one could instead use Enumerator#each_index, writing triathalon.each.with_index(1) . The argument 1 causes the index (count) to begin at 1, a convenience.

    – Cary Swoveland
    Mar 9 at 18:04

















So, I tried your example code, and had the triathlon array print after the loop. It's generating #field number of identical arrays. If I use 3 as the user input for field, I'm getting 3 identical arrays. Sample output in next comment. Also, I appreciate the help.

– Gryphon59
Mar 9 at 8:48






So, I tried your example code, and had the triathlon array print after the loop. It's generating #field number of identical arrays. If I use 3 as the user input for field, I'm getting 3 identical arrays. Sample output in next comment. Also, I appreciate the help.

– Gryphon59
Mar 9 at 8:48














Please enter the number of athletes competing in the triathalon: 3 [[3, 80, 102, 193, 375], [3, 80, 102, 193, 375], [3, 80, 102, 193, 375]]

– Gryphon59
Mar 9 at 8:48






Please enter the number of athletes competing in the triathalon: 3 [[3, 80, 102, 193, 375], [3, 80, 102, 193, 375], [3, 80, 102, 193, 375]]

– Gryphon59
Mar 9 at 8:48














My bad, in setting up the triathalon array it is required to duplicate the object to avoid create an array whit the reference to the same object. I edited. See: ruby-doc.org/core-2.6.1/…

– iGian
Mar 9 at 11:03






My bad, in setting up the triathalon array it is required to duplicate the object to avoid create an array whit the reference to the same object. I edited. See: ruby-doc.org/core-2.6.1/…

– iGian
Mar 9 at 11:03














A small point regarding your last sentence: one could instead use Enumerator#each_index, writing triathalon.each.with_index(1) . The argument 1 causes the index (count) to begin at 1, a convenience.

– Cary Swoveland
Mar 9 at 18:04






A small point regarding your last sentence: one could instead use Enumerator#each_index, writing triathalon.each.with_index(1) . The argument 1 causes the index (count) to begin at 1, a convenience.

– Cary Swoveland
Mar 9 at 18:04




















draft saved

draft discarded
















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55074646%2fruby-iterating-through-2d-arrays-and-populating-with-random-data%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

1928 у кіно

Захаров Федір Захарович

Ель Греко