I want to reduce the overhead of the MonteCarlo
Simulation in Swift language by performing concurrent programming on the outer loop while the inner loop would be executed normally. I got some info from the post
Using Grand Central Dispatch in Swift to parallelize and speed up “for" loops?, but seems to be outdated and not applying to swift 3. My code is as follows:
//constants
let outerCount = 10
let innerCount = 300
//variables
var firstMove = -1
var num = -1
var sum = [Int](repeating: 0, count: 9)
var wincount = [[Int]](repeating:[Int](repeating:0, count:9),count:10)
var candidateCount = 0
var candidate = [Int](repeating: 0, count: 9)
var maxWins = -2147483648
var winners = [Int](repeating: 0, count: outerCount)
//codeRiddle to solve
winners.withUnsafeMutableBufferPointer { winnersPtr -> Void in
DispatchQueue.concurrentPerform(iterations: outerCount) {
outerIdx -> Void in
for _ in 0...innerCount
{
firstMove = -1
for _ in 0...8
{
if firstMove == -1
{
firstMove = Int(arc4random()%UInt32(9))
}
}
num = Int(arc4random()%UInt32(3))
if num == 0
{
wincount[outerIdx][firstMove] += 0
}
else if num == 1
{
wincount[outerIdx][firstMove] += -10
}
else
{
wincount[outerIdx][firstMove] += 1
}
}
}
}
for i in 0...8
{
for j in 0...9
{
sum[i] += wincount[j][i]
}
}
for i in 0...8
{
if sum[i] > maxWins
{
maxWins = sum[i]
}
}
for i in 0...8
{
if sum[i] == maxWins
{
candidate[candidateCount] = i
candidateCount += 1
}
}
print(candidate[Int(arc4random()%UInt32(candidateCount))])