Skip to content

Instantly share code, notes, and snippets.

@jessejohnson
Last active February 12, 2021 22:32
Show Gist options
  • Save jessejohnson/b51b039ed5aa47555b50733ea8622dff to your computer and use it in GitHub Desktop.
Save jessejohnson/b51b039ed5aa47555b50733ea8622dff to your computer and use it in GitHub Desktop.
Can we replace the for loops with reduce?
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