Home > Software design >  Array Performing XOR On Itself With Offset
Array Performing XOR On Itself With Offset

Time:08-14

Trying to implement an autocorrelation algorithm, meaning, for example:

let exampleData: [Float] = [1, 2, 3, 4, 5]

Trying to find the fastest way to evaluate 1 ^ 2 2 ^ 3 3 ^ 4 4 ^ 5.

Essentially, iterate through the array, and for every element, calculate the result of XOR between it and another element a set distance away.

Trouble is, this also has to be done for many different values of the offset.

Right now I just have a nested for loop, and I don't know how to make it faster...

var data: [Bool]
var result: [Int]

...

for offset in start..<end {
    for index in 0..<(end - offset) {
        if (data[index] ^ data[index   frequency]) {
            result[offset]  = 1
        }
    }
}

CodePudding user response:

Sounds like you might want windows(ofCount:) from swift-algorithms:

https://github.com/apple/swift-algorithms/blob/main/Guides/Windows.md

That will give you a sliding window through any collection, and if your offset is relatively small (or you actually want the whole window, e.g. to do a moving average), that will be great.

The swift-algorithms stuff is nice since it's more optimized than whatever you'll do ad hoc, plus offers lazy eval.

You might also consider aligning and zipping up your sequence and then mapping over that, e.g.:

zip(data, data.dropFirst(offset))
    .map { $0 ^ $1 }

...and so on

  • Related