Last active
November 23, 2016 10:43
-
-
Save mimol91/d4b63d83db7b1418a4fe66d17aac4576 to your computer and use it in GitHub Desktop.
map rand
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const shipConfig = [ | |
[4], | |
[3], | |
[2], | |
[1], | |
[1], | |
[1], | |
[1] | |
]; | |
// Direction 0 - Vertical | |
// Direction 1 - Horizontal | |
// x, y are starting point | |
const placeShip = function (size, direction, x, y, map) { | |
for (var i = 0; i < size; i++) { | |
var xx = x + i * (direction); | |
var yy = y + i * (!direction); | |
map['' + xx + yy] = 1 | |
} | |
}; | |
var getRandomInt = function(min, max) { | |
return Math.floor(Math.random() * (max - min + 1) + min); | |
}; | |
var cc = function(width, height) { | |
var map = {}; | |
const canBePlaced = function(size, direction, x, y, map) { | |
if (direction) { | |
if (x + size > width) { | |
return false | |
} | |
} else { | |
if (y + size > height) { | |
return false; | |
} | |
} | |
for (var i = 0; i < size; i++) { | |
var xx = x + i * (direction); | |
var yy = y + i * (!direction); | |
var key = '' + xx + yy; | |
if (key in map) { | |
return false; | |
} | |
} | |
return true; | |
}; | |
shipConfig.forEach(function(shipLength) { | |
var direction = +(Math.random() > 0.5); | |
do { | |
x = getRandomInt(0, width - 1); | |
y = getRandomInt(0, height - 1); | |
} while(!canBePlaced(shipLength, direction, x, y, map)); | |
placeShip(shipLength, direction, x, y, map); | |
}); | |
return map; | |
}; | |
var result = cc(10, 10); | |
console.log(result); | |
console.log(Object.keys(result).length) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment