Iggy Iggy - 4 months ago 38
Ruby Question

Return elements that are palindrome to each other in an array

How can I return an array of palindrome numbers in a given array? Not palindromic numbers like 11, 22, 33, 44, &c., but the numbers that are palindromic to other number in the same array. Assume all elements are positive and the result should not return single digit numbers (example below)

Let's say I have

array = [13, 31, 51, 79, 83, 97]
. Since 13 & 31 and 79 & 97 are palindromes, I want it to return
array_pali = [13, 31, 79, 97]


def pali_array(array)
array_reverse = array.map{|el| el.to_s.reverse.to_i}
array_pali = array & array_reverse
return array_pali
end


My initial plan is to come up with a reverse of that array,
array_reverse = array.map{|el| el.to_s.reverse.to_i}
and intersect them:
array & array_reverse


A problem that occur is, if I want to return array of prime numbers from 2-100 as given:

array = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]


and I reversed it:

array_reverse = array.map{|el| el.to_s.reverse.to_i}
=> [2, 3, 5, 7, 11, 31, 71, 91, 32, 92, 13, 73, 14, 34, 74, 35, 95, 16, 76, 17, 37, 97, 38, 98, 79]


It returns:

array & array_reverse
=> [2, 3, 5, 7, 11, 13, 17, 31, 37, 71, 73, 79, 97]


The problem with this approach:

2, 3, 5, 7, and 11 are not palindromes to other elements. The reverse of single digit number is that number itself and it causes the code to return all single digit numbers, and all palindromic number (like 11, 22, 33). It should return only
[13, 17, 31, 37, 71, 73, 79, 97]


How can I make it to return only elements that are palindromic to other element in the same array?

Answer

Think this works if you want an alternative:

array = [13, 31, 51, 79, 83, 97]
array.combination(2)
     .select {|pair| pair.first.to_s == pair.last.to_s.reverse }
     .flatten

#=> [13, 31, 79, 97]

Use Array#combination to get every pair combo then we select only those palindrome-pairs. Then just flatten your array.

Comments