Javascript error detecting item in array - javascript

I am working on a minesweeper game in javascript. The mechanism that is causing me trouble is the for loop inside the Mine object that sets the isBomb variable to true or false.
var board = [];
var bombs = [];
var mines;
function findNeighbors(x,y) {
return 'work in progress'
}
function setup() {
// create bombs
for (var i = 0; i < 45; i++) {
var position = [floor(random(0,15)),floor(random(0,15))];
if (!bombs.includes(position)) {
bombs[i] = position;
}
}
// create board
for (var y = 0; y < 15; y++) {
board[y] = new Array();
for (var x = 0; x < 15; x++) {
board[y][x] = new Mine(y,x);
}
}
}
console.log(board);
console.log(bombs);
function Mine(x,y) {
this.x = x;
this.y = y;
this.neighbors = findNeighbors(this.x,this.y);
for (var iter = 0; iter < 45; iter++) {
if (bombs[iter] == [this.x,this.y]) {
this.isBomb = true;
}
else {
this.isBomb = false;
}
}
this.show = function() {
return 'show'
}
this.setValue = function(value) {
this.value = value;
return value;
}
}
When I type bombs[44] in the console for example, it returns something like [5,11] yet when I check if bombs[44] = [5,11] it will always return false. Is there a specific way I have to denote the [5,11] array for it to be recognized?

This is because you cannot compare two arrays in javascript. What you can do is using join() and then compare as strings in single step,
bombs[44].join(",") == [5,11].join(",")
Or you can compare the contents of the array individually

Try changing the conditional expression in your for-loop at the top for (var i = 0; i < 45; i++) to for (var i = 0; i < arr.length; i++)
this will make the loop , go over the full array length with less room for error. for loops can be , error prone and tedious.

Related

how to fill in the value in the array

i have code like this in actionscript3,
var map: Array = [
[[0,1,0],[0,1,0]],
[[0,1,0], [0,1,0]]];
var nom1: int = 0;
var nom2: int = 0;
var nom3: int = 1;
var nom4: int = 18;
stage.addEventListener (Event.ENTER_FRAME, beff);
function beff (e: Event): void
{
map[nom1][nom2][nom3] = nom4
}
stage.addEventListener (MouseEvent.CLICK, brut);
function brut(e: MouseEvent):void
{
trace (map)
}
when run, it gets an error in its output
what I want is to fill in each "1" value and not remove the "[" or "]" sign
so when var nom1, var nom2 are changed
Then the output is
[[[0,18,0],[0,18,0]],
[[0,18,0],[0,18,0]]]
please helps for those who can solve this problem
If what you want to achieve is to replace every 1 by 18 in this nested array, you could try :
for (var i = 0; i < map.length; i++) {
var secondLevel = map[i];
for (var j = 0; j < secondLevel.length; j++) {
var thirdLevel = secondLevel[j];
for (var k = 0; k < thirdLevel.length; k++) {
if (thirdLevel[k] === 1) {
thirdLevel[k] = 18;
}
}
}
}
Note that, this would only work for nested arrays with 3 levels of depth

I Failed To Train Neural Network On JS

I am newbie in machine learning, but decided to make own js library for neural networks, everything went perfect until i tryed to train my NN. In My Mini Library i created some functions...
1) A Function That Creates My Neuron-Object:
this.Node = function (conns) {
var output = {};
output.b = hyth.Random({type: "TanH"});
output.w = [];
for (var a = 0; a < conns; a++){
output.w[a] = hyth.Random({type: "TanH"});
}
output.Value = function (i) {
if (i.length == conns) {
var sum = 0;
for (var a = 0; a < conns; a++){
sum += i[a] * output.w[a];
}
sum += output.b;
return myMath.Activate(sum, {type: "Sigmoid"});
}
}
return output;
}
This function has one argument , which is the amount of wanted weights from neuron, and it returns an object with two properties - "b" the float (bias), and "w" the 1D Array which contains floats, and one method - which calculates the activation of neuron-object.
2) A Function That Creates My Neural Net
this.Network = function () {
var p = arguments;
var arr = [];
for (var a = 0; a < p.length-1; a++){
arr[a] = [];
for (var b = 0; b < p[a+1]; b++){
arr[a][b] = this.Node(p[a]);
}
}
return arr;
}
This Function Returns A 2D Array with Neuron-Object as It's final value, using argument array as settings for layer count and node count for each layer.
3) A Function That Feeds Forward The NN
this.Forward = function (network, input) {
if (network[0][0].w.length == input.length) {
var activations = [];
for (var a = 0; a < network.length; a++){
activations[a] = [];
for (var c = 0; c < network[a].length; c++){
if (a == 0){
activations[0][c] = network[0][c].Value(input);
continue;
}
activations[a][c] = network[a][c].Value(activations[a-1]);
}
}
return activations;
}
}
This Function Returns 2D array with an activation float for every neuron as it's final value. It uses 2 agruments - the output of 2nd function, input array.
4) And Final Function That Backpropagates
this.Backward = function (network, input, target) {
if (network[0][0].w.length == input.length && network[network.length-1].length == target.length) {
var activations = this.Forward(network, input, true);
var predictions = activations[activations.length-1];
var errors = [];
for (var v = 0; v < network.length; v++) {
errors[v] = [];
}
for (var a = network.length-1; a > -1; a--){
for (var x = 0; x < network[a].length; x++) {
var deract = hyth.Deractivate(activations[a][x]);
if (a == network.length-1) {
errors[a][x] = (predictions[x] - target[x]) * deract;
} else {
errors[a][x] = 0;
for (var y = 0; y < network[a+1].length; y++) {
errors[a][x] += network[a+1][y].w[x] * errors[a+1][y];
}
errors[a][x] *= deract;
}
}
}
return errors;
}
}
This Function Returns 2D array with the rror float for every neuron as it's final value. Arguments are 3 - the nnet , input and wanted output.
So I can make a neural network, feed forward and and backpropagate, receive activations and errors, but i always fail to train my net with my errors and activations to work perfect , last time it was outputing same result for every type of input. I want to understand training algorithm from zero , so i need someone's help.
P.S. - i dont want someone say that i need to use famous libraries , i want to understand and make it myself.

