I have variable with string values in two dimensional array format.
var arrayList=[["1","2"],["6","3600","11","60"],["1","2","3","4","5","6"]];
What I want,each odd position value multiply with next even position and finally adding that values
like.
["1","2"]=(1*2);
["6","3600","11","60"]=((6*3600)+(11*60));
["1","2","3","4","5","6"]=((1*2)+(3*4)+(5*6))
for this I written the following code,second and third cases are not working.
really sorry might be it's very basic question but I tested each and every line it's seems code is correct but in second and third cases getting Nan.
var result=[];
for (var index = 0; index < arrayList.length; index++) {
var innerResult=0;
for (var jndex = 0; jndex < arrayList[index].length; jndex++) {
var cali=parseInt(arrayList[index][jndex])*parseInt(arrayList[index][jndex+1]);
innerResult=innerResult+cali;
jndex=jndex+2;
};
result.push(innerResult);
};
result
I am getting like this [3,Nan,Nan].
please can anyone help me.
Thanks
You're incrementing jndex on each loop and then you are adding 2 more at the end of that loop. You have two options, changing this:
for (var jndex = 0; jndex < arrayList[index].length; jndex++) {
to:
for (var jndex = 0; jndex < arrayList[index].length; jndex+=2 ) {
or this:
jndex=jndex+2;
to:
jndex=jndex+1;
If you do the first one, you no longer need the increment within the loop.
I have written this algorithm that I believe might help you.
var array = [["1","2"],["6","3600","11","60"],["1","2","3","4","5","6"]];
array.map(function(subArray){
var total = 0;
for(var i = 1; i < subArray.length; i += 2)
total += parseInt(subArray[i], 10) * parseInt(subArray[i - 1], 10);
return total;
});
The jindex will be incremented by the loop as well. This will mean the jindex is incremented by 3 each loop.
Consider the case where jindex is arrayList[index].length - 1; when you parseInt(arrayList[index][jndex+1]) you will reach outside the bounds of the array, and get undefined (and parseInt(undefined) is NaN again).
If you fix those, you should find your code works;
var result = [];
for (var index = 0; index < arrayList.length; index++) {
var innerResult = 0;
for (var jndex = 0; jndex < arrayList[index].length - 1; jndex++) {
var cali = parseInt(arrayList[index][jndex]) * parseInt(arrayList[index][jndex + 1]);
innerResult = innerResult + cali;
jndex = jndex + 1;
};
}
http://jsfiddle.net/Bwx2g/
Try this:
var result = [];
for (var index = 0; index < arrayList.length; index++) {
var innerResult = 0;
for (var jndex = 0; jndex < arrayList[index].length;) {
var cali = (parseInt(arrayList[index][jndex]) * parseInt(arrayList[index][jndex + 1]));
innerResult = innerResult + cali;
jndex = jndex + 2;
}
result.push(innerResult);
}
Inner for loop changed to while loop (you have double increment in for loop):
var result = [];
for (var index = 0; index < arrayList.length; index++) {
var innerResult = 0;
var j = 0;
while (j < arrayList[index].length) {
var cali = parseInt(arrayList[index][j]) * parseInt(arrayList[index][j + 1]);
innerResult = innerResult + cali;
j += 2;
}
result.push(innerResult);
};
Related
How to rotate a string in javascript and print the rotated versions of string without using any javascript functions, only for loops.
Given a string:
"hell"
Output:
"lhel", "llhe", "ellh", "hell"
I have tried but not succeded
var str1 = "hell";
let i = 0;
let len = str1.length - 1;
let temp;
for (let j = 0; j < len+1; j++) {
temp = str1[len]
while (i < len) {
console.log(str1[i]);
temp += str1[i];
i++;
}
console.log(temp);
//console.log(typeof temp, typeof str1)
str1 = temp;
}
You are almost there ! There is one thing missing, i should be reset at each iteration of the for loop, otherwise, the while (i < len) will be "played" only once :
var str1 = "hell";
let len = str1.length - 1;
let temp;
for (let j = 0; j < len+1; j++) {
let i = 0; // <-------------------- notice this
temp = str1[len]
while (i < len) {
//console.log(str1[i]);
temp += str1[i];
i++;
}
console.log(temp);
//console.log(typeof temp, typeof str1)
str1 = temp;
}
You could take a nested loop and get the characters at the position of i and j and take the reminder operator % for preventing characters outside of the string.
var string = "hell",
i, j,
temp;
for (i = 0; i < string.length; i++) {
temp = '';
for (j = 1; j <= string.length; j++) temp += string[(i + j) % string.length];
console.log(temp);
}
You can try this method. Basically you have two loops the first loop with (i) is for the possibilities the second one is for the shifting
var strValue = "hell";
var temp;
for(var i = 0; i < strValue.length; i++){
temp = "";
for(var j = 1; j < strValue.length; j++){
temp += strValue[j];
}
temp += strValue[0]
strValue = temp;
console.log(strValue)
}
In first loop add all symbols which indexes are greater then amount of shift steps (i in this case).
And add rest symbols after it the second loop.
const str = 'hello';
for (let i = 0; i < str.length; i++) {
let shifted = '';
for (let j = i; j < str.length; j++) {
shifted += str[j];
}
for (let j = 0; j < i; j++) {
shifted += str[j];
}
console.log(shifted);
}
i know this has already been answered so.. this is how i'd do it.
maybe you can learn from it.
const str = "hell";
// this loop will set the offset. so if it's 1, "hell" will become "ellh"
for (let offset = 0; offset < str.length; offset++) {
// this will contain the final string
let output = "";
// here we iterate through all the characters
for (let index = 0; index < str.length; index++) {
// and use modulo to switch 5 to 1 (in case length is 4)
output += str[(index + offset) % str.length];
}
// there we go
console.log(output);
}
let str = 'hell';
for(let i=0;i<str.length;i++){
str = str.substring(1,str.length) + str[0];
console.log(str);
}
I try to develop a simple program that prints all numbers in between 1 and 100 that divide by 3 without any residual and calculate the total sum
I did it with for loop:
var sum = 0;
for (var i = 3; i <= 100; i = i + 3) {
document.write("<br/>" + i);
sum = sum + i;
}
document.write("<br/>sum = " + sum); //1683
But I failed when I wanted to do it with array:
var numbers = [];
var sum = 0;
for (var i = 0; i <= 100; i = i + 3) {
numbers[i - 1] = i;
}
for (var index = 0; index < 100; index++) {
document.write("<br/>" + numbers[index]);
sum = sum + i;
}
document.write("<br/>sum = " + sum);
Use it like this,
Array indexes should start from 0, that is why I have introduced another variable j=0
var numbers = [];
var sum = 0;
for (var i = 0, j = 0; i <= 100; i = i + 3, ++j) {
numbers[j] = i;
}
Update
First Issue:
In your code, ie. below code of yours,
for (var i = 0; i <= 100; i = i + 3) {
numbers[i - 1] = i;
}
In the first iteration,
i = 0;
numbers[0-1] = i // i.e numbers[-1] = 0;
and in your second loop, you are starting the index from 0
for (var index = 0; index < 100; index++) {
Second issue:
Also, if you don't use a sequential counter to fill the Array, you will end with undefined values for the ones you did not fill.
If you notice, the output after the loop, it says numbers.length = 99 which is wrong it will not have that many items in it.
Third Issue:
In below code, even if you introduce a sequential counter, this is still wrong
for (var i = 0; i <= 100; i = i + 3) {
numbers[i - 1] = i;
}
because i should start with 3 instead of 0, otherwise you will end up with 34 elements in the array because numbers[0] will be 0;
Fourth Issue:
In this code,
for (var index = 0; index < 100; index++) {
document.write("<br/>" + numbers[index]);
sum = sum + i;
}
You don't actually have to loop it till 100, you already have the numbers array filled, so you just need to use numbers.length, like this
var len = numbers.length;
for (var index = 0; index < len; index++) {
document.write("<br/>" + numbers[index]);
sum = sum + i;
}
A better way to write this
var numbers = [];
for (var i = 3, j=0; i <= 100; i = i + 3, j++) {
numbers[j] = i;
}
var sum = numbers.reduce((a, b) => a+b);
console.log(sum);
The line var sum = numbers.reduce((a, b) => a+b); uses Array.reduce() method.
adding number to array
var numbers = [];
for(var i = 3; i <= 100; i = i +3){
numbers.push(i);
}
summation and printing values
var sum = 0;
for (var i = 0; i < numbers.length; i++) {
document.write("<br/>" + numbers[i]);
sum = sum + numbers[i];
}
document.write("<br/>sum = " + sum); //1683
There are few issues in your code.
for (var i = 0; i <= 100; i = i + 3) {
numbers[i - 1] = i;
}
1: array is 0 based. so first insertion into the array goes for a toss.
2: the number array created will have skipping index like 3, 6 ,9
for (var index = 0; index < 100; index++) {
document.write("<br/>" + numbers[index]);
sum = sum + i;
}
3: Here you are iterating index till 100 , you should iterate it till the length of the numbers array only.
when index is 1,2
number[index] will become undefined.
4: sum = sum + i (i ??????)
You should try like this or you can also use push()
var numbers = [];
var sum = 0;
for (var i = 0,j=0; i <= 100; i = i + 3, j= j+1) {
numbers[j] = i; // array is 0 based.
}
for (var index = 0; index < numbers.length; index++) {
document.write("<br/>" + numbers[index]);
sum = sum + numbers[index];
}
document.write("<br/>sum = " + sum);
Indexes in an array begin with zero.
for (var i = 0; i <= 100; i = i + 3) {
numbers[i - 1] = i; // In the first iteration, there will be numbers[-1] = i;
}
You have several issues i suppose.
var numbers = [];
var sum = 0;
for (var i = 0; i <= 100; i = i + 3) {
numbers.push(i);
}
for (var index = 0; index < numbers.length; index++) {
document.write("<br/>" + numbers[index]);
sum = sum + i;
}
document.write("<br/>sum = " + sum);
Also for array you can use:
for (var i in array) {
console.log(array[i]);
}
And I'm pretty sure, that array of number sequence is absolutely useless, if there is no other information in it.
Try this
var numbers = [];
var sum = 0;
for (var i = 0; i <= 100; i = i + 3) {
numbers[(i-3)/3] = i;
}
for (var index = 0; index < numbers.length; index++) {
document.write("<br/>" + numbers[index]);
sum = sum + numbers[index];
}
document.write("<br/>sum = " + sum);
Here is the fiddle i tried
https://jsfiddle.net/4ncgnd7c/
This should work using a single loop
var numbers = [];
var sum = 0;
for (var i = 3; i <= 100; i = i + 3) {
numbers[i] = i;
document.write("<br/>" + i);
sum = sum + i;
}
document.write("<br/>sum = " + sum);
I'm trying to get the following code to add each number in the element separately and not the whole array together but the dash seems to stop the loop from calculating the total sum of each element. I can't seem to make it so it'll except any length of number for the variable. Any help is greatly appreciated!
var creditNum = [];
creditNum[0] = ('4916-2600-1804-0530');
creditNum[1] = ('4779-252888-3972');
creditNum[2] = ('4252-278893-7978');
creditNum[3] = ('4556-4242-9283-2260');
var allNum = [];
var total = 0;
var num = 0;
var cnt = 0;
for (var i = 0; i < creditNum.length; i++) {
num = creditNum[i];
for (var j = 1; j <= num.length; j++) {
var num = creditNum[i].substring(cnt, j);
console.log(creditNum[i].charAt(cnt));
console.log(cnt, j);
cnt = cnt + 1;
}
if (num != "-") j = j++;
console.log(parseInt(num));
}
console.log(total);
Assuming the intent is to add '4916-2600-1804-0530' and output the value as 49, then the following modification will achieve that.
var creditNum = ['4916-2600-1804-0530', '4779-252888-3972', '4252-278893-7978','4556-4242-9283-2260'];
for (var i = 0; i < creditNum.length; i++) {
var num = creditNum[i].replace(/\-/g, '');
var total = 0;
for (var j = 0; j < num.length; j++) {
total += Number(num[j]);
}
console.log(creditNum[i], total);
}
Using native array methods, the code can be refactored as the following.
var creditNumbers = ['4916-2600-1804-0530', '4779-252888-3972', '4252-278893-7978','4556-4242-9283-2260'];
creditNumbers.forEach(function(creditNumber) {
var num = creditNumber.replace(/\-/g, '').split('');
var total = num.reduce(function(tally, val) {
return tally += Number(val);
}, 0);
console.log(creditNumber, total);
});
I'm working in JavaScript and this is a bit confusing because the code is returning the correct sum of primes. It is working with larger numbers. There is a bug where for 977 it returns the sum of primes for 976, which is 72179, instead of the sum for 977 which is 73156. Everything I've test so far has come back correctly.
function sumPrimes(num) {
var sum = 0;
var count = 0;
var array = [];
var upperLimit = Math.sqrt(num);
var output = [];
for (var i = 0; i < num; i++) {
array.push(true);
}
for (var j = 2; j <= upperLimit; j++) {
if (array[j]) {
for (var h = j * j; h < num; h += j) {
array[h] = false;
}
}
}
for (var k = 2; k < num; k++) {
if (array[k]) {
output.push(k);
}
}
for (var a = 0; a < output.length; a++) {
sum += output[a];
count++;
}
return sum;
}
sumPrimes(977);
The problem stems from the fact that your "seive" Array is indexed from 0, but your algorithm assumes that array[n] represents the number n.
Since you want array[n]===true to mean that n is prime, you need an Array of length 978 if you want the last item to be indexed as array[977] and mean the number 977.
The issue seems to be fixed when I change all instances of < num to < num+1.
I am not sure how to phrase this, so please re-title this question if it doesn't make sense. Anyways, this is what I am trying to do.
I have a variable with the length of 9.
And then I have another variable with the length of 3.
How do I write a loop that iterates through all 9 but starts over every third time?
For example: I have this,
x = 3;
l = 9;
for ( var i = 0; i < l; i++)
{
console.log(i + 1);
}
output = 1,2,3,4,5,6,7,8,9
The output I want to create
output = 1,2,3,1,2,3,1,2,3
I was thinking there might be away to do this with an if statement or possibly modulus, but wasn't quite sure how to implement it. What would be a good way to do this? Thanks in advance.
Embrace the modulus:
function expand(length, loop_length) {
for (var i = 0; i < length; i++) {
console.log(i % loop_length + 1);
}
}
expand(9, 3) // => 1, 2, 3, 1, 2, 3, 1, 2, 3
x = 3;
l = 9;
for ( var i = 0; i < l; i++)
{
console.log(i % x + 1);
}
output = 1,2,3,1,2,3,1,2,3
See it in action here: http://jsfiddle.net/BgBGL/
If you want to loop from a min value to a max value a specific number of times, the easiest way is just to have 2 loops, like this:
var min = 1, max = 3, times = 3;
for (var i = 0; i < times; i++) {
for (var j = min; j <= max; j++) {
console.log(j);
}
}
Or if you want to fix total length of the sequence, then yes, you can do it with a single loop and a little bit of math:
var min = 1, max = 3, totalLength = 9;
for (var i = 0; i < totalLength; i++) {
console.log((i % (max - min + 1)) + min);
}
For that case, this works:
x = 3;
l = 9;
for ( var i = 0; i < l; i++)
{
var num=(i %(x+1)) || 1;
console.log(num);
}
You could go mad with following syntax:
var i = 0;
do {
console.log(i++ % 3 + 1);
} while (i < 9);
Alternative, you could define 3 and 9 as a variable also.
I took an advantage of the fact that calling i++ will display old variable and increases it by 1 after, so I saved some bits!
See: fiddle example
x = 3;
l = 9;
for ( var i = 0; i <= l; i++)
{
for ( var j = 1; j <= x; j++)
{
console.log(j);
}
}