getting different random numbers in a loop not random - javascript

I am filling an array with random numbers with a loop, but the random number is exactly the same for each item in the array, I think this is because of the seed value that Math.rand() uses. How can i get a different number each time?
for(var i = 0; i < 10; i++){
number[i] = getRandom(0, 100);
}
function getRandom(a, b){
var num = Math.floor((Math.random()*b)+a);
return num;
}

Works fine for me:
http://jsfiddle.net/kzUUt/
You need to declare number though...
var number = new Array(10);
for(var i = 0; i < 10; i++)
{
number[i] = getRandom(0, 100);
console.log(number[i]);
}
function getRandom(a, b)
{
var num = Math.floor((Math.random()*b)+a);
return num;
}

Here is working demo.
var number = new Array();
for (var i = 0; i < 10; i++) {
number[i] = getRandom(0, 100);
}
function getRandom(a, b) {
return Math.floor((Math.random() * b) + a);
}
for (var j = 0; j < 10; j++) {
alert(number[j]);
}

Related

There's a bug in my code

My code isn't working . I'm trying to figure out what the bug is . Can someone help ? ! It's a function that is supposed to return an array of the first n triangular numbers.
For example, listTriangularNumbers(5) returns [1,3,6,10,15].
function listTriangularNumbers(n) {
var num;
var array = [];
for (i = 1; i <= n; ++i) {
num = i;
for (j = i; j >= 1; --j) {
num = num + j;
}
array.push(num);
}
return array;
}
Your initial initialization of j is wrong, it's starting at i so it's going too high. Also switched the operators around to make sure the conditions work.
function listTriangularNumbers(n) {
var num;
var array = [];
for (i = 1; i <= n; i++) {
num = i;
for (j = i-1; j >= 1; j--) {
num = num + j;
}
array.push(num);
}
return array;
}
You can try below code to get help:
a = listTriangularNumbers(8);
console.log(a);
function listTriangularNumbers(n) {
var num;
var array = [0];
for (i = 1; i <= n; i++) {
num = 0;
for (j = 1; j <= i; j++) {
num = num + j;
}
array.push(num);
}
return array;
}
You actually don't need 2 for-loops to do this operation. A single for-loop would suffice.
function listTriangularNumbers(n) {
// Initialize result array with first element already inserted
var result = [1];
// Starting the loop from i=2, we sum the value of i
// with the last inserted element in the array.
// Then we push the result in the array
for (i = 2; i <= n; i++) {
result.push(result[result.length - 1] + i);
}
// Return the result
return result;
}
console.log(listTriangularNumbers(5));
function listTriangularNumbers(n) {
var num;
var array = [];
for (i = 1; i <= n; ++i) {
num = i;
for (j = i-1; j >= 1; --j) {
num = num + j;
}
array.push(num);
}
return array;
}
var print=listTriangularNumbers(5);
console.log(print);

I'm having trouble adding these elements of my array together. the dash seems to inhibit the addition of each variable

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);
});

Sum of Primes using Sieve of Eratosthenes can't find bug

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.

Binary to Decimal Javascript

