2-D array changes value with var AND let - javascript

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.

Related

How do I fix this cocktail shaker sort code to work?

I'm trying to write a code that sorts random numbers with different sorting alrorithms. I have 5 algorithms so far, including bubble sort, javascript built in sort, insertion sort, selection sort, and cocktail sort. I am also writing how many swaps and how much time each sort takes. Other sorts are working just fine( I think), but it seems like cocktail sort is not working.
I tried to modify that part of the code, but none of them worked. Here is the code below. I want it to work properly while displays how many swaps and how much time it took at the console. Thank you.
NUM_ELEMENTS = 500;
numbers = [];
function setup() {
createCanvas(400, 300);
for(i=0;i<=NUM_ELEMENTS;i++) {
numbers.push(round(random(1,NUM_ELEMENTS)));
}
para1 = createElement("p","");
tempString = "";
for(i=0;i<=NUM_ELEMENTS;i++) {
console.log(numbers[i]);
tempString = tempString + numbers[i] + ",";
}
para1.html(tempString);
button1 = createButton("Bubble Sort");
button1.mousePressed(bubbleSort);
button2 = createButton("Seclection Sort");
button2.mousePressed(selectionSort);
button3 = createButton("Insertion Sort");
button3.mousePressed(insertionSort);
button4 = createButton("Javascript Bulit-in Sort");
button4.mousePressed(bSort);
}
function bubbleSort() {
total = 0
swaps = 0
t1 = millis();
console.log("sorting")
let n = numbers.length;
for(let i = 0; i < n; i++) {
for(let j = 0; j < n; j++) {
if(numbers[j] > numbers[j+1]){
let t = numbers[j];
numbers[j] = numbers[j+1];
numbers[j+1] = t;
swaps = swaps + 1;
}
}
}
t2 = millis();
console.log(t2-t1);
console.log("swaps :",swaps);
}
function selectionSort() {
let n = numbers.length;
console.log("Sorting...")
total = 0
t1 = millis();
swaps = 0
for(let i = 0; i < n; i++) {
let min = i;
for(let j = i+1; j < n; j++){
if(numbers[j] < numbers[min]) {
min=j;
swaps = swaps + 1;
}
}
if (min != i) {
let tmp = numbers[i];
numbers[i] = numbers[min];
numbers[min] = tmp;
swaps = swaps + 1;
}
}
t2 = millis();
console.log(t2-t1);
console.log("swaps :", swaps);
}
function insertionSort() {
console.log("sorting");
t1 = millis();
swaps = 0;
total = 0
let n = numbers.length;
for (let i = 1; i < n; i++) {
let current = numbers[i];
let j = i-1;
while ((j > -1) && (current < numbers[j])) {
numbers[j+1] = numbers[j];
swaps = swaps + 1;
j--;
}
numbers[j+1] = current;
}
t2 = millis();
console.log(t2-t1);
console.log("swaps : ", swaps);
}
function bSort() {
console.log("Sorting...")
total = 0
t1 = millis();
sort(numbers);
t2 = millis();
console.log(t2-t1);
console.log("swaps : unknown");
}
function cocktailSort() {
console.log("sorting...")
total = 0
swaps = 0
t1 = millis();
let n = numbers.length;
let sorted = false;
while (!sorted) {
sorted = true;
for (let i = 0; i < n - 1; i++) {
if (numbers[i] > numbers[i + 1]){
let tmp = numbers[i];
numbers[i] = numbers[i + 1];
numbers[i+1] = tmp;
sorted = false;
}
}
if (sorted)
break;
sorted = true;
for (let j = n - 1; j > 0; j--) {
if (numbers[j-1] > numbers[j]) {
let tmp = numbers[j];
numbers[j] = numbers[j + 1];
numbers[j+1] = tmp;
sorted = false;
}
}
}
t2 = millis();
console.log(t2-t1);
}
function draw() {
background(220);
textSize(13);
column = 10;
row = 0;
for (i=0;i<NUM_ELEMENTS;i++) {
if (i%18==0) {
column = column + 18;
row = 0;
}
text(numbers[i],column,row*15+15);
row++;
}
}

CodeWars sorting numbers and letters

