loading...

Discussion on: Daily Challenge #81 - Even or Odd

EarlWare

A Swift solution:

``````import Foundation

/*
evenOrOdds takes a list of numbers and outputs which total is greater, all odds, or all evens.

@param numList: [Int] list of integers of any length

@return String describing which value is greater or even they are equal.
*/
func evenOrOdds(_ numList:[Int]) -> String {
let evenWin = "Even is greater than Odd"
let oddWin  = "Odd is greater than Even"
let draw    = "Even and Odd are the same"

var accum = 0

for num in numList {
if num % 2 == 0 {
accum += num
} else {
accum -= num
}
}

if accum > 0 {
return evenWin
} else if accum < 0 {
return oddWin
}

return draw
}

// utility function to generate a list of Ints
func genRandoms() {
var randomGen = SystemRandomNumberGenerator.init()
var randomList = [Int](repeating: 1, count: 100)

for index in 0..<randomList.count {
randomList[index] = Int(bitPattern: randomGen.next(upperBound: UInt(bitPattern: 500)))
}

print(randomList)
}

let example1 = [104, 258, 303, 66, 310, 363, 41, 180, 299, 208, 355, 135, 234, 214, 243, 350, 494, 408, 37, 438, 335, 101, 489, 449, 44, 136, 285, 408, 432, 350, 343, 271, 9, 286, 304, 451, 26, 388, 303, 259, 212, 434, 241, 20, 199, 201, 55, 318, 110, 48, 135, 359, 345, 277, 424, 23, 249, 348, 419, 301, 409, 316, 163, 81, 319, 440, 466, 185, 57, 102, 230, 446, 454, 369, 21, 284, 7, 161, 136, 113, 471, 2, 217, 350, 361, 334, 437, 421, 29, 290, 123, 326, 360, 142, 330, 354, 325, 140, 312, 116]

let example2 = [407, 461, 144, 458, 246, 103, 5, 241, 166, 75, 300, 215, 430, 424, 325, 283, 81, 420, 405, 485, 266, 23, 71, 42, 290, 189, 364, 382, 368, 203, 89, 317, 26, 465, 94, 84, 133, 223, 204, 189, 430, 400, 273, 476, 222, 246, 455, 137, 258, 470, 428, 242, 173, 285, 428, 147, 105, 306, 211, 489, 383, 414, 93, 433, 257, 449, 485, 183, 160, 302, 307, 227, 5, 361, 188, 18, 356, 442, 16, 409, 309, 152, 94, 319, 264, 147, 247, 359, 25, 364, 58, 144, 218, 16, 401, 62, 391, 110, 399, 24]

let example3 = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2]

// used to generate a draw data set, but just explicitly defined after copying the output
//var example3 = [Int](repeating: 1, count: 50)
//example3.append(contentsOf: [Int](repeating: 2, count: 25))

print(evenOrOdds(example1),"")

print(evenOrOdds(example2),"")

print(evenOrOdds(example3),"\n")

``````

Outputs:

``````Even is greater than Odd
Odd is greater than Even
Even and Odd are the same

Program ended with exit code: 0
``````

Went with accumulating by adding evens and subtracting odds so in a case where the list of values being summed up ends up greater than Int.max you don't get a runtime error...... not that these test cases are likely to total greater than 9223372036854775807.... haha