How do I get every possible UInt8 array combination up to a certain array size?

130 Views Asked by At

I am trying to get every possible UInt8 array up to an array size of 100 in Swift. So far, I have the following code:

var arrays = [[UInt8]]()
for size in 1...100 {
    let arr = Array(repeating: 255, count: size) as [UInt8]
    arrays.append(arr)
}

The code so far just creates an array filled with 255 how many ever times specified by the for loop. Instead, I want the code to create an array for every array size that lists all possible combinations. For example, when size is one, the arrays should look like the following:

[0], [1], [2], [3], [4], so on until [255]

And when size is two, the arrays should look like this:

[0,0], [0,1], [0,2], [0,3], [0,4], so on until [0,255]
[1,0], [1,1], [1,2], [1,3], [1,4], so on until [1,255]

This should continue up to where size is 100. Is there any way that I can accomplish this using Swift?

Thanks in advance.

1

There are 1 best solutions below

0
On

These kind of problems can now be tackled with Swift Algorithms.

see combinations(ofCount:) :

import Algorithms

let combinations = (1...5).combinations(ofCount: 2)
combinations.forEach { combination in
    print(combination)
}

output:

[1, 2]
[1, 3]
[1, 4]
[1, 5]
[2, 3]
[2, 4]
[2, 5]
[3, 4]
[3, 5]
[4, 5]