I am currently doing a codewars problem, and I think I almost got it however, I ran across a problem when sorting index values with the same letter. link to problem is here. https://www.codewars.com/kata/5782dd86202c0e43410001f6
function doMath(s) {
let strSplit = s.split(' ');
let clonedArr = strSplit.slice();
for (let i = 0; i < strSplit.length; i++) {
for (let j = 0; j < strSplit[i].length; j++) {
let current = strSplit[i][j];
if (isNaN(current)) {
let letter = current;
strSplit[i] = strSplit[i].replace(letter, '');
strSplit[i] = letter + strSplit[i];
}
}
}
let sortedArr = strSplit.sort();
console.log(sortedArr);
// ["b900", "y369", "z123", "z246", "z89"]
let noLetterArr = sortedArr.map(x => {
return x.slice(1);
});
let numberArr = noLetterArr.map(y => {
return +y;
})
let firstEl = numberArr[0];
for (let i = 1; i < numberArr.length; i++) {
if (numberArr.indexOf(numberArr[i]) % 4 == 1) {
firstEl += numberArr[i];
}
if (numberArr.indexOf(numberArr[i]) % 4 == 2) {
firstEl -= numberArr[i];
}
if (numberArr.indexOf(numberArr[i]) % 4 == 3) {
firstEl *= numberArr[i];
}
}
return firstEl;
}
console.log(doMath('24z6 1z23 y369 89z 900b'));
I would like to sort the sortedArr the ones with the same letter by how they first appeared in string. So since "z246" appeared first in the original string. I would like to have that before "1z23". I had a hard time creating a function for that.
var al = [];
function doMath(s) {
var ar = s.split(" ");
for (let i = 0; i < ar.length; i++) {
for (let char of ar[i]) {
let temp = char.match(/[a-z]/i);
if (temp) {
al[i] = char;
ar[i] = ar[i].replace(char, '');
ar[i] = char + ar[i];
}
}
}
al = al.sort();
//New Sort Logic to pass above test case and others too
var n = [];
for (let i = 0; i < al.length; i++) {
for (let j = 0; j < ar.length; j++) {
if (ar[j].startsWith(al[i]) && !n.includes(ar[j])) {
n.push(ar[j]);
}
}
}
var result = parseInt(n[0].substr(1)),
count = 1;
for (let i = 1; i < n.length; i++) {
if (count == 1) {
result = result + parseInt(n[i].substr(1));
count++;
} else if (count == 2) {
result = result - parseInt(n[i].substr(1));
count++;
} else if (count == 3) {
result = result * parseInt(n[i].substr(1));
count++;
} else if (count == 4) {
result = result / parseInt(n[i].substr(1));
count = 1;
}
}
return Math.round(result);
}

Why do I get an Uncaught TypeError: property 4 is undefined when looping through a 2d array?

So I am building Tetris. After creating an array, data, I am trying to implement gravity by checking
every string in an array if it's is "full" as well as being able the space below it being empty. However, it is giving me an error that suggests that something is undefined. The I tried a for loop and a for...of loop, as well as Googling it.Why do I get this error, and how can I fix it?
const editor = document.getElementById("edit");
var data = [];
function array(x, text) {
var y = [];
for (var i = 0; i < x - 1; i++) {
y.push(text);
}
return y;
}
for (var i = 0; i < 20; i++) {
data.push(array(10, "b"));
}
function draw() {
var j;
var i;
var dataOut = data;
for (i = 0; i < data.length; i++) {
for (j = 0; j < data[i].length; j++) {
if (data[i][j] == "a" && data[i + 1][j] == "b") {
if (i < data.length - 1) {
dataOut[i][j] = "b";
dataOut[i + 1][j] = "a";
}
}
}
}
data = dataOut;
console.log(data);
requestAnimationFrame(draw);
}
data[0][4] = "a";
requestAnimationFrame(draw);
with for-of-loop you iterate only objects/values of array and not indexes.
use only for-loop in order to use indexes
const editor = document.getElementById("edit");
var data = [];
function array(x, text) {
var y = [];
for (var i = 0; i < x - 1; i++) {
y.push(text);
}
return y;
}
for (var i = 0; i < 20; i++) {
data.push(array(10, "b"));
}
function draw() {
var dataOut = data;
for (let i = 0; i < data.length - 1; i++) { // logical error here
for (let j = 0; j < data.length; j++) {
if (data[i][j] == "a" && data[i + 1][j] == "b") {
if (i < data.length - 1) {
dataOut[i][j] = "b";
dataOut[i + 1][j] = "a";
}
}
}
}
data = dataOut;
console.log(data);
requestAnimationFrame(draw);
}
data[0][4] = "a";
requestAnimationFrame(draw);
A simple example of for-of-loop
const arr = ["aa","bb"]
for(let a of arr) console.log(a);
// will print
/*
aa
bb
*/
for(let a = 0; a < arr.length; a++) console.log(a);
// will print
/*
0
1
*/

Merge and quick sort time result anomaly

