I've working my way through codewars, and I've come across mazerunner (https://www.codewars.com/kata/maze-runner/train/javascript) I've been stumped for about 2 days!
function mazeRunner(maze, directions) {
//find start value
var x = 0; //x position of the start point
var y = 0; //y position of the start point
for (var j = 0 ; j < maze.length ; j++){
if (maze[j].indexOf(2) != -1){
x = j;
y = maze[j].indexOf(2)
}
} // end of starting position forloop
console.log(x + ', ' + y)
for (var turn = 0 ; turn < directions.length ; turn++){
if (directions[turn] == "N"){
x -= 1;
}
if (directions[turn] == "S"){
x += 1;
}
if (directions[turn] == "E"){
y += 1;
}
if (directions[turn] == "W"){
y -= 1;
}
if (maze[x][y] === 1){
return 'Dead';
}else if (maze[x][y] === 3){
return 'Finish';
}
if (maze[x] === undefined || maze[y] === undefined){
return 'Dead';
}
}
return 'Lost';
}
When I run this, it works on most of the scenarios, however on the last one I get the following error
TypeError: Cannot read property '3' of undefined
at mazeRunner
at /home/codewarrior/index.js:87:19
at /home/codewarrior/index.js:155:5
at Object.handleError
Any help would be appreciated! I'm pulling my hair out over this one!
The problem of your solution is that after the move, you just check the value of maze[x][y]
In the test that fails, maze[x] will be at some point undefined (moves south for a while). I guess at that same point y would be 3, hence the error Cannot read property '3' of undefined
To avoid that, you should move up the code where you test for undefined, before trying to access the coordinates:
// move this as first check
if (maze[x] === undefined || maze[y] === undefined){
return 'Dead';
}
Related
We travel around the city in 4 cardinal directions and can only take 10 steps and must return to the place where we started. My program breaks on tests (didn't come to the place where I started from). Where is the mistake? I know that it can be solved easier, but I would like to know what my mistake is
function isValidWalk(walk) {
let x = 0, y = 0;
let result = 0;
if(walk.length !== 10) {
return false;
}
for (let i = 0; i < 10; i++) {
if(walk[i] === 'n') {
x += 1;
}
else if(walk[i] === 's') {
x += -1
}
else if(walk[i] === 'w') {
y += -1;
}
else if(walk[i] === 'e') {
y += 1;
}
}
result = x + y;
if(result === 0) {
return true;
}
return false;
}
You need ot check x and y directly. Their values should be zero, because you can not go north and west to get a neutral position.
if (x === 0 && y === 0) return true;
return false;
For example look to this walk
NWSSEN
There you have a balanced north and south, as well west and east.
I am having real trouble finding where my loop is. I run the code and it hangs. I am trying to make a circuits game where there are circuits for the user to connect. But I am getting stuck at square one even setting up the map to make sure it is solvable. There is an infinite loop but I can't find it I looked and looked... here is the code.`
//maxLength of circut board is the board
let theHighestMaxLength = 10;
let board;
let gridX = 10;
let gridY = 10;
let perX = 10;
let perY = 10;
//s is here so we don't have to pass it everywhere the square we are looking at in functions
let s=null;
//length and usedsquares and begin are here to be used across functions
let length=0;
let usedSquares=0;
let begin=null;
class Asquare {
constructor(x, y) {
this.x = x;
this.y = y;
this.isCircut = false;
this.isWire = false;
this.OtherCircut = null;
this.Left = null;
this.Right = null;
this.Top = null;
this.Bottom = null;
this.otherCircut = null;
this.isBlank = false;
}
drawSelf() {
if (this.isCircut) {
rectMode(CENTER)
var xx = max(this.otherCircut.x, this.x);
var yy = max(this.otherCircut.y, this.y);
fill(color(xx * 25, yy * 25, 0));
square((this.x + 0.5) * perX, (this.y + 0.5) * perY, perX);
}
else if (this.isWire) {
fill(color(this.otherCircut.x * 20, this.otherCircut.y * 20, 0));
circle((this.x + 0.5) * perX, (this.y + 0.5) * perY, perX);
}
else if (this.isBlank) {
fill(color(0, 204, 0))
circle((this.x + 0.5) * perX, (this.y + 0.5) * perY, perX);
}
}
}
function handleWireMove(){
s.isWire = true;
//remember the starting circut
s.otherCircut = begin;
informAll(s);
//the length is used
length++;
}
function informAll() {
//tell all the other squares of s
if (s.x - 1 >= 0) {
board[s.x - 1][s.y].Right = s;
}
if (s.x + 1 < gridX) {
board[s.x + 1][s.y].Left = s;
}
if (s.y - 1 >= 0) {
board[s.x][s.y - 1].Bottom = s;
}
if (s.y + 1 < gridY) {
board[s.x][s.y + 1].Top = s;
}
//the used squares is now higher
usedSquares++;
}
function setup() {
createCanvas(gridX * perX, gridY * perY);
noLoop();
//fill the board with squares
board = new Array(gridX).fill(0).map(() => new Array(gridY).fill(0));
for (var x = 0; x < gridX; x++) {
for (var y = 0; y < gridY; y++) {
board[x][y] = new Asquare(x, y);
}
}
//the number of squares in the grid used
usedSquares = 0;
//till the board is full
while (usedSquares < gridX * gridY) {
//get a random x y
var rx = floor(random(gridX));
var ry = floor(random(gridY));
//create an s and begin var s for every nw square and begin for the first
s = board[rx][ry];
//if this square is already in use
if(s.isBlank||s.isCircut||s.isWire){continue;}
//begin at this square
begin = s;
//if there is some way to go
if (s.Left == null || s.Right == null || s.Top == null || s.Bottom == null) {
// get a random length to try and reach
var maxLength = floor(random(1, theHighestMaxLength))
//the starting length
length = 0;
begin.isCircut = true;
//inform all the surounding squares and increase the number of used
informAll();
//while the length isn't full
while (length <= maxLength) {
//add an option count for left right top botoom
var numOption = s.Left == null ? 1 : 0;
numOption = s.Right == null ? numOption + 1 : numOption;
numOption = s.Top == null ? numOption + 1 : numOption;
numOption = s.Bottom == null ? numOption + 1 : numOption;
//if there are no toptions to move we must stop here ot if the maxLength is reached
if (numOption == 0 || length == maxLength) {
//this is a circut the beigin circut is begin the begin other circut is this final one
s.isCircut = true;
s.isWire = false;
s.otherCicut = begin;
begin.otherCircut = s;
//make sure the loop ends
length=9999;
break;
}
//pick a random direction number
var randomChoiseNumber = floor(random(numOption));
//if left is an option
if (s.Left == null) {
//if r is already 0 that means we picked left
if (randomChoiseNumber == 0) {
//while left is an option and the maxlength isn't hit and left isn't off the map
while (s.Left == null && length < maxLength && s.x - 1 >= 0) {
//set s to the left
s = board[s.x - 1][s.y];
//handleWireMove the move
handleWireMove()
}
//continue we used the direction
continue;
} else {
//we passed an option reduce the number
randomChoiseNumber--;
}
}
//if right is an option
if (s.Right == null) {
//if this is the zero choice
if (randomChoiseNumber == 0) {
//if right is not off the map and an option while the length is not hit
while (s.Right == null && length < maxLength && s.x + 1 < gridX) {
//set s to right
s = board[s.x + 1][s.y];
//handleWireMove the move
handleWireMove();
}
continue;
} else {
//reduce the number as we passed an option
randomChoiseNumber--;
}
}
//if top is an option
if (s.Top == null) {
//if this is the zero option
if (randomChoiseNumber == 0) {
//while top is a choise and the length is not reached and top is not off the map
while (s.Top == null && length < maxLength && s.y - 1 >= 0) {
//move to the top
s = board[s.x][s.y - 1];
//handleWireMove the move
handleWireMove();
}
//continue the direction is used up
continue;
} else {
//we passed a number reduce the choise number
randomChoiseNumber--;
}
}
//if bottom is an option
if (s.Bottom == null) {
//if this is the zero option
if (randomChoiseNumber == 0) {
//while bottom is a choise and the length is not reached and it is not off the map
while (s.Bottom == null && length < maxLength && s.y + 1 < gridY) {
//go to the bottom
s = board[s.x][s.y + 1];
//handleWireMove the move
handleWireMove();
}
}
}
}
}
else {
//if there was no way to go the square is blank tell the others and increace usedSquares
s.isBlank = true;
informAll();
}
}
}
function drawAll() {
board.forEach(a => a.forEach(b => b.drawSelf()));
}
function draw() {
background(gridX * perX);
drawAll();
}
The problem is in the setup function but I can't find it. Please help
The problem is that you compute the number of available numOption only based on whether the randomly selected grid square has unconnected slots (Left, Top, Right, or Bottom) without considering whether the value of s.x and s.y make it possible to select one of those directions). As a result your inner loop repeats infinitely because it never calls handleWireMove() and thus never increases length.
The code below is modified with some extra logging and it becomes obvious where the infinite loop is (it eventually prints 'we failed to make a choice. that is not good' forever):
//the number of squares in the grid used
usedSquares = 0;
//till the board is full
while (usedSquares < gridX * gridY) {
console.log(usedSquares);
//get a random x y
var rx = floor(random(gridX));
var ry = floor(random(gridY));
//create an s and begin var s for every nw square and begin for the first
s = board[rx][ry];
//if this square is already in use
if (s.isBlank || s.isCircut || s.isWire) {
continue;
}
//begin at this square
begin = s;
//if there is some way to go
if (
s.Left == null ||
s.Right == null ||
s.Top == null ||
s.Bottom == null
) {
// get a random length to try and reach
var maxLength = floor(random(1, theHighestMaxLength));
//the starting length
length = 0;
begin.isCircut = true;
//inform all the surounding squares and increase the number of used
informAll();
//while the length isn't full
console.log('beggining inner loop');
while (length <= maxLength) {
//add an option count for left right top botoom
var numOption = s.Left == null ? 1 : 0;
numOption = s.Right == null ? numOption + 1 : numOption;
numOption = s.Top == null ? numOption + 1 : numOption;
numOption = s.Bottom == null ? numOption + 1 : numOption;
//if there are no toptions to move we must stop here ot if the maxLength is reached
if (numOption == 0 || length == maxLength) {
//this is a circut the beigin circut is begin the begin other circut is this final one
s.isCircut = true;
s.isWire = false;
s.otherCicut = begin;
begin.otherCircut = s;
//make sure the loop ends
console.log('no options, abort');
length = 9999;
break;
}
//pick a random direction number
var randomChoiseNumber = floor(random(numOption));
//if left is an option
if (s.Left == null) {
//if r is already 0 that means we picked left
if (randomChoiseNumber == 0) {
//while left is an option and the maxlength isn't hit and left isn't off the map
while (s.Left == null && length < maxLength && s.x - 1 >= 0) {
//set s to the left
s = board[s.x - 1][s.y];
//handleWireMove the move
handleWireMove();
}
//continue we used the direction
continue;
} else {
//we passed an option reduce the number
randomChoiseNumber--;
}
}
//if right is an option
if (s.Right == null) {
//if this is the zero choice
if (randomChoiseNumber == 0) {
//if right is not off the map and an option while the length is not hit
while (s.Right == null && length < maxLength && s.x + 1 < gridX) {
//set s to right
s = board[s.x + 1][s.y];
//handleWireMove the move
handleWireMove();
}
continue;
} else {
//reduce the number as we passed an option
randomChoiseNumber--;
}
}
//if top is an option
if (s.Top == null) {
//if this is the zero option
if (randomChoiseNumber == 0) {
//while top is a choise and the length is not reached and top is not off the map
while (s.Top == null && length < maxLength && s.y - 1 >= 0) {
//move to the top
s = board[s.x][s.y - 1];
//handleWireMove the move
handleWireMove();
}
//continue the direction is used up
continue;
} else {
//we passed a number reduce the choise number
randomChoiseNumber--;
}
}
//if bottom is an option
if (s.Bottom == null) {
//if this is the zero option
if (randomChoiseNumber == 0) {
//while bottom is a choise and the length is not reached and it is not off the map
while (s.Bottom == null && length < maxLength && s.y + 1 < gridY) {
//go to the bottom
s = board[s.x][s.y + 1];
//handleWireMove the move
handleWireMove();
}
}
}
console.log('we failed to make a choice. that is not good');
}
console.log('exited inner loop');
} else {
//if there was no way to go the square is blank tell the others and increace usedSquares
s.isBlank = true;
informAll();
}
}
Here is a working version that correctly checks not only if there is an opening to the Left/Top/Right/Bottom, but also if that direction is possible (not off the edge of the grid):
//maxLength of circut board is the board
let theHighestMaxLength = 10;
let board;
let gridX = 10;
let gridY = 10;
let perX = 10;
let perY = 10;
//s is here so we don't have to pass it everywhere the square we are looking at in functions
let s = null;
//length and usedsquares and begin are here to be used across functions
let length = 0;
let usedSquares = 0;
let begin = null;
class Asquare {
constructor(x, y) {
this.x = x;
this.y = y;
this.isCircut = false;
this.isWire = false;
this.OtherCircut = null;
this.Left = null;
this.Right = null;
this.Top = null;
this.Bottom = null;
this.otherCircut = null;
this.isBlank = false;
}
drawSelf() {
if (this.isCircut) {
rectMode(CENTER);
var xx = max(this.otherCircut.x, this.x);
var yy = max(this.otherCircut.y, this.y);
fill(color(xx * 25, yy * 25, 0));
square((this.x + 0.5) * perX, (this.y + 0.5) * perY, perX);
} else if (this.isWire) {
fill(color(this.otherCircut.x * 20, this.otherCircut.y * 20, 0));
circle((this.x + 0.5) * perX, (this.y + 0.5) * perY, perX);
} else if (this.isBlank) {
fill(color(0, 204, 0));
circle((this.x + 0.5) * perX, (this.y + 0.5) * perY, perX);
}
}
}
function handleWireMove() {
s.isWire = true;
//remember the starting circut
s.otherCircut = begin;
informAll(s);
//the length is used
length++;
}
function informAll() {
//tell all the other squares of s
if (s.x - 1 >= 0) {
board[s.x - 1][s.y].Right = s;
}
if (s.x + 1 < gridX) {
board[s.x + 1][s.y].Left = s;
}
if (s.y - 1 >= 0) {
board[s.x][s.y - 1].Bottom = s;
}
if (s.y + 1 < gridY) {
board[s.x][s.y + 1].Top = s;
}
//the used squares is now higher
usedSquares++;
}
function setup() {
createCanvas(gridX * perX, gridY * perY);
noLoop();
//fill the board with squares
board = new Array(gridX).fill(0).map(() => new Array(gridY).fill(0));
for (var x = 0; x < gridX; x++) {
for (var y = 0; y < gridY; y++) {
board[x][y] = new Asquare(x, y);
}
}
//the number of squares in the grid used
usedSquares = 0;
//till the board is full
while (usedSquares < gridX * gridY) {
console.log(usedSquares);
//get a random x y
var rx = floor(random(gridX));
var ry = floor(random(gridY));
//create an s and begin var s for every nw square and begin for the first
s = board[rx][ry];
//if this square is already in use
if (s.isBlank || s.isCircut || s.isWire) {
continue;
}
//begin at this square
begin = s;
//if there is some way to go
if (
s.Left == null ||
s.Right == null ||
s.Top == null ||
s.Bottom == null
) {
// get a random length to try and reach
var maxLength = floor(random(1, theHighestMaxLength));
//the starting length
length = 0;
begin.isCircut = true;
//inform all the surounding squares and increase the number of used
informAll();
//while the length isn't full
console.log('beggining inner loop');
while (length <= maxLength) {
//add an option count for left right top botoom
var numOption = s.Left == null && s.x - 1 >= 0 ? 1 : 0;
numOption = s.Right == null && s.x + 1 < gridX ? numOption + 1 : numOption;
numOption = s.Top == null && s.y - 1 >= 0 ? numOption + 1 : numOption;
numOption = s.Bottom == null && s.y + 1 < gridY ? numOption + 1 : numOption;
//if there are no toptions to move we must stop here ot if the maxLength is reached
if (numOption == 0 || length == maxLength) {
//this is a circut the beigin circut is begin the begin other circut is this final one
s.isCircut = true;
s.isWire = false;
s.otherCicut = begin;
begin.otherCircut = s;
//make sure the loop ends
console.log('no options, abort');
length = 9999;
break;
}
//pick a random direction number
var randomChoiseNumber = floor(random(numOption));
//if left is an option
if (s.Left == null && s.x - 1 >= 0) {
//if r is already 0 that means we picked left
if (randomChoiseNumber == 0) {
//while left is an option and the maxlength isn't hit and left isn't off the map
while (s.Left == null && length < maxLength && s.x - 1 >= 0) {
//set s to the left
s = board[s.x - 1][s.y];
//handleWireMove the move
handleWireMove();
}
//continue we used the direction
continue;
} else {
//we passed an option reduce the number
randomChoiseNumber--;
}
}
//if right is an option
if (s.Right == null && s.x + 1 < gridX) {
//if this is the zero choice
if (randomChoiseNumber == 0) {
//if right is not off the map and an option while the length is not hit
while (s.Right == null && length < maxLength && s.x + 1 < gridX) {
//set s to right
s = board[s.x + 1][s.y];
//handleWireMove the move
handleWireMove();
}
continue;
} else {
//reduce the number as we passed an option
randomChoiseNumber--;
}
}
//if top is an option
if (s.Top == null && s.y - 1 >= 0) {
//if this is the zero option
if (randomChoiseNumber == 0) {
//while top is a choise and the length is not reached and top is not off the map
while (s.Top == null && length < maxLength && s.y - 1 >= 0) {
//move to the top
s = board[s.x][s.y - 1];
//handleWireMove the move
handleWireMove();
}
//continue the direction is used up
continue;
} else {
//we passed a number reduce the choise number
randomChoiseNumber--;
}
}
//if bottom is an option
if (s.Bottom == null && s.y + 1 < gridY) {
//if this is the zero option
if (randomChoiseNumber == 0) {
//while bottom is a choise and the length is not reached and it is not off the map
while (s.Bottom == null && length < maxLength && s.y + 1 < gridY) {
//go to the bottom
s = board[s.x][s.y + 1];
//handleWireMove the move
handleWireMove();
}
}
}
console.log('we failed to make a choice. that is not good');
}
console.log('exited inner loop');
} else {
//if there was no way to go the square is blank tell the others and increace usedSquares
s.isBlank = true;
informAll();
}
}
}
function drawAll() {
board.forEach((a) => a.forEach((b) => b.drawSelf()));
}
function draw() {
background(gridX * perX);
drawAll();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/p5.js"></script>
One closing though: this bug is a symptom of this code being horribly complicated and violating fundamental principles of good design such as not having shared global state that is updated as a side effect of function calls.
Beginner coder here, so forgive me, I've searched but can't find anything to help me with this basic issue.
I have grid in the form of arrays within an array called 'cells', populated with 1s and 0s, representing living and dead cells. For each place on the grid I want to search the 8 places that surround it. I execute this with for loops:
//iterate through the whole board
for (y = 0; y < cells.length; y++) {
for (x = 0; x < cells[0].length; x++) {
let liveNeighbours = 0;
let deadNeighbours = 0;
//iterate through neighbours in 9 cell grid, ignore the cell itself
for (yy = y - 1; yy <= y + 1; yy++) {
for (xx = x - 1; xx <= x + 1; xx++) {
if (yy !== y || xx !== x) {
if (typeof(cells[yy][xx]) !== 'undefined') {
if (cells[yy][xx] === 1) {
liveNeighbours++;
} else if (cells[yy][xx] === 0) {
deadNeighbours++;
}
}
}
}
}
console.log('Looking at cell ' + x + ', ' + y);
console.log('Live neighbours ' + liveNeighbours);
console.log('Dead neighbours ' + deadNeighbours);
}
}
}
}
This seems like the simplest method, although obviously it means that the search will occassionally be looking at undefined array indexes (cells[-1][-1]). I've tried to get around this by implementing a typeof check but I still receive the error:
TypeError: Cannot read property '-1' of undefined
It refuses to check the typeof because it is undefined, even though that's exactly what I want to know. What am I doing wrong here?
Maybe a better way to do it:
cells[yy]?.[xx]
Using the optional chaining operator. Will return undefined if either cells[yy] or cells[yy][xx] is undefined.
That way you don't need that if wrapper at all because undefined !== 1 and undefined !== 0.
Old code:
if (typeof(cells[yy][xx]) !== 'undefined') {
if (cells[yy][xx] === 1) {
liveNeighbours++;
} else if (cells[yy][xx] === 0) {
deadNeighbours++;
}
}
New code:
if (cells[yy]?.[xx] === 1) {
liveNeighbours++;
} else if (cells[yy]?.[xx] === 0) {
deadNeighbours++;
}
Edit: CanIUse Optional Chaining Operator? (Yes, except for IE)
You're pretty close. The problem is that typeof(cells[yy][xx]) !== "undefined" will not work when yy is out of range, because it will try to access a subscript of undefined.
Change that to
if (typeof cells[yy] !== "undefined" && typeof cells[yy][xx] !== "undefined")
i'm currently attempting to make a map generator but in the section where i randomly set pieces to be land , if i set them to anything other than 0 or "" it returns
"Uncaught TypeError: Cannot set property "1 - 15"' of undefined"
(it doesn't return "1-15", it just returns a number between 1 and the arrays length (which is 15) when it is run)
//lets every block surrounding a land peice have a 1 in 3 chance of making more land
for(let y = 0; y < proxy.length; y++){
for(let x = 0; x < proxy[y].length; x++){
if(proxy[y][x] != 0){
for(let i = -1; i <= 1; i++){
for(let j = -1; j <= 1; j++){
let run = Math.floor(Math.random() * 3)
if(run == 0){
proxy[y + i][x + j] = "o"
}
}
}
}
}
}
(full code)
https://jsfiddle.net/2q9rz38x/1/
Let's simplify this problem for a second. The actual error you see is because you are accessing proxy[A][B], where proxy[A] is undefined, and hence you get Cannot set property B of undefined.
Think for a second what possible values A can get. A is y + i in your code. You are looping y from 0 to proxy.length - 1, and you are looping i from -1 to 1.
So, the possible range for y + i will be -1 to proxy.length. That is 1 item more in both directions than it should be! (You'll agree that proxy[-1] is probably undefined, same for proxy[proxy.length]...)
The same goes for x + j of course, but this would not throw an error because it would just write new properties at proxy[something][-1] for example, which is probably not intended but is valid JavaScript.
Therefore, you'll either have to change the loop or constrain the values. Since this is a map generator on a fixed-size map, I'd guess it's more logical to constrain the result. So, you'd do something like this:
if (
y + i >= 0 &&
y + i < proxy.length &&
x + j >= 0 &&
x + j < proxy[y + i].length
) {
proxy[y + i][x + j] = "o"
}
...or, alternatively:
if ((y + i) in proxy && (x + j) in proxy[y + i]) {
proxy[y + i][x + j] = "o"
}
I've googled this and searched through the JavaScript documentation but I can't find any mention of this operator: a |ǀ| b
When I try the operator on its own I get an error but when I run the following code it runs perfectly fine:
var a, b = 0; tex = '\u0076\u0061r'
var players, score = 0, x, y, z = 1;
function f(s) {
var t = 0, r = 0;
var js = 'window';
while (t == r) {
if (t == 1) {
r = s.length;
return false;
} else {
t += 1;
} for (var i = 0; i < 20; i++) {
r = 20;i+=9000;eval(s); x = 50; y =+ 8;
z = -20; y = s;
}
if (r < 20) {
return t + 2;
}}
return true;
} while (f(tex + ' \u01C0='+'0') && score < 900) {
score = 9000.0001;}eval(y); a = 1; b += a;
x = 50;{y =+ 8;
}
// testing:
document.writeln(false |ǀ| false); // 0
document.writeln(false |ǀ| true); // 1
document.writeln(true |ǀ| false); // 1
document.writeln(true |ǀ| true); // 1
Changing the values of a and b would suggest it works like || but I just can't work out why it works with the previous code, but doesn't work on its own. Does anyone know whats going on here?
It's not an operator. It's the | operator, twice, with a "Latin letter 'Dental Click'" character in between. That character is valid in JavaScript identifiers. Thus the expression:
false |ǀ| false
(probably) means the same thing as
false | undefined | false
because there's no real variable called ǀ. (edit — Actually there probably is, otherwise you'd get a reference error.)
The | (bitwise-OR) operator treats its operands as numbers, and both false and undefined become 0.
That function f() is what's defining a window property called ǀ.