Imagine this loop:
for i in range(3):
for j in range(3):
for k in range(3):
print("{}{}{}".format(letter, number, symbol))
I want to generate this sequence numerically - without a nested for loop, by manipulating the i, j and k values. What's the formula to covering every permutation of these 3 values?
Given 3 numbers I, j, k how do I calculate the next position without repeats? I should add that i, j, k might have different sizes.
I've tried using python itertools permutations and I've used a counting algorithm.
I tried to generate it with a counting algorithm. But I think there's something obvious in my counting algorithm that I'm missing, but I'm not sure what it is.
Imagine a function called .tick that produces the next item in the sequence without repeats.
My counting algorithm looks like this. You can find it on Repl.it here.
class Tick:
def __init__(self, collections, func):
self.collections = collections
self.indexes = []
self.loops = 0
self.reset = -1
self.func = func
self.started = False
for collection in collections:
self.indexes.append(0)
def size(self):
total = len(self.collections[0])
for collection in self.collections[1:]:
total = total * len(collection)
return total
def tick(self):
if self.started:
if self.reset != -1:
self.indexes[self.reset + 1] = 0
for index in range(self.reset + 1, len(self.indexes)):
self.indexes[index] = 0
self.reset = -1
else:
self.loop = len(self.indexes) - 1
while self.loop != -1 and self.indexes[self.loop] == len(self.collections[self.loop]) - 1:
self.loop = self.loop - 1
if self.loop == -1:
return
self.indexes[self.loop] = self.indexes[self.loop] + 1
if self.loop < len(self.indexes) - 1:
self.reset = self.loop
else:
self.started = True
items = []
for loop in range(len(self.indexes)):
items.append(self.collections[loop][self.indexes[loop]])
return self.func(items)
a = ["0", "1", "2"]
b = ["0", "1", "2"]
c = ["0", "1", "2"]
def printer(items):
output = ""
for item in items:
output += item
return output
ticker = Tick([a, b, c], printer)
print(ticker.size())
for index in range(ticker.size()):
print(ticker.tick())
Unfortunately it produces the following
27
000
001
002
012
010
011
012
022
020
021
022
122
100
101
102
112
110
111
112
122
120
121
122
222
200
201
202
Notice the following are duplicated. I used this duplicate line finder.
COUNT | LINE
-----------------------------------------------------
3 | 122
2 | 012
2 | 022
2 | 112
1 | 000
1 | 001
1 | 002
1 | 010
1 | 011
1 | 020
1 | 021
1 | 100
1 | 101
1 | 102
1 | 110
1 | 111
1 | 120
1 | 121
1 | 200
1 | 201
1 | 202
1 | 222
-----------------------------------------------------
27 | TOTAL LINES
22 | DISTINCT LINES