Skip to content

Instantly share code, notes, and snippets.

@chosa91
Last active January 8, 2019 16:15
Show Gist options
  • Save chosa91/18b00a27d0f7955c37d1329536a27d5a to your computer and use it in GitHub Desktop.
Save chosa91/18b00a27d0f7955c37d1329536a27d5a to your computer and use it in GitHub Desktop.
// # Challenge2
struct TestCase {
let nums: [Int]
let expectation: Int
}
let test1 = [3, 1, 2, 3] // => output: 9 | ok
/**
3, 3 => 3
6 => 6
===> 3 + 6 = 9
*/
let test2 = [4, 1, 2, 3, 4] // => output: 19 | something wrong
/**
3, 4, 3 => 3
3, 7 => 7
10 => 10
===> 3 + 7 + 10 => 20
*/
let test3 = [5, 1, 3, 5, 6, 7] // => output: 48
/**
5, 6, 7, 4 => 4
7, 4, 11 => 11
11, 11 => 11
22 => 22
===> 4 + 11 + 11 + 22 => 48
*/
let cases = [
TestCase(nums: test1, expectation: 9),
TestCase(nums: test2, expectation: 19), // If you check it manually, you can't come out with output 19 -> It has to be 20, explanation above!
TestCase(nums: test3, expectation: 48),
]
// My sent solution:
func reductionCost(num: [Int]) -> Int {
var numbers = Array(num.dropFirst())
var costs = [Int]()
while numbers.count != 1 {
let first = numbers.removeFirst()
let second = numbers.removeFirst()
let cost = first + second
costs.append(cost)
numbers.append(cost)
}
return costs.reduce(0, +)
}
// After timeout I've reworked a little bit:
func reductionCostOptimized(num: [Int]) -> Int {
var nums = Array(num.dropFirst())
var s = 0
while nums.count > 1 {
let first = nums.removeFirst()
let second = nums.removeFirst()
s += first + second
nums.append(first + second)
}
return s
}
for test in cases {
print("\n===")
print("original: \(test.nums)\n- expectation: \(test.expectation)")
print("Fn1: \(reductionCost(num: test.nums))")
print("Fn2: \(reductionCostOptimized(num: test.nums))")
}
@chosa91
Copy link
Author

chosa91 commented Jan 8, 2019

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment