Else statement won't work in for loop - javascript

I have a function here that is not working as I hoped it would. After a bit of testing, I discovered that it is not running the "else if" statement.
Here is the code:
getWeights : function() {
weights = [];
for (var i = 0; i < hiddenLayer.length; i++) {
weights[i] = {};
for (var j = 0; j < Object.keys(hiddenLayer[i]).length * 3; j++) {
if (i == 0) {
for (var t = 0; t < input.length; t++) {
weights[i]["weightsSet" + j] = 1;
}
}
else {
weightCalc = Object.keys(hiddenLayer[i - 1]).length;
for (var u = 0; u < Object.keys(hiddenLayer[i]).length * weightCalc; u++) {
weights[i]["weightsSet" + j] = 1;
}
}
}
}
},
Please help me find out why it won't work.
Any help is greatly appreciated.
EDIT
Removed comment
EDIT 2
I figured out the problem. Thanks for all the help :)

Try simplifying the function as follows and then debug to see what is happening:
getWeights : function() {
weights = [];
for (var i = 0; i < hiddenLayer.length; i++) {
weights[i] = {};
var limit = input.length;
if (i > 0) {
var weightCalc = Object.keys(hiddenLayer[i - 1]).length;
limit = Object.keys(hiddenLayer[i]).length * weightCalc;
}
for (var j = 0; j < Object.keys(hiddenLayer[i]).length * 3; j++) {
for (var t = 0; t < limit; t++) {
weights[i]["weightsSet" + j] = 1;
}
}
}
}
For any further help you would need to add data related to this code, and expected output in your question.

Check 2nd or 3rd for loop may be its running for infinitive number of times

Related

Combine 10 cycles into one in Javascript

Here's my code with cycles and I want to make it shorter (in one cycle if possible).
function plan(piece) {
for (i = 0; i < 10; i++) {
piece.addStep('right');
}
for (i = 0; i < 9; i++) {
piece.addStep('down');
}
for (i = 0; i < 8; i++) {
piece.addStep('left');
}
for (i = 0; i < 7; i++) {
piece.addStep('up');
}
}
etc... to i < 1
I thought about it that case,
function plan(piece) {
for (i=10; i>1; i--){
piece.addStep('right');
piece.addStep('down');
piece.addStep('left');
piece.addStep('up');
}
but it's was wrong. Help pls!
here's look of task(maze)
You can add function for the repeating logic :
function addSteps(piece, n) {
while (n--) {
piece.addStep(piece);
}
}
addSteps('right', 10);
addSteps('down', 9);
addSteps('left', 8);
addSteps('up', 7);
Simply combine all of them by introducing some if Checks.
For Example :
function plan(piece) {
for (i = 0; i < 10; i++) {
piece.addStep('right');
if(i < 9)
piece.addStep('down');
if(i < 8)
piece.addStep('left');
if(i < 7)
piece.addStep('up');
}
}
One option is:
function plan(piece) {
['right', 'down', 'left', 'up'].forEach((dir, ind) => {
for (let i = 0; i < 10 - ind; i++) {
piece.addStep(dir);
}
});
}
Doubt it is efficient, but you can be Array fill, concat, and forEach
var steps = [].concat(Array(10).fill("right"), Array(9).fill("down"), Array(8).fill("left"), Array(7).fill("up"))
steps.forEach(dir => piece.addStep(dir));
You could take nested loops and increment the index for getting the right direction.
var sequence = ['right', 'down', 'left', 'up'],
i, j,
k = 0,
l = sequence.length;
for (i = 0; i < 10; i++) {
for (j = i; j < 10; j++) {
document.getElementById('out').innerHTML += sequence[k] + '\n';
// or piece.addStep(sequence[k]);
}
++k;
k %= l;
}
<pre id="out"></pre>

My code code infinitely and crashes the page

This is my code:
// Population
var Gene = function(text){
if(text){
this.text = text;
}
};
Gene.fitness = 0;
Gene.generation = 0;
var word = new Gene('Hello');
// This is where it crashes!!
// Make elements
var genArr = [];
var population = 20;
var mutation = 0;
for(var i = 0; i < population; i++){
var gene = "";
var abc = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for (var j = 0; i < word.text.length; j++) {
var element = abc.charAt(Math.floor(Math.random() * abc.length));
gene += element;
}
genArr.push(gene);
}
// Divide them - fitness
// 1/20 - 0.05% each
var fitElements = [];
for (var i = 0; i < genArr.length; i++) {
var score = 0;
var curWord = Array.from(genArr[i]);
for (var j = 0; j < word.text.length; j++) {
if(genArr[j].substr(j, 1) == word.text.substr(j, 1)){
score += 1;
}
}
if(score > 0){
fitElements.push([genArr[i], (score * (1 / population)) ** 2]);
}
}
for (var i = 0; i < fitElements.length; i++) {
console.log('Element: ' + fitElements[i][0] + ', Score: ' + fitElements[i][1]);
}
My problem is that it crashes the page but doesn't gives errors. The idea is to create a simple word register in fitElements Array but I can't see what am I missing?
Thanks in advance.
In your code the nested for loop with variable j's end condition relies on i.
Take a the line:
// VVVV it relies on i instead of j
for (var j = 0; i < word.text.length; j++) {
var element = abc.charAt(Math.floor(Math.random() * abc.length));
gene += element;
}
The new code would look something like
for (var j = 0; j < word.text.length; j++)
var element = abc.charAt(Math.floor(Math.random() * abc.length));
gene += element;
}
The only difference in the entire sample is the i is changed to a j. Cheers!

Aligning contents of range to other range

I would like align row in function of the Name (column B & D), for exemple on the picture (1) the 2 red rectangles should be on the same line like for the 2 green rectangles but I don't know why, it doesn't work, here the code :
function onOpen(event){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("test1");
var data = sheet.getDataRange().getValues();
for(var j = 1; j < data.length; j++) {
if(data[j][1].trim() != '') {
for (var i = 1; i < data.length; i++) {
if(data[i][3].trim() != '') {
if(data[j][1] == data[i][3]) {
if(j != i) {
var j1 = j + 1;
var i1 = i + 1;
sheet.getRange('D'+j1+':E'+j1).moveTo(sheet.getRange('F1:G1'));
sheet.getRange('D'+i1+':E'+i1).moveTo(sheet.getRange('D'+j1+':E'+j1));
sheet.getRange('F1:G1').moveTo(sheet.getRange('D'+i1+':E'+i1));
}
break;
}
}
}
}
}
}
I'm pretty sure this code should work
Oddly it works if I'm running the code step by step like this, firstly :
for(var j = 1; j < 2; j++)
after
for(var j = 2; j < 3; j++)
after
...
until
for(var j = 6; j < 7; j++)
Well I found a workaround :)
function onOpen(event){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("test1");
var data = sheet.getDataRange().getValues();
var blank = 0;
// I count the blank case so I don't run the code effortlessly on blank case
for(var j = 1; j < data.length; j++) {
if(data[j][1].trim() == '')
blank++;
}
var length = data.length - blank;
// I don't make a real switch in fact, I'm using a tempory space where I order the data
for(var j = 1; j < length; j++) {
for (var i = 1; i < length; i++) {
if(data[j][1] === data[i][3]) {
var j1 = j + 1;
var i1 = i + 1;
sheet.getRange('D'+i1+':E'+i1).moveTo(sheet.getRange('F'+j1+':G'+j1)); // column F & G is the tempory space where I put the ordered data
break;
}
}
}
// I move back the tempory space ordered now to his initial place
sheet.getRange('F2:G'+length).moveTo(sheet.getRange('D2:E'+length));
}

Print prime numbers between 0 and 100