Trying to search an array against another array, with other array having internal priority

ic is my input array and cbList is my internal array that im checking agaist. I want to check the whole array and return the highest value in based on the cbList. I have some ugly code already tried but i dont want to use it, can someone basically make this better and more efficient. I've been searching and cant find anything in my situation.
So basically just want to check ic and if highest pops up, break out and return that value, if no highest is found, then go on to check high value, and so on...
function hcbin(inv){
var fh;
var ic = ['low','med','low','high'];
var cbList = [ 'low', 'med', 'high','highest'];
for( var i = 0; i < ic.length; i++) {
if (ic[i] === cbList[3]) {
$scope.hdc = ic[i];
fh = true;
}
}
if (!fh){
for( var ii = 0; ii < ic.length; ii++) {
if (ic[ii] === cbList[2]) {
$scope.hdc = ic[ii];
fh = true;
}
}
}
if (!fh){
for( var iii = 0; iii < ic.length; iii++) {
if (ic[iii] === cbList[1]) {
$scope.hdc = ic[iii];
fh = true;
}
}
}
if (!fh){
for( var iiii = 0; iiii < ic.length; iiii++) {
if (ic[iiii] === cbList[0]) {
$scope.hdc = ic[iiii];
fh = true;
}
}
}
};
Try this snippet:
var ic = ['low','med','low', 'high'];
var cbList = [ 'low', 'med', 'high','highest'];
var result = null;
for (var i = (cbList.length - 1); i >=0; i--) {
if (ic.indexOf(cbList[i]) > -1) {
result = cbList[i];
break;
}
}
console.log(result);
Make sure cbList keeps the priority order(from low to highest importance) because the for is based upon that.

Array equals itself plus number = NaN

I must be doing something stupid. The array newArea needs to add up data from all regions, i.e. be global. Regions are represented by variable p. But when I try to get newArea array to add to itself, e.g. newArea[p] += otherArray, it outputs NaNs. Even newArea[p] += 1 outputs NaNs.
Can anyone spot what I'm doing wrong? It's driving me mad and I'm working to a deadline.
mm=0
var maxVolume = 0;
var tempCAGR = 0;
var maxCAGR = 0;
var newArray = [];
var newRegions = [];
var newConsValues = [];
var newArea = [];
for (var p=0; p<arrayRef[mm].length; p++) {//9 regions
newArray[p] = [];
for (var q=0; q<arrayRef[mm][p].length; q++) {//4 scenarios
newArea[q] = [];
if (q==0) {
newRegions.push(arrayRef[mm][p][q][0]);
newConsValues.push(arrayRef[mm][p][q][1]);
}
for (var r=0; r<dates.length; r++) {//time
//console.log('p: '+p+', q: '+q+', r: '+r);
if (p==0) {
newArea[q][r] = 1;
} else {
newArea[q][r] += 1;
}
}
arrayRef[mm][p][q].shift();
tempCAGR = Math.pow(( arrayRef[mm][p][q][len] / arrayRef[mm][p][q][1] ),(1/len))-1;
//console.log(newRegions[p]+', num: '+arrayRef[mm][p][q][len-1]+', denom: '+arrayRef[mm][p][q][0]+', len: '+len+', cagr: '+tempCAGR);
newArray[p][q] = tempCAGR;
maxCAGR = Math.max(maxCAGR,tempCAGR);
}
}
console.log(newArea);
You are cleaning the array in newArea everytime you loop through it:
...loop q ...
newArea[q] = []; // <-- resets the array at q pos
... loop r ...
if (p==0) {
newArea[q][r] = 1;
} else {
newArea[q][r] += 1;
}
So when p === 0 it will fill an array at q pos of your newArea array. However, next iteration of p will clear them out, so there's nothing there to sum.
You probably want to keep the old array or create a new one if there isn't one.
newArea[q] = newArea[q] || [];
It looks like you do not have the variable initialised. With adding something to undefined, you get NaN.
You can change the art of incrementing with a default value:
if (p == 0) {
newArea[q][r] = 1;
} else {
newArea[q][r] = (newArea[q][r] || 0) + 1;
}

Javascript - Object Value not Updating after Moving between Arrays

I am moving one object from one holders array to another:
for (var x = 0; x < array.length; x++) {
var i = holder1.array.length - 1;
while (i >= 0) {
var object = array[holder1.array[i].index];
holder1.array[i].splice(i, 1);
object.owner = i;
object.index = x;
holder2.array.push(object);
i--;
}
}
I then change the data like so:
for (var i = 0; i < holders.length; i++) {
var holderActive = holders[i];
if (holderActive.array.length > 0) {
for (var x = 0; x < holderActive.array.length; x++) {
var object = array[holderActive.array[x].index];
console.log(object.property); << ALWAYS THE SAME!
object.property ++;
}
// ...
}
}
As you can see, I am editing the property of the object, but every time this is run, the property is logged as the same value. What is going on here?

Categories