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!
Related
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));
}
The code below only executes through the first for loop once, yet all the other for loops perform as expected. Does anyone know why this is the case? I'm not sure how relevant the bulk of the (inefficient, poorly formatted) code within the loop is but I include it nonetheless.
var numbers = [9795526789839145, 2861747566959730, 4498854833783559, 6301982162016598, 1131197164065322];
for (i = 0; i < numbers.length; i++) {
var current = numbers[i];
var currentStr = current.toString();
var reverseStr = currentStr.split('').reverse().join('');
var reverseArr = [];
for (i = 0; i < reverseStr.length; i++) {
reverseArr.push(reverseStr[i]);
}
var A = 0;
for (i = 0; i < reverseArr.length; i += 2) {
A += Math.round((reverseArr[i]));
}
var evenDigits = [];
for (i = 1; i < reverseArr.length; i += 2) {
evenDigits.push(reverseArr[i]);
}
for (i = 0; i < evenDigits.length; i++) {
evenDigits[i] = evenDigits[i] * 2;
if (evenDigits[i] > 9) {
var temp = evenDigits[i].toString();
var firstInt = Math.round(temp[0]);
var secondInt = Math.round(temp[1]);
evenDigits[i] = firstInt + secondInt;
}
}
var B = 0;
for (i = 0; i < evenDigits.length; i++) {
B += evenDigits[i];
}
var sum = A + B;
if (sum % 10 == 0) {
console.log('Yes');
} else console.log('No');
}
In your code you are using same instance of 'i' variable to iterate all loops.
Solution is to use different index variables to iterate external and internal loops
var numbers = [9795526789839145, 2861747566959730, 4498854833783559, 6301982162016598, 1131197164065322];
var i = 0;
var j = 0;
for (j=0; j < numbers.length; j++) {
var current = numbers[j];
/...
}
JavaScript behaves like this because 'i' is not scoped to block (like in Java od C#). In ES2015 you can use let or const to bind variable to block scope (in this sample to for loop)
I have this so far, trying to get it to find the sum of each one of any number of inputted numbers with integers and "-"s.
When I run this,
var howM = prompt("How many cards?")
var arr = [];
for (var i = 0; i < howM; i++)
arr.push(prompt("Enter a card:"));
console.log(arr)
var sumpre = [];
for (var i = 0; i <= howM; i++) {
var sum = 0;
var eXt = arr[i];
eXt = eXt.replace(/-/g, "");
for (i = 0; i < eXt.length; i++) {
sum += parseInt(eXt.substr(i, 1));
}
sumpre.push(sum);
}
console.log(sumpre)
I have also tried
var howM = prompt("How many cards?")
var arr = [];
for (var i = 0; i < howM; i++)
arr.push(prompt("Enter a card:"));
console.log(arr)
for (var i = 0; i < howM; i++) {
var sum = 0;
var eXt = arr[i]
eXt = eXt.replace(/-/g, "");
for (i = 0; i < eXt.length; i++) {
sum += parseInt(eXt.substr(i, 1));
}
}
console.log(sum);
In both cases I get the sum for the first piece in the array and then undefined. How do I get it to run for each piece? I kind of have an idea of what is wrong with it I just don't quite know how to fix it.
You need to use a second counter for the nested for loop, like so:
var howM = prompt("How many cards?")
var arr = [];
for(var i = 0; i < howM; i++)
arr.push(prompt("Enter a card:"));
console.log(arr)
var sumpre = [];
for(var i = 0; i < howM; i++) {
var sum = 0;
var eXt = arr[i];
eXt = eXt.replace (/-/g, "");
for (var j = 0; j < eXt.length; j++) {
sum += parseInt(eXt.substr(j, 1));
}
sumpre.push(sum);
}
console.log(sumpre)
Your var sum = 0; inside your for-loop meaning sum variable will not be accessible outside of the loop
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>");
}
I want to create a multidimensional array like this:
array[0][1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
array[1][21,22,23,24,25,26,27....]
array[.][....]
How can I do this in Javascript?
I have tried this:
var squares = new Array();
for(var i = 1; i <= 8; i++)
{
for(var j = 1; j <= 20; j++)
{
squares.push(i, j);
}
}
How can I accomplish this?
You can do something like this:
var squares = new Array();
for(var i = 0; i <= 8; i++)
{
squares[i] = new Array();
for(var j = (i * 20) + 1; j <= 20 * i + 20; j++)
if (squares[i] == null)
squares[i] = j;
else
squares[i].push(j);
}
Output comes like:
array[0][1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
array[1][21,22,23,24,25,26,27....]
var array = []; // Main array
var numArrays = 10, // Number of sub-arrays
numPerArray = 20; // Number of squares per sub-array
for(var i = 0; i < numArrays; i++){
var subArray = [];
// Number to start at
var start = i * numPerArray;
// Count up to start + numPerArray
for(var j = start; j < start + numPerArray; j++){
subArray.push(j);
}
// Add to main array
array.push(subArray);
}
Use modulus operand to limit the inner array's size
var limit = 80
var inner_limit = 20
var square=[]
var inner =[]
for(var i=1;i<=limit;i++){
inner.push(i)
if(i%inner_limit==0){
square.push(inner)
inner = []
}
}
You can do it with two "for" loops. In the first loop you go through the main array and for each element add the elements from the second loop.
var arrayLength = 10; // Main array length
var limit = 20; // Number of squares
var array = [];
for ( var i = 0; i < arrayLength; i++ )
{
array[i] = []; // Create subArray
for( var j = 1; j <= limit; j++ )
{
array[i].push(j);
}
}