Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Solución reto #45 en Swift #283

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -29,3 +29,56 @@ import Foundation
* https://retosdeprogramacion.com/semanales2022.
*
*/

internal func validArray(_ data: [Int]) -> Bool {
let lengthData = data.count
if lengthData < 3 { return false }
if data.contains(where: { $0 < 0 }) { return false }
if data.filter({ $0 == 0 }).count == lengthData { return false }
return true
}

func countGotas(_ data: [Int]) -> Int {
guard validArray(data) else {
return 0
}

var countTotal = 0
let lengthData = data.count
(1..<lengthData-1).forEach { index in
let current = data[index]
let prev = data[(0..<index)].max() ?? 0
let next = data[(index+1..<lengthData)].max() ?? 0
let min = [prev, next].min() ?? 0
let valueToSum = min - current
if valueToSum > 0 {
countTotal += valueToSum
}
}

return countTotal
}

let candidate1 = [2, 1, 2, 3, 0, 4, 0, 4]
print("En total hay \(countGotas(candidate1)) gotas de agua")

let candidate2 = [2, 3]
print("En total hay \(countGotas(candidate2)) gotas de agua")

let candidate3 = [2, 3, 2, 3, 5, 1, 5]
print("En total hay \(countGotas(candidate3)) gotas de agua")

let candidate4 = [2, 7, 2, 3, 0, 1]
print("En total hay \(countGotas(candidate4)) gotas de agua")

let candidate5 = [2, 0, 2, 3, 0, 0, 0, 4]
print("En total hay \(countGotas(candidate5)) gotas de agua")

let candidate6 = [2, 0, -2, 3, 0, 0, -1, 4]
print("En total hay \(countGotas(candidate6)) gotas de agua")

let candidate7 = [0, 0, 0, 0, 0]
print("En total hay \(countGotas(candidate7)) gotas de agua")

let candidate8: [Int] = []
print("En total hay \(countGotas(candidate8)) gotas de agua")
1 change: 0 additions & 1 deletion WeeklyChallenge2022.playground/contents.xcplayground
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,5 @@
<page name='Challenge42'/>
<page name='Challenge43'/>
<page name='Challenge44'/>
<page name='Challenge45'/>
</pages>
</playground>