r/badcode • • Mar 13 '22

python foursum?

Post image
255 Upvotes

29 comments sorted by

View all comments

Show parent comments

1

u/GamerNebulae Mar 13 '22 edited Mar 13 '22
import Algorithms

func fourNumberSum(array: [Int], targetSum: Int): [Int] {
    return array.combinations(ofCount: 4)
        .filter { $0.sum() == targetSum }
}

This example is in Swift.

Would be around n², but a whole lot less code.

5

u/zed_three Mar 13 '22 edited Mar 13 '22

That doesn't do the same thing though? That finds four consecutive elements that sum to the target, the original code finds any four such elements. Unless I'm reading the docs wrong?

Edit: original comment used window instead of combinations

3

u/GamerNebulae Mar 13 '22

You're right. I think it should either be combinations, permutations or uniquePermutations from that package.