Home > Back-end >  Find the squares of all natural numbers <= 1000 ending in 3, 9, 6. (Use the map or collect method
Find the squares of all natural numbers <= 1000 ending in 3, 9, 6. (Use the map or collect method

Time:05-19

I don't know what needs to be done in the .map to knock out the last number 3, 6, 9. I try:

(
  (1..(999 % 10 == 3)).map { |x| x ** 2 } |
  (1..(999 % 10 == 6)).map { |x| x ** 2 } |
  (1..(999 % 10 == 9)).map { |x| x ** 2 }
).reduce(&:)

I understand that this is very wrong, but I am a beginner, can you help me! Thank you!

CodePudding user response:

(1..(999 == 3)) gets evaluated as:

(1..(999 == 3))
(1..(9 == 3))
(1..false)

Which gives ArgumentError: bad value for range because you apparently can't iterate from 1 to false.

You could use a range and select:

(1..1000).select { |i| i % 10 == 3 }
#=> [3, 13, 23, 33, ..., 973, 983, 993]

You can then calculate the squares via:

(1..1000).select { |i| i % 10 == 3 }.map { |i| i ** 2 }
#=> [9, 169, 529, ..., 946729, 966289, 986049]

To combine the squares from 3, 6, and 9, you could use Array# :

(1..1000).select { |i| i % 10 == 3 }.map { |i| i ** 2 }  
(1..1000).select { |i| i % 10 == 6 }.map { |i| i ** 2 }  
(1..1000).select { |i| i % 10 == 9 }.map { |i| i ** 2 }

Or you could change the select statement to include those numbers right-away:

(1..1000).select { |i| i % 10 == 3 || i % 10 == 6 || i % 10 == 9 }
         .map { |i| i ** 2 }

# or

(1..1000).select { |i| [3, 6, 9].include?(i % 10) }.map { |i| i ** 2 }

Instead of filtering / selecting from a range of natural numbers, you could also generate this sequence using a custom Enumerator:

three_six_nine = Enumerator.new do |y|
  0.step(by: 10) do |i|
    y << i   3
    y << i   6
    y << i   9
  end
end

three_six_nine.take_while { |i| i <= 1000 } #=> [3, 6, 9, 13, 16, 19, ...]
              .map { |i| i ** 2 }           #=> [9, 36, 81, 169, 256, 361, ...]

CodePudding user response:

(1..999).map{|x| x**2}.select{|x| [3,6,9].include?(x)} but for the record there is no square number ending with 3

  •  Tags:  
  • ruby
  • Related