Can't get inside my for loop (Javascript) - javascript

I am trying to iterate over the variable pieces, but somehow it is not triggering. In the function below, pieces.length turns 4, but piecesNew turns [] - moreover console.log(i) is never reached.
What is happening?
self.reworkPieces = function(pieces) {
var piecesNew = [];
console.log(pieces.length)
for (var i; i <= pieces.length; i++) {
console.log(i)
piecesNew[i] = {
c: pieces[i].r,
r: pieces[i].c,
p: i
}
}
console.log(piecesNew)
return piecesNew;
};

undefined is not less than or greater than any number.
var i; // undefined
i < 10; // false
i > 10; // false
You simply need to make sure i is equal to 0.
You also want i to never be equal to pieces.length so use < instead of <= (the last index of an array is always length - 1, e.g. an array of length 3 has indexes 0, 1 and 2 – the first index is always 0, not 1)
So:
for (var i = 0; i < pieces.length; i++) {
...

define value for variable i, var i = 0
self.reworkPieces = function(pieces) {
var piecesNew = [];
console.log(pieces.length)
for (var i = 0; i <= pieces.length; i++) {
console.log(i)
piecesNew[i] = {
c: pieces[i].r,
r: pieces[i].c,
p: i
}
}
console.log(piecesNew)
return piecesNew;
};

self.reworkPieces = function(pieces) {
var piecesNew = [];
console.log(pieces.length)
for (var i = 0; i <= pieces.length; i++) {
console.log(i)
piecesNew[i] = {
c: pieces[i].r,
r: pieces[i].c,
p: i
}
}
console.log(piecesNew)
return piecesNew;
};

Change:
for (var i; i <= pieces.length; i++)
To:
for (var i = 0; i < pieces.length; i++)

Initialize var i = 0 initially then it will work
self.reworkPieces = function(pieces) {
var piecesNew = [];
console.log(pieces.length)
for (var i = 0; i <= pieces.length - 1; i++) {
console.log(i)
piecesNew[i] = {
c: pieces[i].r,
r: pieces[i].c,
p: i
}
}
console.log(piecesNew)
return piecesNew;
};

Related

Correct merge sort

So... If I input:
4 1 5 3
INSTEAD OF 1,3,4,5
I GET [ 4, 1, 5, 3 ]
Following is the code for merge sort but for the last comparison the program doesn't fetch updated (1,4) (3,5) value rather (4,1) (5,3) thus giving the wrong result.
var a = [4, 1, 5, 3];
q(a);
function q(a) {
var start = 0;
var n = a.length;
var length = parseInt(n / 2);
if (n < 2) {
return n;
}
var l = [], r = [];
for (i = 0; i < length; i++) {
l[i] = a[i]; //left array
}
for (i = 0, j = length; j < n; i++ , j++) {
r[i] = a[j]; //right array
}
q(l); //merge sort left array
q(r); //merge sort right array
comp(l, r);
}
function comp(l, r) {
var k = [], m = 0, i = 0, j = 0;
while (i < ((l.length)) && j < ((r.length))) {
if (l[i] < r[j]) {
k[m] = l[i];
i++;
m++
}
else {
k[m] = r[j];
j++;
m++
}
}
while (i != (l.length)) {
k[m] = l[i];
m++;
i++;
}
while (j != (r.length)) {
k[m] = r[j];
m++;
j++;
}
console.log(k); //for final output it is [ 4, 1, 5, 3 ] instead of [1,3,4,5]
}
You have a couple small problems. The main one is that you are returning the wrong thing from your edge condition:
if (n < 2) {
return n; // n is just a length; doesn't make sense to return it.
}
n is the length, you really want to return the small array here:
if (n < 2) {
return a; // return the array instead
}
Also, you need to pass the result of the recursive call to your comp function. Right now you're just returning the original lists with:
comp(l, r)
Something like this would work better:
let l_sort = q(l); //merge sort left array
let r_sort = q(r); //merge sort right array
return comp(l_sort, r_sort); // merge the arrays when recursion unwinds.
And you need to return things for recursion to work.
Put all together:
function q(a) {
var start = 0;
var n = a.length;
var length = parseInt(n / 2);
if (n < 2) {
return a;
}
var l = [],
r = [];
for (i = 0; i < length; i++) {
l[i] = a[i]; //left array
}
for (i = 0, j = length; j < n; i++, j++) {
r[i] = a[j]; //right array
}
let l_sort = q(l); //merge sort left array
let r_sort = q(r); //merge sort right array
return comp(l_sort, r_sort);
}
function comp(l, r) {
var k = [],
m = 0,
i = 0,
j = 0;
while (i < ((l.length)) && j < ((r.length))) {
if (l[i] < r[j]) {
k[m] = l[i];
i++;
m++
} else {
k[m] = r[j];
j++;
m++
}
}
while (i != (l.length)) {
k[m] = l[i];
m++;
i++;
}
while (j != (r.length)) {
k[m] = r[j];
m++;
j++;
}
return k
}
console.log(q([4, 1, 5, 3]).join(','));
console.log(q([5, 4, 3, 2, 1]).join(','));
console.log(q([2, 3]).join(','));
console.log(q([3, 2]).join(','));
console.log(q([1]).join(','));

what is the wrong with this javascript function?

I want to know what is wrong with this function that takes array and summation it's elements
var arr = [1,2,3,4,5,6,7,8,9,10];
var sum = 0;
var arraySum = function () {
for (var i = 0 ; i<= arr.length ; i++) {
sum += arr[i];
}
console.log(sum);
};
arraySum(arr);
You are trying to access an element outside of the array, this returns undefined.
for (var i = 0 ; i<= arr.length ; i++) {
// ^ the equal sign
replace it with
for (var i = 0 ; i< arr.length ; i++) {
var arr = [1,2,3,4,5,6,7,8,9,10];
var sum = 0;
var arraySum = function () {
for (var i = 0; i< arr.length; i++) {
sum += arr[i];
}
};
arraySum(arr);
document.write(sum);
The problem is there with your for loop's condition. Use < when you are checking against the length,
for (var i = 0 ; i < arr.length ; i++) {
//------------------^ replaced the <= with <
Your loop will iterate additionally one time, at that time the value will be undefined.
So sum + undefined = NaN.
If you want to use <= for sure then subtract 1 from the length and use it.
for (var i = 0 ; i <= arr.length-1 ; i++) {
//------------------------------^ decrement the length by 1
Or you can do the entire process with Array.prototype.reduce
var arr = [1,2,3,4,5,6,7,8,9,10];
var sum = arr.reduce((a, b) => { return a + b }, 0);
Also you can use Array.prototype.forEach function
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var sum = 0;
arr.forEach(function(element) {
sum += element;
});
console.log(sum);

Universal function for getting all unique pairs, trebles etc from an array in javascript

I am looking to create a function in javascript, which would allow me to pass a long array, together with one argument.
what I'm looking for is something like this:
var ar = [1,2,3,4];
var pairs = superAwesomeFunction(ar,2) //=> [[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]];
var trebles = superAwesomeFunction(ar,3) //=> [[1,2,3],[1,2,4],[1,3,4],[2,3,4]
ideally, the function would have no limit on the folding argument.
I wrote a piece of code that looks like this, which is working fine, but it's not really useful as it isn't universal, and I would need a lot of such functions, which seems silly.
getAll2Folds: function (ar) {
var combinations = [],
numOdds = ar.length;
for (var i = 0; i < numOdds; i++) {
for (var j = i + 1; j < numOdds; j++) {
combinations.push([ar[i], ar[j]]);
}
}
return combinations;
},
getAll3Folds: function (ar) {
var combinations = [],
numOdds = ar.length;
for (var i = 0; i < numOdds; i++) {
for (var j = i + 1; j < numOdds; j++) {
for (var k = j + 1; k < numOdds; k++) {
combinations.push([ar[i], ar[j], ar[k]]);
}
}
}
return combinations;
};
},
... (not so great :|)
getAll8Folds: function (ar) {
var combinations = [],
numOdds = ar.length;
for (var i = 0; i < numOdds; i++) {
for (var j = i + 1; j < numOdds; j++) {
for (var k = j + 1; k < numOdds; k++) {
for (var l = k + 1; l < numOdds; l++) {
for (var m = l + 1; m < numOdds; m++) {
for (var n = m + 1; n < numOdds; n++) {
for (var o = n + 1; o < numOdds; o++) {
for (var p = o + 1; p < numOdds; p++) {
combinations.push([ar[i], ar[j], ar[k], ar[l], ar[m], ar[n], ar[o], ar[p]]);
}
}
}
}
}
}
}
}
return combinations;
}
I'm free to use underscore, jquery or whatever tool i want, but can't find an elegant solution, which would also be performant. ideas?
Thanks
Basically combine() takes an array with the values to combine and a size of the wanted combination results sets.
The inner function c() takes an array of previously made combinations and a start value as index of the original array for combination. The return is an array with all made combinations.
The first call is allways c([], 0), because of an empty result array and a start index of 0.
var arr = [1, 2, 3, 4, 5, 6, 7];
function combine(a, size) {
function c(part, start) {
var result = [], i, l, p;
for (i = start, l = arr.length; i < l; i++) {
// get a copy of part
p = part.slice(0);
// add the iterated element to p
p.push(a[i]);
// test if recursion can go on
if (p.length < size) {
// true: call c again and concat it to the result
result = result.concat(c(p, i + 1));
} else {
// false: push p to the result, stop recursion
result.push(p);
}
}
return result;
}
return c([], 0);
}
out(JSON.stringify(combine(arr, 2), null, 4), true);
out(JSON.stringify(combine(arr, 3), null, 4), true);
out(JSON.stringify(combine(arr, 4), null, 4), true);
out(JSON.stringify(combine(arr, 5), null, 4), true);
out(JSON.stringify(combine(arr, 6), null, 4), true);
// just for displaying the result
function out(s, pre) {
var descriptionNode = document.createElement('div');
descriptionNode.className = 'description';
if (pre) {
var preNode = document.createElement('pre');
preNode.innerHTML = s + '<br>';
descriptionNode.appendChild(preNode);
} else {
descriptionNode.innerHTML = s + '<br>';
}
document.getElementById('out').appendChild(descriptionNode);
}
<div id="out"></div>

Simple Javascript for loop hangs browser

This Javascript hangs browser when the number of iteration is set to 5. However, if set to 4, it runs normally. What is the problem?
var sample = [
[1,2,3],
[4,5,6],
[7,8,9]];
for(i = 0; i < 5; i++)
swapColumn(sample, 0, 1);
function swapColumn(array, x, y)
{
for(i = 0; i < array.length; i++)
{
temp = array[i][x];
array[i][x] = array[i][y];
array[i][y] = temp;
}
}
Don't forget to use var to declare variables
var sample = [
[1,2,3],
[4,5,6],
[7,8,9]];
for(var i = 0; i < 5; i++)
swapColumn(sample, 0, 1);
function swapColumn(array, x, y)
{
for(var i = 0; i < array.length; i++)
{
var temp = array[i][x];
array[i][x] = array[i][y];
array[i][y] = temp;
}
}
Otherwise they are treated as global variables, and you are actually overwriting i everytime you enter swapColumn

Arrays acting odd

So, I'm working on a javascript application that can solve any size matrix. I'm running into a SUPER weird problem, where my main array only has the value of 0 after a certain point. The input should be a data set, like this
1, 8
2, 10
3, 13
4, 17
5, 22
But I'm having trouble with it. When I run the code, the console.log prints out a pretty derpy array
[[1, 1, 1, 8],
[0, 0, 0, 0],
[0, 0, 0, 0]]
It gets even weirder. If I move the console.log to before I call the rref function, I get the same thing.
Anybody ever seen this before? Anyone know how to fix it? Thanks!
//Matrix object
var matrix = {
startingDataSet: [],
degree: 0,
M: []
}
//splits up user input into a more readable format
function getDataFromString(data) {
var points = data.split("\n");
for (var i=0; i<points.length; i++) {
points[i] = points[i].split(", ");
points[i][0] = parseInt(points[i][0]);
points[i][1] = parseInt(points[i][1]);
}
return points;
}
//finds the degree of the polynomail from the matrix object's data
function setPolynomialDegree(original) {
var data = original;
console.log(original);
//temporary data set to hold numbers in
var tempNumbers = [];
var degree = 1;
//move the original set of Y values into the temporary data set
for (var i = 0; i < data.length; i++) {
tempNumbers.push(data[i][1]);
}
//while the numbers in tempdata are not the same, execute subtraction
while (tempNumbers[0] != tempNumbers[1]) {
var newnums = []
var l = tempNumbers.length;
//find the difference for every set of numbers (0 & 1, 1 & 2, 2 & 3, etc.), and push those into the new data set
for (var i = 0; i < l - 1; i++) {
newnums.push(tempNumbers[i + 1] - tempNumbers[i]);
}
//replace old data set with new one
tempNumbers = newnums;
//increase polynomial degree by one
degree += 1;
}
return degree;
}
//add 2 arrays together
function addrows(r1, r2) {
var temprow = [];
for (var i = 0; i < r1.length; i++) {
temprow.push(r1[i] + r2[i]);
}
return temprow;
}
//multiply array by constant
function multrow(r1, num) {
var temprow = [];
for (var i = 0; i < r1.length; i++) {
temprow.push(r1[i] * num);
}
return temprow;
}
//rref function
function rref(mtrx, deg) {
var temp1 = [];
var temp2 = [];
for (var row = 0; row < mtrx.length; row++) {
for (var j = 0; j < mtrx.length-1; j++) {
temp1 = multrow(mtrx[row], mtrx[j+1][row]);
temp2 = multrow(mtrx[j+1], mtrx[row][row]);
temp1 = multrow(temp1, -1);
mtrx[j+1] = addrows(temp1, temp2);
}
}
return mtrx;
}
//Main function that will solve the matrix
function solveFromDataSet(data) {
data = getDataFromString(data);
for (var i=0; i<data.length; i++) {
matrix['startingDataSet'].push(data[i]);
}
matrix.degree = setPolynomialDegree(matrix.startingDataSet);
matrix.M = [];
for (var i = 0; i < matrix.degree; i++) {
var row = [];
for (var j = matrix.degree; j > 0; j--) {
row.push(Math.pow(data[i][0], j - 1));
}
row.push(data[i][1]);
matrix['M'][i] = row;
}
var var_array = rref(matrix['M']);
console.log(matrix.M);
return matrix.M;
}

Categories

Resources