Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //: Playground - noun: a place where people can play
- import UIKit
- class Queue<T> {
- var queue : [T]!
- let MaxLen : Int
- var elementsCount : Int
- var curIndex : Int
- var lastIndex : Int
- init(length : Int, value : T) {
- queue = [T]()
- MaxLen = length
- elementsCount = 0
- curIndex = 0
- lastIndex = 0
- queue.reserveCapacity(length)
- for _ in 1...length {
- queue.append(value)
- }
- }
- func Count() -> Int {
- return elementsCount
- }
- func IsEmpty() -> Bool {
- return Count() == 0
- }
- func Enqueue(value : T) {
- if elementsCount < MaxLen {
- queue[lastIndex % MaxLen] = value
- lastIndex += 1
- elementsCount += 1
- }
- }
- func Dequeue() -> T? {
- if (!IsEmpty()) {
- let i = curIndex
- elementsCount -= 1
- curIndex = (curIndex + 1) % MaxLen
- return queue![i]
- }
- return nil
- }
- }
- class M {
- let clones = 4
- let count = 10
- let total : Int
- var p1 : Queue<Int>
- var p2 : Queue<Int>
- init() {
- total = clones * count
- p1 = Queue<Int>(length: total, value: 0)
- p2 = Queue<Int>(length: total, value: 0)
- Fill()
- }
- private func Run() -> Int {
- var r = 0
- repeat {
- Step();
- r += 1
- } while !p1.IsEmpty() && !p2.IsEmpty()
- return r
- }
- private func Step() {
- let c1 = p1.Dequeue()!
- let c2 = p2.Dequeue()!
- if (c1 > c2) {
- p1.Enqueue(c1)
- p1.Enqueue(c2)
- }
- else if (c1 < c2) {
- p2.Enqueue(c2)
- p2.Enqueue(c1)
- }
- else {
- print("Pair")
- if (p1.Count() < p2.Count()) {
- p1.Enqueue(c1)
- p1.Enqueue(c2)
- }
- else if (p1.Count() > p2.Count()) {
- p2.Enqueue(c2)
- p2.Enqueue(c1)
- }
- else {
- print("Pair count")
- p1.Enqueue(c1)
- p2.Enqueue(c2)
- }
- }
- }
- private func Fill() {
- var a = [Int]()
- a.reserveCapacity(count)
- for _ in 0..<count {
- a.append(clones)
- }
- FillP(p1, a: &a)
- FillP(p2, a: &a)
- }
- private func FillP(p : Queue<Int>, inout a : [Int]) {
- for _ in 0..<total/2 {
- repeat {
- let index = Rand()
- if a[index] > 0 {
- a[index] -= 1
- p.Enqueue(index)
- break
- }
- } while true
- }
- }
- private func Rand() -> Int {
- return Int(arc4random_uniform(UInt32(count)))
- }
- }
- print(M().Run())
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement