I have the following function that makes absolutely no sense why it fails:
function GetPlayersMap ( map, id ){
let compressedMap = [];
for(let x = 0; x < map.length; x++){
for(let y = 0; y < map[x].length; y++){
if(map[x][y].claimant_id != null) {console.log(map[x][y].claimant_id); console.log(id)}
if(id == null || map[x][y].claimant_id != id){
map[x][y].count = null;
}
if(map[x][y].claimant_id != null){
console.log(map[x][y]);
compressedMap.push(map[x][y]);
}
}
}
return compressedMap;
}
map is a 2d array of objects, map.count is an int that is never null when entering the function. id is an int that can be null. The expected result is that on an id input of 0 it return a compressedMap with one object that matched that. The function is called twice, with the same map and an id of 0 then null. What is printed in console is
0
0
Tile { x: 0, y: 0, claimant_id: 0, count: null, fake_claimed: false }
0
null
Tile { x: 0, y: 0, claimant_id: 0, count: null, fake_claimed: false }
This is printed regardless of if I change the 5th line to
if(id == null){
(which makes no sense, this means it is matching 0 to null)or
if(map[x][y].claimant_id != id){
Only when I change it to
if(false){
do I get the expected output of
0
0
Tile { x: 0, y: 0, claimant_id: 0, count: 1, fake_claimed: false }
0
null
Tile { x: 0, y: 0, claimant_id: 0, count: 1, fake_claimed: false }
I added a simplified example of the code
class Tile {
constructor(x, y) {
this.x = x;
this.y = y;
this.claimant_id = null;
this.count = 1;
this.fake_claimed = false;
}
}
var map = []
for (let x = 0; x < 1000; x++) {
map.push([]);
for (let y = 0; y < 1000; y++) {
map[x].push(new Tile(x, y));
}
}
map[0][0].claimant_id = 0;
function GetPlayersMap(map, id) {
let compressedMap = [];
for (let x = 0; x < map.length; x++) {
for (let y = 0; y < map[x].length; y++) {
if (map[x][y].claimant_id != null) {
console.log(map[x][y].claimant_id);
console.log(id)
}
if (id == null || map[x][y].claimant_id != id) {
map[x][y].count = null;
}
if (map[x][y].claimant_id != null) {
console.log(map[x][y]);
compressedMap.push(map[x][y]);
}
}
}
return compressedMap;
}
GetPlayersMap(map, 0);
GetPlayersMap(map, null);
GetPlayersMap(map, 0);
map.count is an int that is never null when entering the function.
I kindly disagree with that statement since because you don't copy the array or the objects nested inside so that map[x][y].count = null; will edit the array/object permanent. This might lead to the impresiion that null==0 though the code was never executed in that call.
Below the code with a deep-copy. Does this answer your question?
Since you have allot of data, I assume give the post about deep-copy a read.
class Tile {
constructor(x, y) {
this.x = x;
this.y = y;
this.claimant_id = null;
this.count = 1;
this.fake_claimed = false;
}
}
var map = []
for (let x = 0; x < 10; x++) {
map.push([]);
for (let y = 0; y < 10; y++) {
map[x].push(new Tile(x, y));
}
}
map[0][0].claimant_id = 0;
function GetPlayersMap(map, id) {
// added copy of array
const copy = JSON.parse(JSON.stringify(map));
let compressedMap = [];
for (let x = 0; x < copy.length; x++) {
for (let y = 0; y < copy[x].length; y++) {
if (id == null || copy[x][y].claimant_id != id) {
copy[x][y].count = null;
}
if (copy[x][y].claimant_id != null) {
console.log(copy[x][y]);
compressedMap.push(copy[x][y]);
}
}
}
return compressedMap;
}
GetPlayersMap(map, 0);
GetPlayersMap(map, null);
GetPlayersMap(map, 0);
Related
I am iterating over the matrix object. Which I create inside the loop, then I modify its values through the increment. When the increment reaches its maximum (51), I have to go back to the outer loop and create a new object one more element. Example: {0: 0, 1: 0}. Now I iterate over the last element in the object, if it = maximum, I go to the next one, from "1" to "0", and increment "0", and "1" = 0. Then I have to iterate over "1".
But the values are not cleared when element = maximum a bug is displayed.
const letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
function check(maxLength) {
for (let matrixLength = 0; matrixLength < maxLength; matrixLength++) {
let a = matrix(matrixLength);
let Indx;
while (Indx!==null) {
Indx = getIndex(a,letters.length);
console.log(increment(a,Indx,Indx));
}
}
}
function matrix(length) {
let matrix = {};
for (let i = 0; i <= length; i++) {
matrix[i] = 0;
}
return matrix;
}
function getIndex(matrix, arrLength) {
for (let i = Object.values(matrix).length - 1; i >= 0; i--) {
if (matrix[i]!==arrLength - 1) {
return i;
}
}
console.log('null');
return null;
}
function increment(matrix, index, prevIndex = null) {
matrix[index]++;
if (prevIndex === null || index === prevIndex) {
return matrix;
}
for (let i = index + 1; i < Object.values(matrix).length; i++) {
matrix[i] = 0;
}
return matrix;
}
check(3);
Check whether Indx is null after calling getIndex, not before the next iteration.
const letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
function check(maxLength) {
for (let matrixLength = 0; matrixLength < maxLength; matrixLength++) {
let a = matrix(matrixLength);
while (true) {
let Indx = getIndex(a, letters.length);
if (Indx == null) {
break;
}
console.log(increment(a, Indx, Indx));
}
}
}
function matrix(length) {
let matrix = {};
for (let i = 0; i <= length; i++) {
matrix[i] = 0;
}
return matrix;
}
function getIndex(matrix, arrLength) {
for (let i = Object.values(matrix).length - 1; i >= 0; i--) {
if (matrix[i] !== arrLength - 1) {
return i;
}
}
console.log('null');
return null;
}
function increment(matrix, index, prevIndex = null) {
matrix[index]++;
if (prevIndex === null || index === prevIndex) {
return matrix;
}
for (let i = index + 1; i < Object.values(matrix).length; i++) {
matrix[i] = 0;
}
return matrix;
}
check(3);
I am trying to make a Tetris game. I am trying to work on a function that rotates a 2D variable array 90 degrees (or -90).
For example, given an array like:
"-T-",
"TTT"
It would output:
"T-",
"TT",
"T-"
I have tried this function:
function rotateN90(a){
var temp = [];
for(var x = 0; x<a[0].length; x++){
temp.push("");
for(var y = 0; y<a.length; y++){
temp[x] += a[y][x];
}
}
return temp;
}
But it does not give the desired result. While it does rotate the first T-Block example given -90 degrees once, afterwards it reverts to it's original state.
Please help!
(PS: I am using KA's processing environment, so I can't use libraries or ES6)
The following code is to rotate a mxn size array to -90 degree.
function rotateN90(a){
var temp = new Array(a[0].length); // number of columns
var i=0;
for (i = 0; i < temp.length; i++) {
temp[i] = [];
}
for(i=0;i<a.length;i++){
for(let j = 0; j<a[0].length;j++){
temp[j][i]= a[i][a[i].length-1-j];
}
}
return temp;
}
If your array is :
[[1, 2,3],[4, 5, 6]]
It will rotate -90 degree and returned array will be
[[3, 6],[2, 5],[1, 4]]
class Array2D extends Array {
constructor(width, height, array) {
super();
this.width = width;
this.height = height;
for(let i = 0; i < width*height; i++) {
this[i] = array ? array[i]:0;
}
}
set(x, y, value) {
this[x+y*this.width] = value;
}
get(x, y) {
return this[x+y*this.width];
}
static swap(array2d) {
const result = new Array2D(array2d.height, array2d.width);
for(let x = 0; x < array2d.width; x++) {
for(let y = 0; y < array2d.height; y++) {
result.set(y, x, array2d.get(x, y));
}
}
return result;
}
static flip(array2d) {
const result = new Array2D(array2d.width, array2d.height);
for(let x = 0; x < array2d.width; x++) {
for(let y = 0; y < array2d.height; y++) {
result.set(x, array2d.height-1-y, array2d.get(x, y));
}
}
return result;
}
static spin(array2d) {
const swapped = Array2D.swap(array2d);
return Array2D.flip(swapped);
}
}
const a2d = new Array2D(2, 2, [1, 1, 1, 0]);
console.log(Array2D.spin(Array2D.spin(a2d)));
This should do the job, changed format though a little.
Because class notation isn't allowed in khan academy here is a modified solution
//technically this one is a little unnessecary, but I like the organization
function create2D(width, height, array) {
var arr = [];
arr.width = width;
arr.height = height;
for(var i = 0; i < width*height; i++) {
arr[i] = array ? array[i]:0;
}
return arr;
}
function set(array, x, y, value) {
array[x+y*array.width] = value;
}
function get(array, x, y) {
return array[x+y*array.width];
}
function swap(array2d) {
var result = create2D(array2d.height, array2d.width);
for(var x = 0; x < array2d.width; x++) {
for(var y = 0; y < array2d.height; y++) {
set(result, y, x, get(array2d, x, y));
}
}
return result;
}
function flip(array2d) {
var result = create2D(array2d.width, array2d.height);
for(var x = 0; x < array2d.width; x++) {
for(var y = 0; y < array2d.height; y++) {
set(result, x, array2d.height-1-y, get(array2d, x, y));
}
}
return result;
}
function spin(array2d) {
return flip(swap(array2d));
}
var a1 = create2D(2, 2, [1, 1, 1, 0]);
var a2 = spin(spin(a1));
console.log(a2);
This answer would work for flipping 90 AND flipping -90
a truthy value in the left parameter would flip it -90
a falsey value in the left parameter would flip it +90
//1 to rotate left, 0 to rotate right
function rotate(arr,left){
var newArr=[]
arr.forEach(function(a){newArr.push(a.toString())})
arr=newArr //we gonna do some wild stuff so this is to not mess with the original array given to function
arr=arr.map(function(a){return a.split``})
var newArr=new Array(arr[0].length)
for(var i=0;i<newArr.length;i++){newArr[i]=[]}
arr.forEach(function(a,i){
a.forEach(function(b,j){
newArr[j][i]=b
})
})
if(left){
newArr=newArr.map(function(a){return a.join``})
return(newArr)
}
//else(right)
newArr.map(function(a){a.reverse()})
newArr=newArr.map(function(a){a.join``})
return(newArr)
}
//example 1 (-90 degrees)
console.log("example 1(-90 degrees)",rotate(["-T-","TTT"],1))
//same example but you can use truthy or falsy values not JUST 1 or 0
console.log("example 1(-90 degrees) with another truthy value",rotate(["-T-","TTT"],{a:true}))
//example 2(+90 degrees)
console.log("example 2(+90 degrees)",rotate(["-T-","TTT"],0))
I'm new to JavaScript, I'm trying to solve leetcode question 37. I need to a create a blank two dimensional array, I initially used the method in the comments; however, it doesn't work correctly, it will change all the value. Then, I used the for loop method to create array and currently it worked correctly. But I still cannot figured out why this will happen, could anyone explain the reason why this will happen, is this because of shallow copy?
var solveSudoku = function (board) {
// let rows = new Array(9).fill(new Array(10).fill(0)),
let rows = new Array(9);
for (let i = 0; i < 9; i++) {
rows[i] = new Array(10).fill(0);
}
let cols = new Array(9);
for (let i = 0; i < 9; i++) {
cols[i] = new Array(10).fill(0);
}
let boxes = new Array(9);
for (let i = 0; i < 9; i++) {
boxes[i] = new Array(10).fill(0);
}
// let cols = new Array(9).fill(new Array(10).fill(0)),
// boxes = new Array(9).fill(new Array(10).fill(0));
for (let i = 0; i < 9; i++) {
for (let j = 0; j < 9; j++) {
let c = board[i][j];
if (c !== '.') {
let n = parseInt(c),
bx = Math.floor(j / 3),
by = Math.floor(i / 3);
// 0代表为使用,1为使用过
rows[i][n] = 1;
console.log(i, n)
cols[j][n] = 1;
// box索引
boxes[by * 3 + bx][n] = 1;
}
}
}
fill(board, 0, 0)
function fill(board, x, y) {
// 完成填充条件
if (y === 9) return true;
// 下一个点的坐标
let nx = (x + 1) % 9,
// 判断进入是否下一行
ny = (nx === 0) ? y + 1 : y;
// 如果已经填充,则进入下一个点
if (board[y][x] !== '.') return fill(board, nx, ny);
// 没有被填充过
for (let i = 1; i <= 9; i++) {
let bx = Math.floor(x / 3),
by = Math.floor(y / 3),
box_key = by * 3 + bx;
if (!rows[y][i] && !cols[x][i] && !boxes[box_key][i]) {
rows[y][i] = 1;
cols[x][i] = 1;
boxes[box_key][i] = 1;
board[y][x] = i.toString();
console.log(board[y][x])
// 递归向下一个点求解
if (fill(board, nx, ny)) return true;
// 恢复初始状态
board[y][x] = '.';
boxes[box_key][i] = 0;
rows[y][i] = 0;
cols[x][i] = 0;
}
}
return false;
}
console.log(board);
};
The problem with fill(), at least with object, is that it passes the same object, by reference, to all element of the array. So if you mutate this object, then it will mutate every object of every arrays.
Note that in your case, you are creating a new Array object using it's constructor ( new Array() ) which makes them objects.
const matrix = new Array(5).fill(new Array(5).fill(0));
console.log(matrix);
In the previous snippet, you can see that the values of the other rows, from the second one to the end, are reference to the initial row.
To get around that, you can fill you array with empty values and then use the map() to create unique object for each position in the array.
const matrix = new Array(5).fill().map(function() { return new Array(5).fill(0); });
console.log(matrix);
As you can see in the previous snippet, all the rows are now their unique reference.
This is the reason all of your values were changed.
I've applied this solution to your code. I wasn't able to test it, because I wasn't sure of the initial parameters to pass.
I've also used anonymous function here ( function() { return; } ), but I would success using arrow function ( () => {} ) instead, if you are comfortable with them. It's cleaner.
var solveSudoku = function (board) {
let rows = new Array(9).fill().map(function() { return new Array(10).fill(0); }),
cols = new Array(9).fill().map(function() { return new Array(10).fill(0); }),
boxes = new Array(9).fill().map(function() { return new Array(10).fill(0); });
for (let i = 0; i < 9; i++) {
for (let j = 0; j < 9; j++) {
let c = board[i][j];
if (c !== '.') {
let n = parseInt(c),
bx = Math.floor(j / 3),
by = Math.floor(i / 3);
// 0代表为使用,1为使用过
rows[i][n] = 1;
console.log(i, n)
cols[j][n] = 1;
// box索引
boxes[by * 3 + bx][n] = 1;
}
}
}
fill(board, 0, 0)
function fill(board, x, y) {
// 完成填充条件
if (y === 9) return true;
// 下一个点的坐标
let nx = (x + 1) % 9,
// 判断进入是否下一行
ny = (nx === 0) ? y + 1 : y;
// 如果已经填充,则进入下一个点
if (board[y][x] !== '.') return fill(board, nx, ny);
// 没有被填充过
for (let i = 1; i <= 9; i++) {
let bx = Math.floor(x / 3),
by = Math.floor(y / 3),
box_key = by * 3 + bx;
if (!rows[y][i] && !cols[x][i] && !boxes[box_key][i]) {
rows[y][i] = 1;
cols[x][i] = 1;
boxes[box_key][i] = 1;
board[y][x] = i.toString();
console.log(board[y][x])
// 递归向下一个点求解
if (fill(board, nx, ny)) return true;
// 恢复初始状态
board[y][x] = '.';
boxes[box_key][i] = 0;
rows[y][i] = 0;
cols[x][i] = 0;
}
}
return false;
}
console.log(board);
};
My code currently has a bug where my 2-d array with the bool value false suddenly contains true values before it is assigned any. My current guesses is either console.log somehow is delayed and picks up the values after it is called, with the updated values or that there is some issue that I don't understand about how scope works in javascript.
As seen below console.log(visited[i][j]) results in false for all values but the
new visited line contains true values even before the following is called.
const field_size = 800;
const cells_in_row = 5;
const frames_per_second = 1;
const cell_size = field_size / cells_in_row;
class Cell {
constructor(x,y) {
this.value = 0;
this.x = x;
this.y = y;
this.coordinates = [x*cell_size,y*cell_size];
}
fill() {
this.value = 1;
}
clear() {
this.value = 0;
}
}
const get_new_grid = (random = 0) => {
const grid = new Array(cells_in_row);
for (let i = 0; i < grid.length; i++) {
grid[i] = new Array(cells_in_row);
for (let j = 0; j < grid.length; j++) {
grid[i][j] = new Cell(i,j);
v = 0;
if (random) {
v = Math.floor(Math.random() * 2);
}
grid[i][j].value = v;
}
}
return grid;
}
const get_islands = (grid) => {
// bool array to mark visited cells
let visited = new Array(cells_in_row);
for (let i = 0; i < grid.length; i++) {
visited[i] = new Array(cells_in_row);
for (let j = 0; j < grid[0].length; j++) {
visited[i][j] = false;
}
}
console.log("New Visited", visited);
let count = 0;
let islands = [];
let island_coords = [];
for (let i = 0; i < grid.length; i++) {
for (let j = 0; j < grid.length; j++) {
if (visited[i][j] == false && grid[i][j].value == 1) {
// visit all cells in this island and increment island count
// dfs will return array of coordinates of island
[visited, island_coords] = dfs(i, j, grid, visited, island_coords);
console.log(visited);
islands.push(island_coords);
count += 1;
}
}
}
return [count, islands];
}
const dfs = (i, j, grid, visited, island_coords) => {
let row_nbr = [-1, -1, -1, 0, 0, 1, 1, 1];
let col_nbr = [-1, 0, 1, -1, 1, -1, 0, 1];
visited[i][j] = true;
island_coords.push([i,j]);
for (let k = 0; k < 8; k++) {
if (is_safe(i + row_nbr[k], j + col_nbr[k], grid, visited)) {
console.log("DFSing " + i + "," + j);
[visited, island_coords] = dfs(i + row_nbr[k], j + col_nbr[k],
grid, visited, island_coords);
}
}
return [visited, island_coords];
}
const is_safe = (i, j, grid, visited) => {
return (i >= 0 && i < grid.length &&
j >= 0 && j < grid.length &&
!(visited[i][j]) && grid[i][j].value === 1);
}
(function () {
var old = console.log;
var logger = document.getElementById('log');
console.log = function () {
for (var i = 0; i < arguments.length; i++) {
if (typeof arguments[i] == 'object') {
logger.innerHTML += (JSON && JSON.stringify ? JSON.stringify(arguments[i], undefined, 2) : arguments[i]) + '<br />';
} else {
logger.innerHTML += arguments[i] + '<br />';
}
}
}
})();
window.onload = () => {
const canvas = document.getElementById('canvas');
const grid = get_new_grid(random = 0);
grid[0][0].value = true;
grid[0][1].value = true;
grid[1][0].value = true;
grid[1][1].value = true;
const islands = get_islands(grid);
console.log(grid);
console.log(islands);
}
<!DOCTYPE html>
<html>
<body>
<script src="gameoflife.js"></script>
<pre id="log"></pre>
</body>
</html>
EDIT:
So I updated the snippet but it looks like it works on this end, however it shows the behavior I mentioned before on my own browser even with the exact same javascript code and html in the snippet.
Mentioned in the comments by Niet, objects logged to the console are live.
My problem is this:
Suppose this class, it's an example of my true code:
class TileMap {
constructor ( w, h ) {
this.tiles = [];
// init the matrix
for (var i = 0; i < h; i++) {
var a = [];
for (var j = 0; j < w; j++) {
a.push(0);
}
this.tiles[i] = a;
}
}
setTile (x, y, tile) {
this.tiles[y][x] = tile;
}
doSomething () {
this.setTile(0, 0, 1);
this.setTile(0, 1, 2);
}
}
// What's happening is when I use like this:
var player = {};
player.map = new TileMap(32, 90, 90);
player.map.doSomething();
console.log("before Tile[0][0] = " + player.map.tiles[0][0]);
player.map.setTile(0, 0, 3);
console.log("after Tile[0][0] = " + player.map.tiles[0][0]);
Shows me the follow output:
before Tile[0][0] = 1
after Tile[0][0] = 1
The matrix are modified but turn back to before values.
What should I do? (NOTE I'm not familiar with javascript but with language like C++)
I do not understand what is wrong. I added to your code the player object.
class TileMap{
constructor ( w, h ){
this.tiles = [];
//init the matrix
for (var i = 0; i < h; i++)
{
var a = [];
for (var j = 0; j < w; j++)
a.push(0);
this.tiles[i] = a;
}
}
setTile (x, y, tile){
this.tiles[y][x] = tile;
}
doSomething (){
this.setTile(0,0, 1);
this.setTile(0,1, 2);
}
}
//What's happening is when I use like this:
var player = {};
player.map = new TileMap(32,90,90);
player.map.doSomething();
console.log("before Tile[0][0] = "+player.map.tiles[0][0]);
player.map.setTile(0,0, 3);
console.log("after Tile[0][0] = "+player.map.tiles[0][0]);