2

I have a number, and would like to see if I multiply the number by a real number, if the new number has the exact same digits as the previous number, only re-arranged. For example, if I wanted to multiply a number by 2 and see if the digits remained the same, I would do

125874
=> 251748

251748 is 125874 multiplied by 2 and both numbers have the exact same digits, only re-arranged. For simplicity, I'm only testing it with multiples of 2 for now. This is what I tried to do and failed.

x = 125874
array = x.to_s.chars.map{|x|x.to_i}
  => [1,2,5,8,7,4]
array.permutation.include?((x * 2).to_s.chars.map{|x|x.to_i}
  => true

Now, I tried to run this in a loop to find all numbers under 100,000 that met this criteria.

range = (1..100000).to_a
range.select do |x|
  array = x.to_s.chars.map{|x|x.to_i}
  array.permutation.include?((x * 2).to_s.chars.map{|x|x.to_i}
end
  => []

Now, it should have recorded at least 125874 in that array, since 125874 * 2 equals 251748, which is a permutation of 125874.

I think I managed to out-confuse myself on this one.

1 Answers1

3

First assume that if the given number contains repeated digits, we require that the number and product of the number and a multiplier contain the same number of each digit that appears in either number:

def same_digits?(nbr, mult)
  nbr.to_s.chars.sort == (nbr * mult).to_s.chars.sort
end

same_digits?(125874,2) #=> true  (125874*2 => 251748)
same_digits?(125874,3) #=> false (125874*3 => 377622)

If nbr and nbr*prod must contain the same digits, but not necessarily the same number of each of those digits, the method differs only slightly:

def same_digits?(nbr, mult)
   nbr.to_s.chars.uniq.sort == (nbr * mult).to_s.chars.uniq.sort
end

same_digits?(10255,2) #=> true   (10255*2 => 20510)
same_digits?(10255,3) #=> false  (10255*3 => 30765)

In this second case there are many other ways to determine if two arrays contain the same elements after duplicates have been removed. Let:

a = nbr.to_s.chars.uniq
b = (nbr*mult).to_s.chars.uniq

Above I've used a.sort == b.sort to check for a match. Here are a few of other ways:

(a&b)==a && (a&b)==b         # Array intersection

(a-b).empty? && (b-a).empty? # Array difference

require 'set'
a.to_set == b.to_set 
Cary Swoveland
  • 106,649
  • 6
  • 63
  • 100