Skip to content

Instantly share code, notes, and snippets.

@audinue
Last active August 31, 2024 19:20
Show Gist options
  • Save audinue/c6ca24caee3d21ab9315be2d3f55dbb4 to your computer and use it in GitHub Desktop.
Save audinue/c6ca24caee3d21ab9315be2d3f55dbb4 to your computer and use it in GitHub Desktop.
Random path generator
<script>
var width = 5;
var height = 5;
var length = 10;
var possible_directions = [
[0, -1, "&uarr;"], // up
[0, 1, "&darr;"], // down
[-1, 0, "&larr;"], // left
[1, 0, "&rarr;"], // right
];
loop: while (true) {
var position = [0, 0, "X"];
var path = [position];
while (true) {
if (path.length === length) {
break loop;
}
var direction_to_try = shuffle_array(possible_directions);
while (true) {
if (!direction_to_try.length) {
continue loop;
}
var direction = direction_to_try.pop();
var next_position = [
position[0] + direction[0],
position[1] + direction[1],
"X",
];
if (
find_vector(next_position, path) ||
next_position[0] < 0 ||
next_position[1] < 0 ||
next_position[0] > width - 1 ||
next_position[1] > height - 1
) {
continue;
}
position[2] = direction[2];
position = next_position;
break;
}
path.push(position);
}
}
var html = "<table border=1>";
for (var i = 0; i < height; i++) {
html += "<tr>";
for (var j = 0; j < width; j++) {
html += "<td width=30 height=30 align=center valign=middle>";
var vector = find_vector([j, i], path);
if (vector) {
html += vector[2];
} else {
html += "&nbsp;";
}
}
}
html += "</table>";
document.write(html);
function find_vector(vector, array) {
for (var i = 0; i < array.length; i++) {
if (array[i][0] === vector[0] && array[i][1] === vector[1]) {
return array[i];
}
}
}
function shuffle_array(array) {
var copy = array.slice(0);
var shuffled = [];
while (copy.length) {
shuffled.push(copy.splice(Math.floor(Math.random() * copy.length), 1)[0]);
}
return shuffled;
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment