I am trying to rotate a 2dimensional array in javascript
the code outside the forloop to switch the values works but when i try to do that inside the for loop the variables are not changing
i think it is some sort of reference problem and i searched for that but i can't find a solution to this problem
temp = tempboard[0][1];
console.log("unchanged:"+tempboard[0][1]+""+tempboard[6][1]);
tempboard[0][1] = tempboard[6][1];
tempboard[6][1] = temp;
console.log("changed:"+tempboard[0][1]+""+tempboard[6][1]);
for(i = 0; i < board.length; i++){
for(j = 0; j < board[0].length; j++){
/*a = tempboard[i][j];
b = tempboard[j][i];
temp = a;
a = b;
b = temp;
console.log(a+" "+b);*/
temp = tempboard[i][j];
console.log("unchanged:"+tempboard[i][j]+""+tempboard[j][i]);
tempboard[i][j] = tempboard[j][i];
tempboard[j][i] = temp;
console.log("changed:"+tempboard[j][i]+""+tempboard[i][j]);
}
}
I think it will be easier to build a new array based on the old one.
In the below code a new array is build in reverse based on the original one.
arr = [[11, 12, 13], [21, 22, 23], [31, 32, 33], [41, 42, 43]];
console.log(JSON.stringify(Rotate2D(arr)));
function Rotate2D(array) {
//Create a new empty array with the same size as the original one.
let returnArr = [...Array(array.length)].map(e => Array(array[0].length));
let maxIndexI = array.length - 1;
let maxIndexJ = array[0].length - 1;
//Fill the return array rotated
for (let i = 0; i < array.length; i++) {
for (let j = 0; j < array[0].length; j++) {
returnArr[maxIndexI - i][maxIndexJ - j] = array[i][j]
}
}
return returnArr;
}
Try adding "let" keyword to your for loop, it could be an hoisting issue;
for(let i = 0; i < board.length; i++){
for(let j = 0; j < board[0].length; j++){
/*a = tempboard[i][j];
b = tempboard[j][i];
temp = a;
a = b;
b = temp;
console.log(a+" "+b);*/
temp = tempboard[i][j];
console.log("unchanged:"+tempboard[i][j]+""+tempboard[j][i]);
tempboard[i][j] = tempboard[j][i];
tempboard[j][i] = temp;
console.log("changed:"+tempboard[j][i]+""+tempboard[i][j]);
}
}
Related
I have a function to bubble sort and I want to save the array after each swap into another array. The bubble sort is working properly and I can log the array after each swap to the console. But I cant seem to push to the other array properly.
Here's my code :
var arr = [5, 4, 3, 2, 1];
var steps = [];
function bubbleSort() {
for (let i = 0; i < arr.length - 1; i++) {
for (let j = 0; j < arr.length - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
swap(arr, j, j + 1);
}
var temp = arr;
console.log(temp);
steps.push(temp);
}
}
console.log(steps);
}
const swap = (a, x, y) => {
var temp = a[x];
a[x] = a[y];
a[y] = temp;
};
bubbleSort();
Here's a screenshot of the console :
screenshot of console
It's only when I try to use get a hold of the array at each step that it isn't showing properly? what do I do?
I think clonning the array could work ? var temp = [...arr];
var arr = [5, 4, 3, 2, 1];
var steps = [];
function bubbleSort() {
for (let i = 0; i < arr.length - 1; i++) {
for (let j = 0; j < arr.length - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
swap(arr, j, j + 1);
}
var temp = [...arr];
console.log(temp);
steps.push(temp);
}
}
console.log(steps);
}
const swap = (a, x, y) => {
var temp = a[x];
a[x] = a[y];
a[y] = temp;
};
bubbleSort();
You are inserting the Reference of the Temp-Array and not the actual content. This way, you store multiple times the reference and at the End you are presented with all those reference pointing to the last version of your temp Array.
You can use the destructuring assignment of an array, to create an easy shallow copy to be stored.
var arr = [5, 4, 3, 2, 1];
var steps = [];
function bubbleSort() {
for (let i = 0; i < arr.length - 1; i++) {
for (let j = 0; j < arr.length - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
swap(arr, j, j + 1);
}
var temp = arr;
console.log(temp);
// Changed to destructuring assignment
steps.push([...temp])
}
}
console.log(steps);
}
const swap = (a, x, y) => {
var temp = a[x];
a[x] = a[y];
a[y] = temp;
};
bubbleSort();
I'm trying to return a message if one of the argument is not a number. Otherwise continue with the function.
I'm trying this but it's not working as I'm expecting.. ..Please, any help?
function findingPairs(arr, value){
if(isNaN(arr) || isNaN(value)){
return "Please, introduce just numbers"
}
let sum = 0;
let finalOutput = [];
for(let i = 0; i < arr.length; i++){
let numA = arr[i]
console.log(numA)
} for(let j = 1; j < arr.length; j++){
let numB = arr[j]
console.log(numB)
}
}
findingPairs([1,3,7], 9)
You can use Number.isInteger to check if something is a number.
And Array.every over the array to check all the array.
Also I'm throwing an Error instead of returning a value because that's what is expected usually.
Error Docs
function findingPairs(arr, value) {
if (!arr.every(Number.isInteger) || !Number.isInteger(value)) {
throw new Error("Please, introduce just numbers");
}
let sum = 0;
let finalOutput = [];
for (let i = 0; i < arr.length; i++) {
let numA = arr[i];
console.log(numA);
}
for (let j = 1; j < arr.length; j++) {
let numB = arr[j];
console.log(numB);
}
}
const value = findingPairs([1, 3, 7], 9);
const value2 = findingPairs([1, "a", 7], 9); // Will throw
const value2 = findingPairs([1, 23, 7], "hey"); // Will throw
console.log(value);
You need to check if each element of the array is a number, you can use Array.prototype.some() to test if one element of the array respects a condition
function findingPairs(arr, value){
if(arr.some(isNaN) || isNaN(value)){
return "Please, introduce just numbers"
}
let sum = 0;
let finalOutput = [];
for(let i = 0; i < arr.length; i++){
let numA = arr[i]
console.log(numA)
}
for(let j = 1; j < arr.length; j++){
let numB = arr[j]
console.log(numB)
}
}
findingPairs([1,3,7], 9)
I want to make an array w[i][j] where each w[i][j] is itself an array of numbers.
If I try to do it naively by declaring an empty array w
and assigning variable by looping through it I get the error:
const w : Array<Array<Array<number>>> = [];
for(let i = 0; i < N; i++){
for(let j = 0; j < N; j++){
w[i][j] = [1,2,3];
}
}
TypeError: Cannot set property '0' of undefined.
Instead I am forced to initialze each element of the array to be empty, using the below code. Only after doing this am I able to make the array with no problems. This can't be the best practice. What am I misunderstanding and what should I write instead?
const w : Array<Array<Array<number>>> = [];
for(let i = 0; i < N; i++){
w[i] = [];
for(let j = 0; j < N; j++){
w[i][j] = [];
}
}
You are getting the error because w[i] is not set when you are trying to set w[i][j].
Fix
Do an init or load in the loop e.g.
const N = 5;
const w: Array<Array<Array<number>>> = [];
for (let i = 0; i < N; i++) {
w[i] = w[i] || [];
for (let j = 0; j < N; j++) {
w[i][j] = [1, 2, 3];
}
}
console.log(w); // All good 🌹
When I run the third line alone and log test2darr it returns a 2D array filled with 6's in a 3x3 matrix
But when I run the fourth line and log test2darr again, it returns:
[4, 5, 4]
​
[5, 6, 5]​
[4, 5, 4]
(as well as for secondtest)
Though it should return the same array of 6's for test2darr and on assign the 2d array to secondtest
const n = 3;
const filler = new Array(n * n);
const test2darr = fill2DarrFromArr(filler.fill(6));
const secondtest = pileReduce(test2darr);
Here is my code for fill2DarrFromArr and pileReduce:
function pileReduce(_cells) {
_cells = fillEmpty(_cells);
for (let j = 0; j < _cells.length; j++) { //The Algorithm itself is not important
for (let i = 0; i < _cells.length; i++) { // But there might be some assignment problem that I missed
if (_cells[j][i] >= 4) {
_cells[j][i] = _cells[j][i] - 4;
if (j !== _cells.length - 1) _cells[j + 1][i]++;
if (j !== 0) _cells[j - 1][i]++;
if (i !== _cells.length - 1) _cells[j][i + 1]++;
if (i !== 0) _cells[j][i - 1]++;
}
}
}
return _cells;
}
function fill2DarrFromArr(_arr) {
let sideLength = Math.sqrt(_arr.length);
let out = create2DArr(sideLength, sideLength);
for (let j = 0; j < sideLength; j++) {
for (let i = 0; i < sideLength; i++) {
out[j][i] = _arr[j * sideLength + i];
}
}
return out;
}
function create2DArr(_n, _m) {
let _arr = new Array(_n);
for (let j = 0; j < _m; j++) {
_arr[j] = new Array(_m);
}
return _arr;
}
function fillEmpty(_arr) {
for (let j = 0; j < _arr.length; j++) {
for (let i = 0; i < _arr.length; i++) {
if (!_arr[j][i]) _arr[j][i] = 0;
}
}
return _arr;
}
Passing an array into a function doesn't create a copy of that array. Your functions are modifying the contents of the passed arrays, therefore they have side effects.
I need help merging two arrays without using any of the array built in functions ( no concat, push, pop, shift, replace, sort, splice, etc)
And I've got to this point but I'm stuck.
function addTwoArrays(arr1, arr2){
var merge = [], p;
for(p = 0; p < arr1.length; p++){
merge[arr1[p]] = true;
}
for(p = 0; p < arr2.length; p++){
merge[arr2[p]] = true;
}
return Object.keys(merge);
}
window.alert(addTwoArrays([1,2,3,4],[4,3,2,1]));
return is 1,2,3,4 - instead of 1,2,3,4,4,3,2,1
You only need to loop once - simply take arr1.length as a start index and add to the array:
function addTwoArrays(arr1, arr2) {
let start = arr1.length;
for (let i = 0; i < arr2.length; i++) {
arr1[start++] = arr2[i];
}
return arr1;
}
console.log(addTwoArrays([1, 2, 3, 4], [4, 3, 2, 1]));
Keys are unique in a JSON object. So, Object.keys() will return unique occurrences of each element.
Instead try this:
function addTwoArrays(arr1, arr2){
var merge = [], p, index = 0;
for(p = 0; p < arr1.length; p++){
merge[index++] = arr1[p];
}
for(p = 0; p < arr2.length; p++){
merge[index++] = arr2[p];
}
return merge;
}
window.alert(addTwoArrays([1,2,3,4],[4,3,2,1]));
function mergedArray(arrayOne, arrayTwo) {
let newArr = arrayOne
let x = arrayOne.length
let y = arrayTwo.length
let z = arrayOne.length + arrayTwo.length
let i, j
for (i = x, j = 0; i < z && j < y; i++, j++) {
newArr[i] = arrayTwo[j]
}
return newArr
}