Skip to content

Instantly share code, notes, and snippets.

@karenpeng
Last active August 29, 2015 14:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save karenpeng/2048133c320ed39479ee to your computer and use it in GitHub Desktop.
Save karenpeng/2048133c320ed39479ee to your computer and use it in GitHub Desktop.
var nodes = []
var colors = ['r', 'g', 'b', 'y']
function Node(left, right, up, down, color) {
this.left = left
this.right = right
this.up = up
this.down = down
this.color = color
this.checked = false
this.needChange = false
}
function checkneighbour(node, newColor) {
node.needChange = true
var neighbours = [
node.left,
node.right,
node.up,
node.down
];
neighbours.forEach(function (neighbour) {
if (neighbour !== undefined && !neighbour.checked) {
if (neighbour.color === node.color || neighbour.color === newColor) {
neighbour.needChange = true
neighbour.checked = true
checkneighbour(neighbour)
} else {
neighbour.checked = true
}
}
});
}
function changeColor(newColor) {
nodes.forEach(function (node) {
if (node.needChange) {
node.color = newColor
node.needChange = false
}
})
}
for (var i = 0; i < 10; i++) {
//nodes.push([]);
for (var j = 0; j < 10; j++) {
//Math.random() => [0, 1)
var ran = Math.round(Math.random() * 3)
nodes.push(new Node(null, null, null, null, colors[ran]))
}
}
for (var i = 0; i < 10; i++) {
for (var j = 0; j < 10; j++) {
var node = nodes[i * 10 + j]
node.left = nodes[i * 10 + j - 1]
node.right = nodes[i * 10 + j + 1]
node.up = nodes[(i - 1) * 10 + j]
node.down = nodes[(i + 1) * 10 + j]
}
}
printColor()
checkneighbour(nodes[0], 'r')
changeColor('r')
printColor()
console.log(' ')
function printColor() {
console.log()
for (var i = 0; i < 10; i++) {
console.log(nodes[i * 10].color, nodes[i * 10 + 1].color, nodes[i * 10 + 2].color, nodes[i * 10 + 3].color, nodes[i * 10 + 4].color, nodes[i * 10 + 5].color, nodes[i * 10 + 6].color, nodes[i * 10 + 7].color, nodes[i * 10 + 8].color, nodes[i * 10 + 9].color)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment