$rowCount = 40 ;
for (var $j = 0; $j < $rowCount -1; $j++) {
var currentNum = #something
}
I need to have a mechanism, where I can loop in a way that I will be applying the values to the currentNum in a random way.
Eg: At the end of the loop, the currentNum should have the value (0....39). But it shouldn't be applied starting from 0,1,2,3,4,5,6,7,8,.....39.
It should be applied in a random way like 39, 4, 5,17, 28 , 16 .... and it should cover all the numbers from 0-40. I figured this can be achieved using a HashMap in java, but how to implement in javascript?
var numbers = Array(rowCount);
for(var i = 0; i < rowCount; i++) numbers[i] = i;
shuffle(numbers); // randomly shuffle array elements
for (var $j = 0; $j < $rowCount -1; $j++) {
var currentNum = numbers[i];
}
You can try something like this:
var _data = [];
for (var i = 0; i < 40; i++) {
_data.push(i);
}
var result = [];
_data.slice().forEach(function(){
result.push(getRandomValue(_data))
});
function getRandomValue(arr,i) {
var r = Math.floor(Math.random() * arr.length);
var result = arr[r];
arr.splice(r, 1);
return result;
}
document.write("<pre>" + JSON.stringify(result,0,4) + "</pre>");
Related
I need to print a number series like below in javascript
123567101112161718232425
After 3 numbers next will be empty. that will increase as 1 number missed, next 2 number missed like that.
Can anyone help me how to do that..
Something like this might work I believe:
Idea: after every 3 numbers, increase the jump count. Before increasing, just add it to the current Number.
var retStr = '';
var jump = 1;
var currNum = 1;
for(var i=0;i<10;i++){
for(var j=0;j<3;j++){
retStr = retStr + (currNum++);
}
currNum += jump++;
}
console.log(retStr);
Output: "123567101112161718232425313233404142505152616263737475"
var serie = "";
var skip = 0;
for (var i=1; i<100; i++)
{
serie = serie + i + (i+1) + (i+2)
i= i+2
skip = skip +1;
i= i + skip;
}
console.log(serie);
var count = 1 ;
var j=1;
for(var i=0;i<5;i++){
for(j=count; j<(count+3); j++){
document.write(j);
}
count = j+=i+1;
}
function Print(N) {
var arr = [];
var k =0;
var p =0 ;
for (var i = 1; i <= N; i++) {
arr.push(i + k)
if (arr.length % 4 == 0) {
k= k+p ;
p++;
k++;
}
}
return console.log(arr);
}
Print(20)
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 have a numeric 2D array (an array of arrays, or a matrix) and I need to do simple matrix operations like adding a value to each row, or multiplying every value by a single number. I have little experience with math operations in JavaScript, so this may be a bone-headed code snippet. It is also very slow, and I need to use it when the number of columns is 10,000 - 30,000. By very slow I mean roughly 500 ms to process a row of 2,000 values. Bummer.
var ran2Darray = function(row, col){
var res = [];
for (var i = 0 ; i < row; i++) {
res[i] = [];
for (var j = 0; j < col; j++) {
res[i][j] = Math.random();
}
}
return res;
}
var myArray = ran2Darray(5, 100);
var offset = 2;
for (i = 0; i < myArray.length; i++) {
aRow = myArray[i];
st = Date.now();
aRow.map(function addNumber(offset) {myArray[i] + offset*i; })
end = Date.now();
document.write(end - st);
document.write("</br>");
myArray[i] = aRow;
}
I want to avoid any added libraries or frameworks, unless of course, that is my only option. Can this code be made faster, or is there another direction I can go, like passing the calculation to another language? I'm just not familiar with how people deal with this sort of problem. forEach performs roughly the same, by the way.
You don't have to rewrite array items several times. .map() returns a new array, so just assign it to the current index:
var myArray = ran2Darray(5, 100000);
var offset = 2;
var performOperation = function(value, idx) {
return value += offset * idx;
}
for (i = 0; i < myArray.length; i++) {
console.time(i);
myArray[i] = myArray[i].map(performOperation)
console.timeEnd(i);
}
It takes like ~20ms to process.
Fiddle demo (open console)
Ok, Just a little modification and a bug fix in what you have presented here.
function addNumber(offset) {myArray[i] + offset*i; }) is not good.
myArray[i] is the first dimention of a 2D array why to add something to it?
function ran2Darray (row, col) {
var res = [];
for (var i = 0 ; i < row; i++) {
res[i] = [];
for (var j = 0; j < col; j++) {
res[i][j] = Math.random();
}
}
return res;
}
var oneMillion = 1000000;
var myArray = ran2Darray(10, oneMillion);
var offset = 2;
var startTime, endTime;
for (i = 0; i < myArray.length; i++) {
startTime = Date.now();
myArray[i] = myArray[i].map(function (offset) {
return (offset + i) * offset;
});
endTime = Date.now();
document.write(endTime - startTime);
document.write("</br>");
}
try it. It's really fast
https://jsfiddle.net/itaymer/8ttvzyx7/
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);
};