This code is supposed to take in a string ("100101") and output the result in decimal.I'm not quite sure why it's not working.Any help would be appreciated.
function BinaryConverter(str) {
var num=str.split("");
var powers=[];
var sum=0;
for(var i=0;i<num.length;i++){
powers.push(i);
}
for(var i=powers.length-1;i>=0;i--){
for(var j=0;j<num.length;i++){
sum+=Math.pow(2,i)*num[j];
}
}
return sum;
};
Here's my updated code below .For an input "011" it should do( 2^2*0 +2^1*1 +2^0*1)to =3 but it returns 14.Anybody know where I'm going wrong?
function BinaryConverter(str) {
var num=str.split("");
var powers=[];
var sum=0;
for(var i=0;i<num.length;i++){
powers.push(i);
}
for(var i=powers.length-1;i>=0;i--){
for(var j=0;j<num.length;j++){
sum+=Math.pow(2,i)*num[j];
}
}
return sum;
};
The two nested for loops have a problem. The first one subtracts an i, while the second adds an i forever creating a never ending loop.
ALSO your code should be this:
function BinaryConverter(str) {
var num=str.split("");
var powers=[];
var sum=0;
var numlength=num.length;
for(var i=0;i<num.length;i++){
powers.push(i);
}
for(var i=powers.length-1;i>=0;i--){
sum+=Math.pow(2,i)*num[numlength-i-1];
}
return sum;
};
I don't think you need the nested for loop
If you don't want to do that with parseInt() for some reason (like, because the homework problem says you can't), you can do this without the complexity and expense of calling Math.pow() for each digit:
function parseBinary(str) {
var i, value = 0;
for (i = 0; i < str.length; ++i)
value = value * 2 + +str[i];
return value;
}
That doesn't check for invalid input strings.
ace040686 only inverted the pow(2,i) and num[len-1-i] in his answer, otherwise it would be correct. Also you're pushing 0..str.length-1 unnecessarily to powers, those are implicit indices.
function convertNaive(str) {
var num = str.split("");
var len = num.length;
var sum = 0;
for(var i = len - 1; i >= 0; --i)
sum += Math.pow(2, len - 1 - i) * num[i];
return sum;
}
You can improve this a bit to avoid the unnecessary array and especially Math.pow:
function convertImproved(str) {
var len = str.length;
var sum = 0;
for(var i = 0, fac = 1; i < len; ++i, fac *= 2)
sum += fac * str[len - 1 - i];
return sum;
}
Try it yourself:
var input = "100101";
var logNode = document.getElementById("log");
function log(line) {
var text = document.createTextNode(line);
var node = document.createElement("p");
node.appendChild(text);
logNode.appendChild(node);
}
function convertNaive(str) {
var num = str.split("");
var len = num.length;
var sum = 0;
for(var i = len - 1; i >= 0; --i)
sum += Math.pow(2, len - 1 - i) * num[i];
return sum;
}
function convertImproved(str) {
var len = str.length;
var sum = 0;
for(var i = 0, fac = 1; i < len; ++i, fac *= 2)
sum += fac * str[len - 1 - i];
return sum;
}
log("input: " + input);
log("parseInt(input, 2): " + parseInt(input, 2));
log("convertNaive(input): " + convertNaive(input));
log("convertImproved(input): " + convertImproved(input));
<div id="log" />
Here is the simple implementation of binary to decimal in javascript.
main();
function main() {
let binaryInput = 10000100111;
let decimalOutput = binaryTodecimal(binaryInput);
console.log(decimalOutput);
}
function binaryTodecimal(input) {
let inputString = input.toString();
let result = 0;
let exponent = 1;
let currentBit = 0;
for (let i = inputString.length - 1; i >= 0; i--) {
currentBit = parseInt(inputString[i]);
currentBit *= exponent;
result += currentBit;
exponent *= 2;
}
return result;
}

$.inArray() jQuery function

I can not figure out why this is not working, should be returning an array with four distinct values, but it doesn't
$(document).ready(function (e) {
var randomNumbers = new Array();
for (var i = 0; i < 4; i++) {
randomNumbers[i] = Math.floor((Math.random() * 9) + 1);
while ($.inArray(randomNumbers[i], randomNumbers) !== -1) {
randomNumbers[i] = Math.floor((Math.random() * 9) + 1);
}
}
for (var i = 0; i < randomNumbers.length; i++) {
if ($('#output').html() !== '') {
var existingOutput = $('#output').html();
$('#output').html(existingOutput + randomNumbers[i]);
} else {
$('#output').html(randomNumbers[i]);
}
}
});
Can cut out the if and the second loop by appending the joined array
$(document).ready(function (e) {
var randomNumbers = new Array();
for (var i = 0; i < 4; i++) {
var ran =newNum();
/* unique check*/
while ( $.inArray( ran, randomNumbers) >-1){
ran=newNum();
}
randomNumbers.push(ran)
}
$('#output').append( randomNumbers.join(''))
});
function newNum(){
return Math.floor((Math.random() * 9) + 1);
}
Alternate solution using a shuffle method ( found in this post ):
var a=[1,2,3,4,5,6,7,8,9];
function Shuffle(o) {
for(var j, x, i = o.length; i; j = parseInt(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
return o;
};
$('#output').append( Shuffle(a).splice(0,4).join(''))
If you generate a number and put it in the array, don't you think that $.inArray() will tell you so?
Your while loop is guaranteed to hang. A member of the array (randomNumbers[i]) is always, of course, going to be in the array. In fact $.inArray() when called to see if randomNumbers[i] is in the array will return i (if it's nowhere else, which in this case it can't be). Your loop won't get past the first number, so it'll just be 0.
I don't understand the point of your while loop. inArray only returns -1 if the value isn't found, which it will always be found, so you're just creating an infinite loop for yourself that will keep resetting the random number generated.
If you're just trying to add four random numbers to a div, this worked for me:
$(document).ready(function (e) {
var randomNumbers = new Array();
for (var i = 0; i < 4; i++) {
randomNumbers[i] = Math.floor((Math.random() * 9) + 1);
}
for (var i = 0; i < randomNumbers.length; i++) {
if ($('#output').html() !== '') {
var existingOutput = $('#output').html();
$('#output').html(existingOutput + randomNumbers[i]);
} else {
$('#output').html(randomNumbers[i]);
}
}
});
Further refactored:
$(document).ready(function (e) {
var randomNumbers = new Array();
for (var i = 0; i < 4; i++) {
randomNumbers[i] = Math.floor((Math.random() * 9) + 1);
}
for (var i = 0; i < randomNumbers.length; i++) {
$('#output').append(randomNumbers[i]);
}
});

Categories