javascript generate a number of a variable length [duplicate] - javascript

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Generating random numbers in Javascript in a specific range?
If I input a length of say 4, I need to get back a number between 0 9999.
And I want it to be 0 padded (0004), but that may be another function.

Try this:
function getNumber(range){
var max = Math.pow(10,range);
var num = Math.Random() * max;
}
As for the zerofill you're better off trying what Nathan suggested on his comment this

for(var x = 5, i = 0, y = ""; i < x​;​ ++i, y +​​= "9");
Math.floor(Math.random()*parseInt(y)); //random number
​
In the for loop, x would be your input length. You could move the definition of x outside the loop also if you needed.
You could also try this and see which one runs faster (probably the first one, fyi):
for(var x = 5, y = "", i = 0; i < x; ++i, y += Math.floor(Math.random()*9));
parseInt(y); //random number

function getRandom(c){
var r = (Math.random() * Math.pow(10, c)).toFixed(0);
while(r.length != c)
r = "0" + r;
return r;
}
getRandom(3);

Well, here's the number part. You can probably figure out the padding part.
function makeNumber(number){
var nines = "";
var returnNumber = "";
for(var i = 0; i < number; i++)
{
nines+= "9";
}
for(var i = 0; i < number; i++)
{
var returnNumber += String(Math.Random() * parseInt(nines));
}
return returnNumber;
}

Kind of sloppy but works:
var length = 4; //<-- or get however you want
var big = "";
for (i=0; i<length; i++) {
big = big + "9";
}
var big = parseInt(big);
var random = Math.floor(Math.random() * big).toString();
var random_len = random.toString().length;
if (random_len < length) {
var random_padded = random.toString()
padding = length - random_len;
for (i=0; i<padding; i++) {
random_padded = "0" + random_padded;
}
random = random_padded
}
alert(random);

Since it's javascript, you may want to take advantage of its weak typing in this scenario. One particular hackerish way of doing this is to generate n numbers between 0-9 and use string concatenation.
This post seems to have the answer: JavaScript expression to generate a 5-digit number in every case and you can pad with concatenation.
EDIT: so here is my implementation of it:
function random(x){
var rand = Math.floor(Math.random() * Math.pow(10,x));
var dummy = rand;
while (dummy<Math.pow(10,x-1)){
rand = "0" + rand;
dummy = dummy*10;
}
return rand;
}

Related

Counting duplicate random numbers from a for loop

I am trying to create a score predictor based on a teams goal difference (football). I am new to JavaScript, and I have managed to get this far.
I want it to be like spinning a ten-sided dice 20 times + the team's goal difference. I have got this bit sorted I think. With my code now I have a list of random numbers logged in the console which is what I wanted. Now I would like to choose a number (e.g., 2) and see how many times this occurs in the list. I'd like to save this in a new variable called homeFinalScore (So if '2' occurs three times in the list of random numbers, the homeFinalScore variable should be 3). I've tried several things but have been unable to sort it yet!
Any help would be extremely helpful. Thank you in advance!
var homeFinalScore = 0;
function calculateScore(){
var homeTeam = document.getElementById("HomeTeam").value;
var awayTeam = document.getElementById("AwayTeam").value;
var homeGd = parseInt(document.getElementById("HomeGD").value);
var awayGd = parseInt(document.getElementById("AwayGD").value);
var homeGd = 20 + homeGd;
var awayGd = 15 + awayGd;
for (i = 0; i < homeGd; i++) {
var randNum = Math.floor(Math.random() * 11);
console.log(randNum);
}
}
You can create an array, use Array.prototype.push() to push randNum to the array, then use Array.prototype.filter(), .length to determine how many occurrences of a value are present within array.
var homeGd = 20 + 2;
var awayGd = 15 + 2;
var arr = [];
function countOccurrences(n, arr) {
return arr.filter(function(value) {
return value === n
}).length;
}
for (i = 0; i < homeGd; i++) {
var randNum = Math.floor(Math.random() * 11);
arr.push(randNum);
}
console.log(arr);
console.log(countOccurrences(2, arr));
Alternatively, you can increment a variable when randNum is equal to a value.
var homeGd = 20 + 2;
var awayGd = 15 + 2;
var n = 0;
var num = 2;
for (i = 0; i < homeGd; i++) {
var randNum = Math.floor(Math.random() * 11);
console.log(randNum);
if (randNum === num) {
++n
}
}
console.log("occurrences of 2:", n);
const homeGd = 10;
const randomNumbers = []; // array of random numbers
for (i = 0; i < homeGd; i++) {
randomNumbers.push(Math.floor(Math.random() * 11));
}
const countBy = randomNumbers.reduce((acc, current) => {
acc[current] = (acc[current] || 0) + 1;
return acc;
}, {});
console.log(countBy);

