eugene.kazaev
BAN USERstruct Node {
let coins: Int
let children: [Node]
init(coins: Int = 0, children: [Node] = []) {
self.coins = coins
self.children = children
}
}
/* Tree:
0
2 1
0 3 0 0
1 0 0
*/
let tree = Node(coins: 0, children:
[Node(coins: 2, children: [Node(), Node()]),
Node(coins: 1, children: [
Node(),
Node(coins: 3, children: [Node(), Node(), Node()])
])
])
func traverse(node: Node) -> Int {
var value = node.coins == 0 ? 0 : (node.coins - 1)
for child in node.children {
value += traverse(node: child)
}
return value
}
print(traverse(node: tree)) // 3
let requirementss: [String: [String]] = [
"calculus":["english", "math2"],
"math2":["math1", "english", "arabic"],
"math1":["english"],
"english": [],
"arabic": []
]
func minSemsToFinishAllCourses(courses: [String: [String]]) -> Int {
let allCourses = Array(courses.map({ (key, value) -> [String] in
return Array([[key],value].joined())
}).joined())
return Set(allCourses).count
}
print(minSemsToFinishAllCourses(courses: requirementss))
func cubeAllDigits(in number:Int) -> Int {
var sum = 0
var left = number
while left > 0 {
let x = left % 10
sum += x * x * x
left = (left - x) / 10
}
return sum
}
print(cubeAllDigits(in: 2)) // 8
print(cubeAllDigits(in: 153)) // 153
print(cubeAllDigits(in: 103)) // 28
print(cubeAllDigits(in: 555555)) // 750
It's trickier than it seems:
Swift
class Sequence {
let a: [[Int]]
let b: [[Int]]
var ia = 0
var ib = 0
init(a: [[Int]], b: [[Int]]) {
self.a = a
self.b = b
}
func getNext() -> [Int]? {
let r1 = ia < a.count ? a[ia] : nil
let r2 = ib < b.count ? b[ib] : nil
if let r1 = r1, let r2 = r2 {
if r1[0] <= r2[0] {
ia += 1
return r1
} else {
ib += 1
return r2
}
} else {
if let r1 = r1 {
ia += 1
return r1
}
if let r2 = r2 {
ib += 1
return r2
}
}
return nil
}
}
func isIntersect(a:[Int], b:[Int]) -> Bool {
if a[0] < b[0] {
return a[1] >= b[0]
} else {
return b[1] >= a[0]
}
}
func mergeSequences(a: [[Int]], b: [[Int]]) -> [[Int]] {
var result: [[Int]] = []
let s = Sequence(a: a, b: b)
var woking = s.getNext()
if woking != nil {
while woking != nil {
let next = s.getNext()
if let next = next {
if isIntersect(a: woking!, b: next) {
woking = [min(woking![0],next[0]), max(woking![1], next[1])]
} else {
result.append(woking!)
woking = next
}
} else {
result.append(woking!)
woking = nil
}
}
}
return result
}
print(mergeSequences(a: [[1, 2], [3,9]], b: [[4,5], [8,10], [11, 12]])) // [[1, 2], [3, 10], [11, 12]]
print(mergeSequences(a: [[1, 2], [7,9]], b: [[4,5], [8,10], [11, 12]])) // [[1, 2], [4, 5], [7, 10], [11, 12]]
print(mergeSequences(a: [[1, 4], [7,9], [8,11]], b: [[4,5], [11, 12]])) // [[1, 5], [7, 12]]
Swift
- eugene.kazaev November 23, 2018