Last active
February 12, 2021 22:32
-
-
Save jessejohnson/b51b039ed5aa47555b50733ea8622dff to your computer and use it in GitHub Desktop.
Can we replace the for loops with reduce?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func countApplesAndOranges(s: Int, t: Int, a: Int, b: Int, apples: [Int], oranges: [Int]) -> Void { | |
var numA = 0 | |
var numO = 0 | |
for ap in apples{ | |
if(ap+a) >= s{ | |
numA += 1 | |
} | |
} | |
for or in oranges{ | |
if(or+b) <= t{ | |
numO += 1 | |
} | |
} | |
//reduce! | |
numA = apples.reduce(0){acc, elem in | |
if (elem+a) >= s{ | |
return acc + 1 | |
} | |
return acc | |
} | |
numO = oranges.reduce(0){acc, elem in | |
if (elem+b) <= t{ | |
return acc + 1 | |
} | |
return acc | |
} | |
//filter! | |
numA = apples.filter{elem in | |
(elem+a) >= s | |
}.count | |
numO = oranges.filter{elem in | |
(elem+b) <= t | |
}.count | |
print(numA) | |
print(numO) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment