2

Using just Ruby I am trying to

  • Generate an array of random numbers

  • Create a new 2 dimensional array containing x amount of arrays filled with x amount of samples from the original number list.

This is what I have...

a = 1000.times.map{rand(100)}.to_a
b = 5.times.map{a.sample}
#=> [3, 96, 23, 45, 41]

I basically want to be able to generate what I did in b, x amount of times.

Is this possible?

Thank you for the comments everyone!

3 Answers 3

1

Just wrap your definition of b in another map:

a = 1000.times.map{rand(100)} # to_a is unnecessary here, map returns an array
b = 5.times.map{5.times.map{a.sample}}
Sign up to request clarification or add additional context in comments.

1 Comment

Andrew, thank you for the comment you left on my answer, which I subsequently deleted. Note only were you correct that the answer was incorrect if the OP's array a were used elsewhere in the program, but it was just plain wrong. If, for example, the first array contained 1,000 1's (unlikely as that may be), b would always have nothing but 1's, whereas I was just generating random values within the originally-specified interval.
0

A one-liner to do what you want.

3.times.map {2.times.map {rand 1000} }
#=> [[267, 476], [109, 950], [345, 137]]

1 Comment

This is exactly what i was looking for. Thank you!!
0

I don't have Rails installed at the moment, so here's a pure Ruby solution.

a = (0..1000).to_a.map! { rand(100) }
x = 2
b =  (0..x).to_a.map! { a.sample(x) }
# [[83, 73], [55, 93], [57, 18]]

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.