demas demas - 28 days ago 11
Ruby Question

palindromic numbers

Here is working code:

p = (10..14).map { |a|
(a..14).map { |b|
a * b
}
flatten.select { |p|
p.to_s == p.to_s.reverse
}


But I want to keep the information about 'a' and 'b' which produced 'a * b':

p = (10..14).map { |a|
(a..14).map { |b|
[a, b, a * b, '=']
}
}.select { |v|
v[2].to_s == v[2].to_s.reverse
}

puts p


This code print not palindromic number. I guess that reason is a Array flatten. How do I need to change code to get palindromic number?

Answer

You want to flatten only one level, so use flatten(1) instead.

(10..14).map { |a|
  (a..14).map { |b|
    [a, b, a * b, '=']
  }
}.flatten(1).select { |v|
  v[2].to_s == v[2].to_s.reverse
}

Alternatively, replace your outer map by flat_map:

(10..14).flat_map { |a|
  (a..14).map { |b|
    [a, b, a * b, '=']
  }
}.select { |v|
  v[2].to_s == v[2].to_s.reverse
}

Note: flatten takes an argument since Ruby 1.8.7. flat_map is new to Ruby 1.9.2. Make sure you have the right version, or require "backports/1.9.2/enumerable/flat_map" or require "backports/1.8.7/array/flatten".

Comments