How to dynamically update 3 dimensional Array values in Javascript - javascript

I have a 3d array-DataSeriesToPlot in Javascript, what I want to do is all first half rows' elements value plus a value- scale, all remaining half rows'elements value minus the value-scale. The code is like the below showed,
for ( var i = 0; i < DataSeriesToPlot.length; i++) {
for ( var j = 0; j < DataSeriesToPlot[i].length; j++) {
if ((i >= 0) && (i < (DataSeriesToPlot.length / 2))) {
DataSeriesToPlot[i][j][1] = (parseFloat(DataSeriesToPlot[i][j][1]) + parseFloat(scale))
.toFixed(2);
} else {
DataSeriesToPlot[i][j][1] = (parseFloat(DataSeriesToPlot[i][j][1]) - parseFloat(scale))
.toFixed(2);
}
for ( var j = 0; j < DataSeriesToPlot.length; j++) {
console.log("aaaaa"+DataSeriesToPlot[j]);
}
But this ways seems incorrect, because the console output the original value of this 3d array, all values haven't been changed. Could you please help me figure out where the error is? Thanks!

Related

Having issues trying to solve N Rook problem . Always get n*n solution and not N factorial

I'm trying to get N ways of solves a N rook problem. The issue I am having is currently, I seem to get n*n solutions while it needs to be N! . Below is my code, I have written it in simple loops and functions, so it's quite long. Any help would be greatly appreciated
Note: Please ignore case for n = 2. I get some duplicates which I thought I would handle via JSON.stringify
var createMatrix = function (n) {
var newMatrix = new Array(n);
// build matrix
for (var i = 0; i < n; i++) {
newMatrix[i] = new Array(n);
}
for (var i = 0; i < n; i++) {
for (var j = 0; j < n; j++) {
newMatrix[i][j] = 0;
}
}
return newMatrix;
};
var newMatrix = createMatrix(n);
// based on rook position, greying out function
var collision = function (i, j) {
var col = i;
var row = j;
while (col < n) {
// set the row (i) to all 'a'
col++;
if (col < n) {
if (newMatrix[col][j] !== 1) {
newMatrix[col][j] = 'x';
}
}
}
while (row < n) {
// set columns (j) to all 'a'
row++;
if (row < n) {
if (newMatrix[i][row] !== 1) {
newMatrix[i][row] = 'x';
}
}
}
if (i > 0) {
col = i;
while (col !== 0) {
col--;
if (newMatrix[col][j] !== 1) {
newMatrix[col][j] = 'x';
}
}
}
if (j > 0) {
row = j;
while (row !== 0) {
row--;
if (newMatrix[i][row] !== 1) {
newMatrix[i][row] = 'x';
}
}
}
};
// checks position with 0 and sets it with Rook
var emptyPositionChecker = function (matrix) {
for (var i = 0; i < matrix.length; i++) {
for (var j = 0; j < matrix.length; j++) {
if (matrix[i][j] === 0) {
matrix[i][j] = 1;
collision(i, j);
return true;
}
}
}
return false;
};
// loop for every position on the board
loop1:
for (var i = 0; i < newMatrix.length; i++) {
var row = newMatrix[i];
for (var j = 0; j < newMatrix.length; j++) {
// pick a position for rook
newMatrix[i][j] = 1;
// grey out collison zones due to the above position
collision(i, j);
var hasEmpty = true;
while (hasEmpty) {
//call empty position checker
if (emptyPositionChecker(newMatrix)) {
continue;
} else {
//else we found a complete matrix, break
hasEmpty = false;
solutionCount++;
// reinitiaze new array to start all over
newMatrix = createMatrix(n);
break;
}
}
}
}
There seem to be two underlying problems.
The first is that several copies of the same position are being found.
If we consider the case of N=3 and we visualise the positions by making the first rook placed red, the second placed green and the third to be placed blue, we get these three boards:
They are identical positions but will count as 3 separate ones in the given Javascript.
For a 3x3 board there are also 2 other positions which have duplicates. The gets the count of unique positions to 9 - 2 - 1 -1 = 5. But we are expecting N! = 6 positions.
This brings us to the second problem which is that some positions are missed. In the case of N=3 this occurs once when i===j==1 - ie the mid point of the board.
This position is reached:
This position is not reached:
So now we have the number of positions that should be found as 9 - 2 - 1 - 1 +1;
There appears to be nothing wrong with the actual Javascript in as much as it is implementing the given algorithm. What is wrong is the algorithm which is both finding and counting duplicates and is missing some positions.
A common way of solving the N Rooks problem is to use a recursive method rather than an iterative one, and indeed iteration might very soon get totally out of hand if it's trying to evaluate every single position on a board of any size.
This question is probably best taken up on one of the other stackexchange sites where algorithms are discussed.

Merge two arrays by value

I have a specific cuestion about merge arrays:
I'm using google charts and I need to do something like this
Combo Chart
To do something like that I need to fill this matrix
I did fine with axis x and axis y:
$scope.data= [];
$scope.data[0]= ['Months'];
angular.forEach($scope.consultors, function(consultor) {
$scope.data[0].push(consultor.no_user);
})
angular.forEach(months, function(month) {
$scope.data.push([month])
})
but, my problem is when i try to put $scope.relatorias, inside of $scope.data.
This is $scope.relatorias, this variable has the data of every consultor group by month, like this:
If you open each array look like this
I just need push ganancias_netas, but my problem is when there is an empty month, for example anapaula has data in every month but renato hasn't.
I have try to user for or for each but is doesn't work, I'm not an expert in matrix and this is my first time working on it.
fiddle: http://fiddle.jshell.net/rfcabal/5ftw7c8d/
/// UPDATE ///
I added this code that first fill with 0 $scope.data and then search for the values in relatorios and shoudl fill $scope.data, but for some reason jus fill with the last found value.
for (var i = 1; i < $scope.data.length; i++) {
for (var a = 1; a < $scope.data[0].length; a++) {
$scope.data[i][a] = 0;
for (var b = 0; b < $scope.relatorios[a-1].length; b++) {
console.log(a-1+' '+b+' '+3);
console.log($scope.relatorios[a-1][b]['ganancias_netas'])
$scope.data[i][a] = $scope.relatorios[a-1][b]['ganancias_netas'];
}
}
}
Thanks for your help
I just solved with 2 for
First i fill every data space with 0
for (var i = 1; i < $scope.data.length; i++) {
for (var a = 1; a < $scope.data[0].length; a++) {
$scope.data[i][a] = 0;
}
}
The i jus remplace where fecha_emision equal to position 1 of every array.
for (var a = 0; a < $scope.relatorios.length; a++) {
for (var b = 0; b < $scope.relatorios[a].length; b++) {
for (var i = 1; i < $scope.data.length; i++) {
var index = $scope.data[i].indexOf($scope.relatorios[a][b]['fecha_emision']);
if(index >= 0) {
$scope.data[i][a+1] = parseFloat($scope.relatorios[a][b]['ganancias_netas']);
}
}
}
}

Why is this incrementer returning NAN when if I hard code the index it works as expected?

I am trying to do a simple factorial code challenge, but with Javascript, when I try to get the index position by looping of the indexes, I get NAN. I understand that NAN is of the typeOf number, just that Javascript doesn't know which number. I don't see why that is happening in this case. Also how can I use get the index of an array by looping over them in Javascript? Thanks!
// Input = 4 Output = 24
// Input = 8 Output = 40320
var total = 0;
var factor_Array = [];
function FirstFactorial(num) {
for (var i = 1; i <= num; i++){
factor_Array.unshift(i);
// console.log(factor_Array);
}
for (var j = 0; j < factor_Array.length; j++){
// Why does this work??? But not when I use 'j' to grab the index position? Seems like BOTH ways should work
total = factor_Array[0] * factor_Array[0+1];
total = factor_Array[j] * factor_Array[j+1];
}
console.log(total);
//return num;
}
FirstFactorial(4);
Because when j = (factor_Array.length-1) it tries to access the j+1 element, which doesn't exist.
The following would work as you expect
for (var j = 0; j < (factor_Array.length-1); j++){
total = factor_Array[j] * factor_Array[j+1];
}
When you loop
for (var j = 0; j < factor_Array.length; j++){
total = factor_Array[j] * factor_Array[j+1];
}
Then then on the last iteration you will be out of the array bounds since
j = factor_Array.length - 1
and you're accessing j + 1.

Searching a 2D Javascript Array For Value Index

I am trying to write a jQuery that will find the index of a specific value within a 7x7 2D array.
So if the value I am looking for is 0 then I need the function to search the 2D array and once it finds 0 it stores the index of the two indexes.
This is what I have so far, but it returns "0 0" (the initial values set to the variable.
Here is a jsFiddle and the function I have so far:
http://jsfiddle.net/31pj8ydz/1/
$(document).ready( function() {
var items = [[1,2,3,4,5,6,7],
[1,2,3,4,5,6,7],
[1,2,3,0,5,6,7],
[1,2,3,4,5,6,7],
[1,2,3,4,5,6,7],
[1,2,3,4,5,6,7],
[1,2,3,4,5,6,7]];
var row = 0;
var line = 0;
for (i = 0; i < 7; ++i) {
for (j = 0; i < 7; ++i) {
if (items[i, j] == '0,') {
row = i;
line = j;
}
}
}
$('.text').text(row + ' ' + line);
});
HTML:
<p class="text"></p>
Your if statement is comparing
if (items[i, j] == '0,')
Accessing is wrong, you should use [i][j].
And your array has values:
[1,2,3,4,5,6,7]
....
Your value '0,' is a string, which will not match numeric values inside the array, meaning that your row and line won't change.
First, you are accessing your array wrong. To access a 2D array, you use the format items[i][j].
Second, your array doesn't contain the value '0'. It doesn't contain any strings. So the row and line variables are never changed.
You should change your if statement to look like this:
if(items[i][j] == 0) {
Notice it is searching for the number 0, not the string '0'.
You access your array with the wrong way. Please just try this one:
items[i][j]
When we have a multidimensional array we access the an element of the array, using array[firstDimensionIndex][secondDimensionIndex]...[nthDimensionIndex].
That being said, you should change the condition in your if statement:
if( items[i][j] === 0 )
Please notice that I have removed the , you had after 0. It isn't needed. Also I have removed the ''. We don't need them also.
There are following problems in the code
1) items[i,j] should be items[i][j].
2) You are comparing it with '0,' it should be 0 or '0', if you are not concerned about type.
3) In your inner for loop you should be incrementing j and testing j as exit condition.
Change your for loop like bellow and it will work
for (i = 0; i < 7; i++) {
for (j = 0; j < 7; j++) {
if (items[i][j] == '0') {
row = i;
line = j;
}
}
}
DEMO
Note:-
1) Better to use === at the place of ==, it checks for type also. As you see with 0=='0' gives true.
2) Better to say i < items.length and j<items[i].length instead of hard-coding it as 7.
var foo;
items.forEach(function(arr, i) {
arr.forEach(function(val, j) {
if (!val) { //0 coerces to false
foo = [i, j];
}
}
}
Here foo will be the last instance of 0 in the 2D array.
You are doing loop wrong
On place of
for (i = 0; i < 7; ++i) {
for (j = 0; i < 7; ++i) {
if (items[i, j] == '0,') {
row = i;
line = j;
}
}
}
use this
for (i = 0; i < 7; i++) {
for (j = 0; j < 7; j++) {
if (items[i][j] == 0) {
row = i;
line = j;
}
}
}
Here is the demo
looks like you are still learning how to program. But here is an algorithm I've made. Analyze it and compare to your code ;)
var itens = [[1,2,3,4,5,6,7],
[1,2,3,4,5,6,7],
[1,2,3,0,5,6,7],
[1,2,3,4,5,6,7],
[1,2,3,4,5,6,7],
[1,2,3,4,5,6,7],
[1,2,3,4,5,6,7]];
var row = null;
var collumn = null;
for (var i = 0; i < itens.length; i++) {
for (var j = 0; j < itens[i].length; j++) {
if (itens[i][j] == 0) {
row = i;
collumn = j;
}
}
}
console.log(row, collumn);

Remove element in nested loop

I am writting a simple metaballs implementation in JS. I have an array of the metaballs and i iterate through all of them every frame, and for each one I check the distance to every other metaball and if they are close enough I need to merge them.
This is how I guess it could look, but I don't know how to properly remove the element from array and not break the loops.
for(var i = 0; i < points.length; i++) {
for(var j = 0; j < points.length ; j++) {
if(i != j) {
if(distance < 10) {
//remove one of the points using splice
}
}
}
}
Thanks for help.
First, start your inner loop at i + 1. You've already compared elements up to i, so there's no need to repeat, right? That let's you get rid of your if statement as well.
Then, when you splice, decrement j so as to not skip the next element.
for(var i = 0; i < points.length; i++) {
for(var j = i + 1; j < points.length ; j++) {
if (distance(i, j) < 10) {
points.splice(j--, 1);
}
}
}

Categories