use strict; use warnings; # Four digit mechanical lock: no repeated digits, order doesn't matter. # #https://math.stackexchange.com/questions/156928/number-of-4-digit-numbers-with-no-repeated-digit # Start by finding the permutations: For the first choice, you have 10 possible digits to choose from. #For the second choice, you have 9 digits because you used one for the first choice. #The third choice comes from 8 possibilities and the fourth from 7 possibilities. #Now we multiply these together: 10 x 9 x 8 x 7 = 90 x 56 = 5040. That's the number of permutations. #No digits repeat, but 0123 is different from 0321. # Now to find the number of combinations, I have to know how many different ways there are of arranging four digits. #That's the same kind of problem: the first position could be from 4 possibilities, the second from 3 possiblities, #the third from 2 choices and the last has to be the 1 left. So there are 4 x 3 x 2 x 1 = 24 possible ways of #arranging 4 items. # Therefore I divide 5040 / 24 = 210. So there are 210 different combinations of four digits chosen #from 0-9 where the digits don't repeat. my %output; foreach(123..9876){ my $num = sprintf "%04d", $_; next if $num =~ /(\d).*\1/; my @digits = sort split //, $num; my $num_sorted = join '', @digits; #print "$num: @digits - $num_sorted\n"; if (not exists $output{$num_sorted} ) { #print "adding $num_sorted\n"; $output{$num_sorted}=1; } } print "found ", scalar keys %output, " combinations.\n"; print "$_\n" foreach sort keys %output;