How to create 100 random numbers between 1 and 9999 with 4 digits, and place numbers in 10 rows of 10 numbers?

Having an issue figuring out how to get this solved, and I've searched and looked for answers, but they don't resemble what I'm looking for.
This is beginner stuff, I realize but any help would be highly appreciated.
The code below was given by my teacher and it works for creating one random number. For the life of me I can't figure out how to make this create 100 random numbers and make a 10 x 10 square of them.
eg. 5468 2367 1587 2587 2310 9802 0154 8753 4965 2571
3249 3248 2158 4659 1321 1278 9871 0123 4654 4587
etc. for 10 rows.
<div id="answer"></div>
<script type="text/javascript">
function giveValues() {
var length, zeroes;
var number = Math.round((Math.random() * 9999));
// toString()-method and lenght to set amount of digts
zeroes = 4 - number.toString().length;
for (var j = 1; j <= zeroes; j++) {
number = "0" + number;
}
return number;
}
document.getElementById("answer").innerHTML = giveValues();
I also know that there is if (j % nameofvar == 0) { for making a new line, but am unable to make that work.
Considering that you haven't learned arrays yet, try the following as I think it's best inline with what you're looking for. Here is a Plunker as well http://plnkr.co/edit/LltYPtSfR9Ndo46kYmVN?p=preview.
<div id="answer"></div>
<script>
function giveValues() {
var length, zeroes;
var number = Math.round((Math.random() * 9999));
// toString()-method and lenght to set amount of digts
zeroes = 4 - number.toString().length;
for (var j = 1; j <= zeroes; j++) {
number = "0" + number;
}
return number;
}
var columns = 10;
var total = 100;
var bigString = "";
for (var i=0; i<total; i++) {
if (i != 0 && i % columns == 0) {
bigString += "<br/>";
}
bigString += giveValues(i).toString() + " ";
}
var answer = document.getElementById("answer");
answer.innerHTML = bigString;
</script>
Most basic way:
function lpad(number) {
while (number.toString().length < 4) {
number = "0"+number;
}
return number;
}
var max = 9999;
var matrix = [];
var size = 10;
for (var i = 0; i < size * size; i++) {
if (i % size === 0) {
matrix.push([]);
}
var number = lpad(Math.ceil(Math.random() * max));
matrix[matrix.length - 1].push(number);
}
document.getElementById("answer").innerHTML = matrix.join("<br />");
<div id = "answer"></div>
Using arrays is more effective, but you can also simply concatenate too.
You could just generate a large random number, and then limit it to 4 digits.
Try this:
function giveValues() {
var number = Math.round((Math.random() * 999999999));
return number.toString().substr(0, 4);
}
var arr = [];
for(var i = 0; i < 10; i++){
arr.push([giveValues(), giveValues(), giveValues(), giveValues(), giveValues(), giveValues(), giveValues(), giveValues(), giveValues(), giveValues()]);
}
document.getElementById("answer").innerHTML = arr.join(' <br/>').replace(/,/g,' ');
https://jsfiddle.net/moshekarmel1/34spm4hh/

JS: Array shuffling, not string shuffling

I am trying to shuffle a string array using JS. I hard-coded three sets of characters. 3 characters from each set were chosen at random and then concatenated. So the concatenated string is 3 letters, followed by 3 numbers, followed by 3 symbols. I want to shuffle this concatenated string so their order is randomized.
I already checked How to randomize (shuffle) a JavaScript array?, and my algorithm and code essentially matches what the second solution was, except for the fact that I have the shuffle loop in a bigger function (instead of as its own function). Perhaps I should add the shuffling to its own function and call it within the bigger function, but I think that will still give me the same result.
The "shuffling part" of the function isn't actually shuffling. When I debug it with console.log(temp) and console.log(tp[rnd]), the correct values are showing. Basically, the function is returning the unshuffled string that I wanted to shuffle.
var letterSet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
var numberSet = "0123456789";
var symbolSet = "~!##$%^&*()-_+=><";
this.generatePassword = function() {
var rl = "";
var rn = "";
var rs = "";
var tp = "";
// 3 random letters
for(var i = 0; i < 3; i++) {
var rnd = Math.floor((Math.random() * 52));
rl += letterSet[rnd];
}
// 3 random numbers
for(var i = 0; i < 3; i++) {
var rnd = Math.floor((Math.random() * 10));
rn += numberSet[rnd];
}
// 3 random symbols
for(var i = 0; i < 3; i++) {
var rnd = Math.floor((Math.random() * 17));
rs += symbolSet[rnd];
}
// String concatenation
tp = rl + rn + rs;
// Shuffling part
for(var i = 0; i < tp.length; i++) {
var rnd = Math.floor(Math.random() * tp.length);
var temp = tp[i];
tp[i] = tp[rnd];
tp[rnd] = temp;
}
return tp;
}();
I don't understand what is going wrong.
Your shuffle is a bit off, I looked at this which uses an array to shuffle.
// String concatenation
tp = rl + rn + rs;
tp=tp.split('');
// Shuffling part
for(var i = 0; i < tp.length; i++) {
var rnd = Math.floor(Math.random() * tp.length);
var temp = tp[i];
tp[i] = tp[rnd];
tp[rnd] = temp;
}
tp=tp.join("");
When you perform the assignments tp[i] = tp[rnd] and tp[rnd] = temp it is not changing the value of tp because strings are immutable. It is possible to manipulate a string and replace values using methods on String. Change those two assignments to the following:
for (var i = 0; i < tp.length; i++) {
var rnd = Math.floor(Math.random() * tp.length);
var temp = tp[i];
tp = tp.replace(tp.substr(i, 1), tp[rnd]);
tp = tp.replace(tp.substr(rnd, 1), temp);
}

Fastest way to loop through this array in Javascript on Chrome 36

I have a very big array which looks similar to this
var counts = ["gfdg 34243","jhfj 543554",....] //55268 elements long
this is my current loop
var replace = "";
var scored = 0;
var qgram = "";
var score1 = 0;
var len = counts.length;
function score(pplaintext1) {
qgram = pplaintext1;
for (var x = 0; x < qgram.length; x++) {
for (var a = 0, len = counts.length; a < len; a++) {
if (qgram.substring(x, x + 4) === counts[a].substring(0, 4)) {
replace = parseInt(counts[a].replace(/[^1-9]/g, ""));
scored += Math.log(replace / len) * Math.LOG10E;
} else {
scored += Math.log(1 / len) * Math.LOG10E;
}
}
}
score1 = scored;
scored = 0;
} //need to call the function 1000 times roughly
I have to loop through this array several times and my code is running slowly. My question is what the fastest way to loop through this array would be so I can save as much time as possible.
Your counts array appears to be a list of unique strings and values associated with them. Use an object instead, keyed on the unique strings, e.g.:
var counts = { gfdg: 34243, jhfj: 543554, ... };
This will massively improve the performance by removing the need for the O(n) inner loop by replacing it with an O(1) object key lookup.
Also, avoid divisions - log(1 / n) = -log(n) - and move loop invariants outside the loops. Your log(1/len) * Math.LOG10E is actually a constant added in every pass, except that in the first if branch you also need to factor in Math.log(replace), which in log math means adding it.
p.s. avoid using the outer scoped state variables for the score, too! I think the below replicates your scoring algorithm correctly:
var len = Object.keys(counts).length;
function score(text) {
var result = 0;
var factor = -Math.log(len) * Math.LOG10E;
for (var x = 0, n = text.length - 4; x < n; ++x) {
var qgram = text.substring(x, x + 4);
var replace = counts[qgram];
if (replace) {
result += Math.log(replace) + factor;
} else {
result += len * factor; // once for each ngram
}
}
return result;
}

How to return the sum of only even numbers in Fibonacci sequence? [duplicate]

This question already has answers here:
sum of even numbers in Fibonacci sequence
(2 answers)
Closed 8 years ago.
I'm struggling to make this loop work. Is the for/while loop a good way to return the sum of even numbers in a Fibonacci sequence?
function evenFib() {
var x, y, total;
for (var i = 0; i < 10; i++) {
if (i === 0) {
x = 1;
y = 2;
}
while( x %2===0) {
total = x + y;
x = y;
y = total;
}
return(total);
}
};
function fibEven(){
var max = 50;
var cur = 1;
var last = 1;
var evens = 0;
for(var i = 1; i < max; i ++)
{
var tlast = i > 1 ? cur : last;
cur = cur + last;
last = tlast;
if(cur % 2 === 0)
{
evens += cur;
console.log(evens);
}
}
return evens;
}
I'm not even sure how to begin explaining why your attempt is not going to work. So basically we give this a range since fibonacci is infinite. You will start getting insane numbers around 100 iterations. general rule is next number is this number plus last number. use modulus to check if there's a remainder at all. If not, add to the total evens. run this function and see.

Categories