Hacker News new | ask | show | jobs
by mywrathacademia 2654 days ago
Thinking of the problem as a nested for loop it's intuitive to see how you get 1000 combinations without the numbers being unique but I dont see how to get 720 combinations as the answer when each digit is different. Can you explain where 720 combinations comes from in the context I mentioned?
6 comments

I'd like to highlight this comment for everyone who is saying the question can only be gotten wrong by someone who misreads it.

It can be easy for people to forget that many people (even coders) have never done this type of math before.

I believe CS degrees require discreet math (and highschool algebra 2), which means they've done permutations and combinatorics, so yes they've done these types of problems before. The real question is how long has it been?
10 * 9 * 8

The first time you pick, you have 10 different numbers to choose from, the second time, 9, the third time 8.

Or if you are like me (and a bit stupid):

1000 = all possible combinations from 000 to 999.

less 10 combinations with all numbers identical is 990.

now there are three patterns for numbers to be identical left that need to be taken out: 00x 0x0 x00. The x can be replaced with all digits != 0 in this example, so thats 3 (patterns) x 9 ('x' digits) = 27. That times 10 digits that can have double patterns is 270.

1000 - 10 - 270 = 720.

Hmmm. I wouldn't have approached it that way. Thanks for sharing! Lots of ways to approach any problem.
The questions ask for all permutations of length 3. What you've described is the Cartesian product:

    import itertools

    print(len([x for x in itertools.product(range(10), repeat=3)])) #1000
    print(len([x for x in itertools.permutations(range(10), 3)])) #720
itertools.product essentially does a nested for loop.

The reason it's less is because each number has to be different, so you can't have 000 or 111, etc.

Permutation without repetition.

The formula is:

n! / (n − r)!

Since there is 10 (n=10) total numbers, 0-9. And it can only be 3 (r=3) digits long. Then it would be,

10! / (10-3)!* which would result in,

10 * 9 * 8 * 7 * 6 * 5 * 4 * 3 * 2 * 1 / (7 * 6 * 5 * 4 * 3 * 2 * 1) = 10 * 9 * 8 = 720.

for i = 1-10 for j = 1-10 if i == j break for k = 1-10 if i == j or i == k break log(i,j,k)
for i = 1-10

for j = 1-10

if i == j break

for k = 1-10

if i == j or i == k break

log(i,j,k)

(I don't understand HN formatting still)

    #!/usr/bin/python
    r = [(i,j,k) for i in range(10) for j in range(10) for k in range(10) if i!=j and i!=k and j!=k]
    print(len(r))