Discuss Scratch

Ankit_Anmol
Scratcher
500+ posts

Most efficient way to get every possible combination

So I wanted to make some sort of an AI.. for that I needed to make a script

The script does is generate ALL 9 digit number combinations that can be made by a 0,1,2. Like:000000000,111111111,000001111 and those stuff…
So there are 3^9 numbers to generate and I want to generate all of them and put it in a list…


when green flag clicked
Generate all numbers possible in 9 digits only using 0,1,2 numbers
awesome-llama
Scratcher
1000+ posts

Most efficient way to get every possible combination

I'm making a project to show you my solution right now.

Last edited by awesome-llama (May 4, 2021 10:26:49)

PutneyCat
Scratcher
500+ posts

Most efficient way to get every possible combination

That is basically counting from 0 to 3^9-1 in base 3.

So all you need is a script to convert from base 10 to base 3.

That is fairly simple, using a loop and the mod operator. At each stage you take the number, subtract whatever it is in mod 3 (which will give you the digit you need) and divide by 3.

For example, take 19 (= 201 in base 3).

19 mod 3 is 1.
(19-1)/3 = 6.
6 mod 3 = 0
(6-0)/3 mod 3 = 2.
2 mod 3 is 2.
(2-2)/3 = 0.

So that gives you the 201 (but in reverse order). You can pad it out with 0s at the beginning to make it 9 digits long.

Last edited by PutneyCat (May 4, 2021 10:24:30)

deck26
Scratcher
1000+ posts

Most efficient way to get every possible combination

Or just set a list of 9 items to 0. That's your first value 000….00. Now in a loop

look at end of list - if item is less than 2 increase by 1 else move back to previous item in list and do the same test.

When you find a value to change also change all later items n the list to 0.

That gives you the next value. You then either repeat the loop or stop because your value is 222……22 (or, as a more general case you hit the state of wanting to change item 1 but it is already 2).

@PutneyCat's solution is a good one though.

Last edited by deck26 (May 4, 2021 10:44:37)

awesome-llama
Scratcher
1000+ posts

Most efficient way to get every possible combination

Here's my solution:

https://scratch.mit.edu/projects/525244602





I use a digits list to store the state of all the digits. You want 9 digit numbers so there are 9 list items.
Every time the main loop runs, the first digit is incremented by 1. If it is above 3, then move over to the “tens” digit (the second item) and increment it instead. This keeps going for other digits too.
So, my list is a representation of a ternary number (base 3) without actually needing to convert to and from base 10.

Last edited by awesome-llama (May 4, 2021 10:47:14)

Ankit_Anmol
Scratcher
500+ posts

Most efficient way to get every possible combination

Thanks! That was really helpful

Powered by DjangoBB