I am currently working on my investigation for my Extended Essay. I am testing the comparison between the merge and quick sorting algorithms. I am having this weird anomaly with my results. Every first sort in my second for loop return a much higher time taken than the rest. I have no clue why, could someone maybe explain?
For some reason, JSFiddle will not output anything, though when I run it locally it works fine. So, I'll just post the code here:
function generateRandomArray(l, min, max) {
var a = [];
for (var i = 0; i < l; i++) {
a.push(Math.ceil(Math.random() * max + min - 1));
}
return a;
}
function quickSort(a) {
var less = [],
pivotList = [],
greater = [];
if (a.length <= 1) return a;
var pivot = a[0];
for (var i = 0; i < a.length; i++) {
if (a[i] < pivot) less.push(a[i]);
else if (a[i] > pivot) greater.push(a[i]);
else pivotList.push(a[i]);
}
less = quickSort(less);
greater = quickSort(greater);
return less.concat(pivotList, greater);
}
function mergeSort(left, right) {
if (!left) return right;
if (!right) return left;
var result = [],
leftIndex = 0,
rightIndex = 0;
while (leftIndex < left.length & rightIndex < right.length) {
if (left[leftIndex] <= right[rightIndex]) {
result.push(left[leftIndex]);
leftIndex++;
} else {
result.push(right[rightIndex]);
rightIndex++;
}
}
if (leftIndex != left.length) {
var temp = left.slice(leftIndex, left.length);
result = result.concat(temp);
} else if (rightIndex != right.length) {
var temp = right.slice(rightIndex, right.length);
result = result.concat(temp);
}
return result;
}
function mergeSortSplit(a) {
if (a.length <= 1) return a;
var middle = Math.floor(a.length / 2);
var left = a.slice(0, middle),
right = a.slice(middle, a.length);
left = mergeSortSplit(left);
right = mergeSortSplit(right);
return mergeSort(left, right);
}
window.onload = function() {
var timeResults = [
[[], [], [], [], []],
[[], [], [], [], []]
];
for (var i = 0; i < 10; i++) {
for (var j = 3; j < 6; j++) {
var array = generateRandomArray(Math.pow(10, j), 1, 100);
var mergeSortTime = window.performance.now();
mergeSortSplit(array);
timeResults[0][j - 3].push(window.performance.now() - mergeSortTime);
var quickSortTime = window.performance.now();
quickSort(array);
timeResults[1][j - 3].push(window.performance.now() - quickSortTime);
}
}
for (var i = 0; i < timeResults.length; i++) {
document.getElementById("demo").innerHTML += "<b>" + (i + 1) + ". </b><br>";
for (var j = 0; j < timeResults[i].length; j++) {
document.getElementById("demo").innerHTML += "<b>" + Math.pow(10, j + 3) + ": </b>";
for (k = 0; k < timeResults[i][j].length; k++) {
document.getElementById("demo").innerHTML += timeResults[i][j][k] + "<b> | </b>";
}
document.getElementById("demo").innerHTML += "<br><br>";
}
document.getElementById("demo").innerHTML += "<br><br><br>";
}
console.log(timeResults);
}
<html>
<head>
<meta charset="utf-8">
<title>EE Investigation</title>
<script type="text/javascript" src="index.js"></script>
</head>
<body>
<p id="demo"></p>
</body>
</html>

JavaScript function multiple calling

Source code:
function CreateArray(length) {
var array1 = [];
for (var k = 0, t = length; k < t; k++) {
array1.push(Math.round(Math.random() * 3000000))
};
return array1;
var array = CreateArray(100,500,1000) // works only for 100
console.time("insertionSort")
function insertionSort(array) {
var countOuter = 0;
var countInner = 0;
var countSwap = 0;
for(var i = 0; i < array.length; i++) {
countOuter++;
var temp = array[i];
var j = i - 1;
while (j >= 0 && array[j] > temp) {
countInner++;
countSwap++;
array[j + 1] = array[j];
j--;
}
array[j + 1] = temp;
}
console.log('outer:', countOuter, 'inner:', countInner, 'swap:', countSwap);
return array;
}
console.timeEnd("insertionSort")
insertionSort(array.slice());
with this last calling I want to check 100,500,1000,5000 and other different lengths. Any ideas?
I want that the last calling will work for any lengths of arrays.
You need CreateArray to create multiple arrays at once, and then you need insertionSort to be able to process multiple arrays at once - or, even better, call another function (once) that calls insertionSort for each array:
const CreateArray = (...lengths) => lengths.map(length => (
Array.from({ length }, () => Math.floor(Math.random() * 3000000))
));
function insertionSort(array) {
var countOuter = 0;
var countInner = 0;
var countSwap = 0;
for (var i = 0; i < array.length; i++) {
countOuter++;
var temp = array[i];
var j = i - 1;
while (j >= 0 && array[j] > temp) {
countInner++;
countSwap++;
array[j + 1] = array[j];
j--;
}
array[j + 1] = temp;
}
console.log('outer:', countOuter, 'inner:', countInner, 'swap:', countSwap);
}
const insertionSortMultipleArrays = (arrs) => {
arrs.forEach(arr => {
console.time("insertionSort");
insertionSort(arr);
console.timeEnd("insertionSort");
});
};
const arrays = CreateArray(100,500,1000,5000);
insertionSortMultipleArrays(arrays);

Categories

Resources