I'm trying to print all prime number between 0 and 100, but when executing this code the browser's tab just outputs nothing!!
for(var i = 2; i < 100; i++)
{
var prime = [];
for(var j = 0; j <= i; j++)
{
var p = i % j;
}
if(p != 0) prime.push(i);
else continue;
}
for(var k = 0; k < prime.length; k++)
{
document.writeln(prime[k], "<br>");
}
Try this one. I have also optimise the code (you only need to check upto sqrt(i) ).
var prime = [];
prime.push(2); //smallest prime
var flag = 0;
for(var i = 3; i < 100; i=i+2) //skip all even no
{
for(var j = 3; j*j <= i; j=j+2) //check by upto sqrt(i), skip all even no
{
if(i % j == 0) {
flag = 0;break; //not a prime, break
}
flag = 1;
}
if (flag == 1) prime.push(i); //prime, add to answer
}
for(var k = 0; k < prime.length; k++)
{
document.writeln(prime[k], "<br>");
}
Because you blank your list of primes EVERY loop cycle, move it outside the for loop
You need to make your variable prime outside of your loop
This is the code you have re-written
var prime = [];
for(var i = 2; i < 100; i++)
{
for(var j = 0; j <= i; j++)
{
var p = i % j;
}
if(p != 0) prime.push(i);
else continue;
}
for(var k = 0; k < prime.length; k++)
{
document.writeln(prime[k], "<br>");
}
I'm a fan of the sieve of Eratosthenes.
The following code should do what you wanted.
var prime = Array(101).fill(true);
for (var i = 2; i < 100; ++i){
if (prime[i]){
document.writeln(i, "<br>");
for (var j = i*i; j < 100; j += i){
prime[j] = false;
}
}
}
Or since it's only up to 100 you could just manually type the list (but, hey where's the learning if you do it that way?).
(1) Move prime outside the for loop, (2) start j at 2 and end when j < i, (3) check when p == 0 with a boolean flag and break inner loop.
var prime = []; //put prime out here so it does not reassign
for(var i = 2; i < 100; i++)
{
var isPrime = true;
for(var j = 2; j < i; j++) //start j at 2
{
var p = i % j;
if(p == 0)
{
isPrime = false;
break;
}
}
if(isPrime) prime.push(i);
}
for(var k = 0; k < prime.length; k++)
{
document.writeln(prime[k], "<br>");
}

remove value from two tables

I have two table is I remove the value in both tables if in a table of the value is marked by a flag to false
this.notInModel = function (tab1, tab2) {
for (var i = 0; i <= tab1.length - 1; i++) {
if (!tab1[i].inModel) {
for (var j = 0; j <= tab2.length - 1; j++) {
if(tab1[i].name === tab2[j].name)
tab2.splice(j, 1);
}
}
}
for (var i = 0; i <= tab2.length - 1; i++) {
if (!tab2[i].inModel) {
for (var j = 0; j <= tab1.length - 1; j++) {
if(tab2[i].name === tab1[j].name)
tab1.splice(j, 1);
}
}
}
}
I think my curls are a bit repetitive and wanted to know if we could not refactor the code ..?
thank you.
Try this:
this.notInModel = function (tab1, tab2) {
for (var i = tab1.length; i--; ) {
for (var j = tab2.length; j--; ) {
if(tab1[i].name !== tab2[j].name)
continue;
var tab2InModel = tab2[j].inModel;
if(!tab1[i].inModel)
tab2.splice(j, 1);
if(!tab2InModel)
tab1.splice(i, 1);
}
}
}
The trick is to loop through both tabs in reverse order and make the checks for the name and inModel properties for every element combination.
DEMO
You could make it more modular by creating a new function to iterate through the arrays like this:
this.notInModel = function (tab1, tab2) {
function nim(t1,t2) {
for (var i = 1; i <= t1.length - 1; i++) {
if (!t1[i].inModel) {
for (var j = 1; j <= t2.length - 1; j++) {
if(t1[i].name === t2[j].name)
t2.splice(j, 1);
}
}
}
}
nim(tab1,tab2);
nim(tab2,tab1);
}
The following code seems to be equivalent, though I could not test without the definition of splice or without knowing how inModel field is set.
this.notInModel = function (tab1, tab2) {
for (var i = 1; i <= tab1.length - 1; i++) {
for (var j = 1; j <= tab2.length - 1; j++) {
if(!tab1[i].inModel) {
if (tab1[i].name === tab2[j].name)
tab2.splice(j, 1);
}
if(!tab2[j].inModel) {
if (tab1[i].name === tab2[j].name)
tab1.splice(i, 1);
}
}
}
}

Categories

Resources