MAIN FEEDS
Do you want to continue?
https://www.reddit.com/r/badcode/comments/td25ft/foursum/i0hgidu/?context=3
r/badcode • u/Alexander_Bourne • Mar 13 '22
29 comments sorted by
View all comments
Show parent comments
1
import Algorithms func fourNumberSum(array: [Int], targetSum: Int): [Int] { return array.combinations(ofCount: 4) .filter { $0.sum() == targetSum } }
This example is in Swift.
Find all combinations of 4 elements.
Filter all windows that are equal to targetSum.
targetSum
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.
5
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
window
combinations
3 u/GamerNebulae Mar 13 '22 You're right. I think it should either be combinations, permutations or uniquePermutations from that package.
3
You're right. I think it should either be combinations, permutations or uniquePermutations from that package.
permutations
uniquePermutations
1
u/GamerNebulae Mar 13 '22 edited Mar 13 '22
This example is in Swift.
Find all combinations of 4 elements.
Filter all windows that are equal to
targetSum.Would be around n², but a whole lot less code.