Last active
June 16, 2018 19:42
-
-
Save emrepun/1b0262f3e998af7ee44cb5d5444b7b4d to your computer and use it in GitHub Desktop.
Sum up from top the bottom of a String Triangle with NON PRIME numbers
This file contains hidden or 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
//Implemented in Swift 4 | |
import Foundation | |
class ViewController: UIViewController { | |
var assignmentString = """ | |
215 | |
193 124 | |
117 237 442 | |
218 935 347 235 | |
320 804 522 417 345 | |
229 601 723 835 133 124 | |
248 202 277 433 207 263 257 | |
359 464 504 528 516 716 871 182 | |
461 441 426 656 863 560 380 171 923 | |
381 348 573 533 447 632 387 176 975 449 | |
223 711 445 645 245 543 931 532 937 541 444 | |
330 131 333 928 377 733 017 778 839 168 197 197 | |
131 171 522 137 217 224 291 413 528 520 227 229 928 | |
223 626 034 683 839 53 627 310 713 999 629 817 410 121 | |
924 622 911 233 325 139 721 218 253 223 107 233 230 124 233 | |
""" | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
// Call of the algorithm function with a string defined in triangle format. | |
maxSumForTriangle(triangleString: assignmentString) | |
} | |
/// In this algorithm we first reverse the triangle meaning; starting from the last line of the triangle so that we can | |
/// run through all the possible scenarios and find the maximum sum pathway. | |
func maxSumForTriangle(triangleString: String) { | |
var values = triangleString.components(separatedBy: .newlines).map { | |
$0.components(separatedBy: .whitespaces).compactMap(Int.init) | |
} | |
for line in values.indices.reversed() { | |
for column in values[line].indices { | |
// Check if the number is prime, if so we make it equal min value of Int | |
if isPrime(values[line][column]) { | |
values[line][column] = Int.min | |
print(values[line][column]) | |
} else if line + 1 < values.endIndex { | |
values[line][column] += max(values[line+1][column], values[line+1][column+1]) | |
// print(values[line][column]) | |
} | |
} | |
} | |
print(values[0][0]) | |
} | |
/// Returns a boolean value indicating if a given number is a prime number or not. | |
func isPrime(_ number: Int) -> Bool { | |
return number > 1 && !(2..<(Int(sqrt(Double(number))) + 1)).contains { number % $0 == 0 } | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment