0

I have created a two-dimensional (4x4) array, where each element is a random number from -10 to 10.

I would like to now print all negative elements of this array in the terminal. How can one do this?

Here is my code so far which initialises the array, along with my current attempt to print all negative values:

a = Array.new(4) { rand(-10...10) }

a[0] = Array.new(4) { rand(-10...10) }
a[1] = Array.new(4) { rand(-10...10) }
a[2] = Array.new(4) { rand(-10...10) }
a[3] = Array.new(4) { rand(-10...10) }

a.each {|i|
  a.each {|j|
    puts j
  }
}
5
  • Your program seems to work fine. What problem are you having? Please ask a specific question. Commented May 24, 2016 at 20:06
  • Once readers understand the question, someone will be happy to do an edit to help you with the English. Not to worry. I think it's mainly " and when have negative elemt put this elevent in terminal" that we don't understand. Commented May 24, 2016 at 20:08
  • update question. need put array element if element negative Commented May 24, 2016 at 20:09
  • Do you mean you want to display the element (puts ...) if it is negative? If so, do you want to display the element's indices as well (e.g., "a[2,3] = -4")? Commented May 24, 2016 at 20:11
  • rand isn't very random. Use something like: SecureRandom.random_number(-10..10) instead. require 'securerandom' to enable this. Commented May 24, 2016 at 20:18

3 Answers 3

3

You can create the 4x4 array much more simply in a single step, as follows:

a = Array.new(4) { Array.new(4) { rand(-10..10) } }

You can then print all negative values in the 4x4 array via a nested loop:

a.each do |row|
  row.each do |cell|
    puts cell if cell < 0
  end
end
Sign up to request clarification or add additional context in comments.

Comments

1

No need loop it twice.

a = Array.new(4) { Array.new(4) { rand(-10..10) } }

a.flatten.each {|x| puts x if x>0}

1 Comment

If you want to do more than just puts x, then looping twice is more flexible - for example, you could do each_with_index. In addition, this code is ~2.5 times slower. So yes, your code may be slightly more compact, but it comes at a cost.
1
require 'matrix'

n = 4
m = Matrix.build(n) { rand(-10..10) }
  #=> Matrix[[-5, -8, -3, 7], [-5, 5, 2, 7], [-8, -9, 8, 5], [-2, -9, -2, -4]] 
m.each_with_index { |v,r,c| puts "m[%d,%d] = %d" % [r,c,v] if v < 0 }
m[0,0] = -5
m[0,1] = -8
m[0,2] = -3
m[1,0] = -5
m[2,0] = -8
m[2,1] = -9
m[3,0] = -2
m[3,1] = -9
m[3,2] = -2
m[3,3] = -4

If you wish to return the associated array:

m.to_a
  #=> [[-5, -8, -3, 7], [-5, 5, 2, 7], [-8, -9, 8, 5], [-2, -9, -2, -4]] 

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.