yrsamrith
5/11/2015 - 4:52 AM

## Bolk algorithm

Bolk algorithm

``````let m_size = 5
let goal = 20

m = Array(count: m_size, repeatedValue: Array(count: m_size, repeatedValue: 1))
//m = [[1,2,2,3,2],[1,4,3,1,1],[2,4,1,2,1],[3,1,4,1,1],[2,3,1,2,2]]
var x = 0
var y = 0
var x_psum = 0
var y_psum = 0

// Start initiating grid
m[0][0] = Int(arc4random_uniform(UInt32(goal-(m_size-1))))

var j_out = 0

// Start loop

do {

for i in 0...m_size-1 {
for j in 0...m_size-1 {

x_psum = 0
y_psum = 0

// Condition i and j
if i == 0 && j == 0 {
x_psum = 0
y_psum = 0

print(" C1:")

}
else if i == 0 && j > 0 {
y_psum = 0

// Calculate x_psum
if j == 1 {
x_psum = m[0][0]
} else if j > 1 {
for k in 0...j-1 {
x_psum += m[i][k]
}
}

print(" C2:")
}
else if i > 0 && j == 0 {
x_psum = 0

// Calculate y_psum
if i == 1 {
y_psum = m[0][0]
} else if i > 1 {
for k in 0...i-1 {
y_psum += m[k][j]
}
}

print(" C3:")
}
else if i > 0 && j > 0 {

// Calculate both x_psum and y_psum
// x
if j == 1 {
x_psum = m[i][0]
} else if j > 1 {
for k in 0...j-1 {
x_psum += m[i][k]
}
}

// y
if i == 1 {
y_psum = m[0][j]
} else if i > 1 {
for k in 0...i-1 {
y_psum += m[k][j]
}
}

print(" C4:")
}

x = goal - x_psum - (m_size - (j+1))
y = goal - y_psum - (m_size - (i+1))

// Pick the smallest max random number
var cell_maxRndNum = 0
if x <= y {
cell_maxRndNum = x
} else if y < x {
cell_maxRndNum = y
}

if j == m_size - 1{
x_psum = 0
for k in 0...j-1 {
x_psum += m[i][k]
}
m[i][j] = goal - x_psum // OUT
} else if i == m_size - 1 {
y_psum = 0
for k in 0...i-1 {
y_psum += m[k][j]
}
m[i][j] = goal - y_psum // OUT
} else {
// Random from 1 to maximum possible random number
m[i][j] = Int(arc4random_uniform(UInt32(cell_maxRndNum - 1))) + 1 // OUT
}

print("\(m[i][j])")

j_out = j
}

//Testing sum of row
x_psum = 0
if j_out == m_size - 1 {
for k in 0...j_out {
x_psum += m[i][k]
}
print("   x sum: \(x_psum) ")
}

println()
}
println()
} while( m[m_size-1][m_size-1] <= 0)
// End loop

//Testing sum of column

for j in 0...m_size - 1 {
var y_psum2 = 0
for i in 0...m_size - 1{
y_psum2 += m[i][j]

}
print("y: \(y_psum2) ")
}
``````