little stuck, please help! Trying to write code using the random number generator,initialize an array of size 50, with integer values in the
range 0..49 and compute the frequency of the numbers in the range 10..19. Here's what I have so far:
var array_nums = new Array (50);
var frequency = 0;
for (i=0; i<array_nums.length; i++){
array_nums [i] = Math.floor ((Math.random() * 50));
for (i=0; i<array_nums.length; i++){
if((i>=10) && (i<=19)){
frequency = frequency+ [i];
alert(frequency);
}
}
}
var array_nums = [];
var frequency = 0;
for (i=0; i < 50; i++) {
var randInt = Math.floor(Math.random()*50)
array_nums.push(randInt);
if(randInt >= 10 && randInt <= 19) {
frequency = frequency + 1;
}
}
document.getElementById('results').innerHTML = array_nums + '<br/><br/>frequency: ' + frequency;
<div id="results"></div>
We fill an array with 50 random numbers, then reduce it to an object that has the number of times each element between 10 and 19 occured, with a final "all" element that has the number of times all of the numbers between 10 and 19 occured.
var array_nums = Array.apply(null, Array(50)).map(function() {
return Math.floor(Math.random() * 50);
}).reduce(function (acc, curr) {
if (curr >= 10 && curr <= 19) {
acc[curr] = (acc[curr] || 0) + 1;
acc["all"]++;
}
return acc;
}, {all:0});
document.getElementById("results").innerHTML = JSON.stringify(array_nums);
<div id="results">
Related
How to generate random numbers in specific range and using specific numbers?
Example
given numbers [7,8];
given range [100-900];
output must be one of them 777, 787, 788, 878, 877, 888 etc...
Help me
const randomGenerateNumber = (maxRange:number, minRange:number, numbers:number[]) => {
//...what should i do in there??? Help me? Any Idea?
}
I think you don't want random numbers. It seems that you want a set of numbers based on some rules. Random means something else.
If I understand well your question you want to generate all possible numbers containing only a set of digits from a range of numbers. Is this an accurate description?
If so, this is similar with what you want: Generate random numbers only with specific digits
Edit:
You are right, so you want only one number.
In javascript you could do something like this:
I edited the algorithm to take into account min and max in probably the most lazy way. I didn't take into account cases where numbers can't be generated, it will return undefined.
There are so many ways to do this. Your algorithm can work too and maybe more efficient but it seems to have an issue with 0, it will generate numbers with 0 even if it's not in the digits array.
function randomGenerateNumber(minRange, maxRange, digits){
noTries = 0;
while(noTries++ < 100000)
{
var num = 0;
//get a random number from your range
len = Math.floor(Math.random() * (maxRange - minRange) + minRange);
//get the lenght of that random number
len = len.toString().length;
//generate a number with that length using only your set of digits
while(len--)
{
num = num * 10 + digits[Math.floor(Math.random() * digits.length)];
}
if(num >= minRange && num<= maxRange)
{
return num;
break;
}
}
}
//your testing cases
console.log(randomGenerateNumber(100,900,[7,8]))
console.log(randomGenerateNumber(299,300,[1,2,3,4,5,6,7,8,9]));
i did it. Is there any improvement. Little bit messy.
const getRandomNumber = (min: number, max: number, numbers: number[]): number => {
if (numbers.length === 9) {
return Math.floor(Math.random() * (max - min + 1) + min);
}
let result = '';
//split maxDigits 100 => [1, 0, 0]
const maxDigits = max
.toString()
.split('')
.map(i => parseInt(i, 10));
//split minDigits 100 => [1, 0, 0]
const minDigits = min
.toString()
.split('')
.map(i => parseInt(i, 10));
//length of random number [minDigit, maxDigit] inclusive
const randomDigit = Math.floor(Math.random() * (maxDigits.length - minDigits.length + 1) + minDigits.length);
let alreadyHigh = false;
let alreadyLow = false;
let equal = true;
//4 conditions
//1. minDigits.length === maxDigits.length
//2. randomDigit === minDigits.length
//3. randomDigit === maxDigits.length
//4. randomDigit > minDigits.length && randomDigit < maxDigits.length
for (let i = 0; i < randomDigit; i++) {
const numbersToUse = i === 0 ? numbers : [...numbers, 0];
let availableNumbers = [];
if (minDigits.length === maxDigits.length) {
if (equal) {
for (let k = 0; k < numbersToUse.length; k++) {
if (minDigits[i] > maxDigits[i]) {
if (numbersToUse[k] >= 0 && numbersToUse[k] <= maxDigits[i]) {
availableNumbers.push(numbersToUse[k]);
}
} else if (numbersToUse[k] >= minDigits[i] && numbersToUse[k] <= maxDigits[i]) {
availableNumbers.push(numbersToUse[k]);
} else {
availableNumbers.push(maxDigits[i]);
}
}
} else {
if (!alreadyHigh) {
for (let k = 0; k < numbersToUse.length; k++) {
if (numbersToUse[k] >= minDigits[i]) {
availableNumbers.push(numbersToUse[k]);
}
}
} else {
availableNumbers = numbersToUse;
}
}
} else if (randomDigit === minDigits.length) {
if (!alreadyHigh) {
for (let k = 0; k < numbersToUse.length; k++) {
if (numbersToUse[k] >= minDigits[i]) {
availableNumbers.push(numbersToUse[k]);
}
}
} else {
availableNumbers = numbersToUse;
}
} else if (randomDigit === maxDigits.length) {
if (!alreadyLow) {
for (let k = 0; k < numbersToUse.length; k++) {
if (numbersToUse[k] <= maxDigits[i]) {
availableNumbers.push(numbersToUse[k]);
}
}
} else {
availableNumbers = numbersToUse;
}
} else {
availableNumbers = numbersToUse;
}
availableNumbers = [...new Set(availableNumbers)];
const randomIndex = Math.floor(Math.random() * availableNumbers.length);
result += `${availableNumbers[randomIndex]}`;
alreadyHigh = !alreadyHigh ? availableNumbers[randomIndex] > minDigits[i] : true;
alreadyLow = !alreadyLow ? availableNumbers[randomIndex] < maxDigits[i] : true;
equal = equal ? availableNumbers[randomIndex] === maxDigits[i] : false;
}
return parseInt(result, 10);
};
I'm making a program to receive a positive number and output "yes" if it's equal to its reverse;
otherwise, output "no".
What I've done so far:
HTML
<div class="column1">
<div class="input">
<button onclick="problem()"> Run the program </button>
</div>
<strong><p id="output"> </p></strong>
</div>
JS
function problem() {
var outputObj = document.getElementById("output");
var a = parseInt(prompt("Please enter a number: ", ""));
outputObj.innerHTML = "number: " + a + "<br><br>";
var reverse = 0;
while (a > 0){
num = a % 10; // the last digit
reverse = (reverse *10) + num; // calculating the reverse
a = Math.floor(a / 10); // go to next digit
}
if ( reverse == a){
outputObj.innerHTML = "yes";
}
else {
outputObj.innerHTML = "no";
}
outputObj.innerHTML = outputObj.innerHTML + "<br><br>" + "program ended";
document.getElementsByTagName("button")[0].setAttribute("disabled","true");
}
function isPalindrome(number){
return +number.toString().split("").reverse().join("") === number
}
Art for art
function palindrom(x)
{
let len = Math.floor(Math.log(x)/Math.log(10) +1);
while(len > 0) {
let last = Math.abs(x - Math.floor(x/10)*10);
let first = Math.floor(x / Math.pow(10, len -1));
if(first != last){
return false;
}
x -= Math.pow(10, len-1) * first ;
x = Math.floor(x/10);
len -= 2;
}
return true;
}
You should search for plaindromic numbers. For example the following code:
const isPalindrome = x => {
if (x < 0) return false
let reversed = 0, y = x
while (y > 0) {
const lastDigit = y % 10
reversed = (reversed * 10) + lastDigit
y = (y / 10) | 0
}
return x === reversed
}
const isPalindrome = num => {
const len = Math.floor(Math.log10(num));
let sum = 0;
for(let k = 0; k <= len; k++) {
sum += (Math.floor(num / 10 ** k) % 10) * 10 ** (len - k);
}
return sum === num;
}
console.log(isPalindrome(12321));
How to create the random number to assign in java script array with following condition.
need to create random number with (1-28).
Number allowed to repeat 2 times. (EX: 1,3,5,4,5). .
Simple solution for adding a number to an array based on your criteria:
function addNumberToArray(arr){
const minValue = 1;
const maxValue = 28;
if(arr.length==maxValue*2){ //no possible numbers left
return;
}
function getRandomArbitrary(min, max) {
return Math.floor(Math.random() * (max - min) + min);
}
function isValueInArrayLessThenTwoTimes(value, arr){
var occurrences = 0;
for(var i=0; i<arr.length; i++){
if(arr[i]===value){
occurrences++;
}
}
return occurrences<2;
}
var newValue;
do {
newValue = getRandomArbitrary(minValue,maxValue);
} while(!isValueInArrayLessThenTwoTimes(newValue, arr));
arr.push(newValue);
}
A shorter and faster solution:
min=1;
max=28;
nums= new Array();
for(i=1;nums.length<28;i++){
a = Math.round(Math.random()*(max-min+1)+min);
if(nums.indexOf(a)==-1 || nums.indexOf(a)==nums.length-nums.reverse().indexOf(a)-1){
if(nums.indexOf(a)>-1){
nums.reverse();
}
nums.push(a);
}
}
console.log(nums);
https://jsfiddle.net/znge41fn/1/
var array = [];
for (var i = 0; i < 28; i++) {
var randomNumberBetween1and28 = Math.floor(Math.random() * (28 - 1) + 1);
while (getCount(array, randomNumberBetween1and28) > 2) {
randomNumberBetween1and28 = Math.floor(Math.random() * (28 - 1) + 1);
}
array.push(randomNumberBetween1and28);
}
function getCount(arr, value) {
var count = 1;
for (var i = 0; i < arr.length; i++) {
if (value == arr[i]) count++;
}
return count;
}
This is a code that creates a random array and tells you which number in that array is the biggest:
var game = function fucntion(length, limit) {
length = length ? length : 10;
limit = limit ? limit : 1000;
var arr = [];
var max = -1;
for (var i = 0; i < length; i++) {
var r = Math.ceil(Math.random() * limit);
if (r > max) max = r;
arr.push(r);
}
return 'The biggest number in the array: ' + JSON.stringify(arr) + ' is ' + max + '-';
};
How do I make JS add up all the numbers in the array and tell me the sum?
Thanks in advance!
var game = function fucntion(length, limit) {
length = length ? length : 10;
limit = limit ? limit : 1000;
var arr = [];
var max = -1;
var sum = 0;
for (var i = 0; i < length; i++) {
var r = Math.ceil(Math.random() * limit);
if (r > max)
max = r;
sum = sum + r;
arr.push(r);
}
return 'The biggest number in the array: ' + JSON.stringify(arr) + ' is ' + max + ' and the sum is: ' + sum;
};
You could use reduce like so :
sum = array.reduce(function(a, b) { return a + b; }, 0);
This method explores the array from left to right, taking two elements and reducing them to one element using the provided callback, over and over again, until the end of the array is reached
PS : Try better formatting your post, and do some online research before posting a question. I found out the solution only by typing "js sum array" on internet.
I'm prompting the user to enter a number between 50 and 100.
(Default value for the prompt is 100.)
The input, minus one, is then displayed on the screen followed by spaces.
Fore example, if user enters 60, this is what I want to be displayed:
01 02 03 04
05 06 07 08
...
53 54 55 56
57 58 59
So far I'v done the following, but I can't figure out the problem or what to do next:
num = Number(prompt("Please enter a number between 50 and 100"));
var arr= new Array(parseInt(arrayLength));
for (var i = 0; i < array.length; i++) {
document.getElementById("myDiv").innerHTML = arr[i];
}
You can just parseInt on the return value from the "prompt", and then you can create an array that is mappable. Once that is done, you can just join the entire array with a space, which will give you 1 2 3 ... etc.
If you are looking for the most basic format where there are no line-breaks, this is a simple version:
var num = parseInt(prompt('Please enter a number between 50 and 100')) || 100;
var arr = Array.apply(null, Array(num - 1))
.map(function(x, i) {
return i + 1;
});
document.getElementById("myDiv").innerHTML = arr.join(' ');
<div id="myDiv"></div>
Otherwise, if you are looking for the more complex formatting and with the line breaks, here is the same concept modified a little bit:
var num = parseInt(prompt('Please enter a number between 50 and 100')) || 100;
var arr = Array.apply(null, Array(num - 1))
.map(function(x, i) {
var actual = i + 1;
if (actual < 10) {
actual = '0' + actual;
}
if (i % 4 === 3) {
actual += '<br>';
}
return actual;
});
document.getElementById("myDiv").innerHTML = arr.join(' ');
<div id="myDiv"></div>
You can concatenate a string with the numbers and then set the innerHtml of your div to that string:
num = Number(prompt("Please enter a number between 50 and 100"));
var result = "";
for (var i = 1; i < num; i++) {
result += i + " ";
}
document.getElementById("myDiv").innerHTML = result;
If you want the numbers 1-9 to be displayed like 01 02 03... you can do so with this version:
num = Number(prompt("Please enter a number between 50 and 100"));
var result = "";
for (var i = 1; i < num; i++) {
if(i < 10){
result += "0" + i + " ";
}else{
result += i + " ";
}
}
document.getElementById("myDiv").innerHTML = result;
See this Fiddle as reference.
This is how I would do it. I don't know why you need the array?
Just loop from start to end and add spaces after each number (while padding it) and add line breaks after every 4th number.
var num = Number(prompt("Please enter a number between 50 and 100")) || 100;
document.getElementById("myDiv").innerHTML = generateText(num, 4);
function generateText(n, cols) {
var result = '';
for (var i = 1; i < n; i++) {
result += pad(i, 2, '0') + ' ';
if (i % cols === 0) {
result += '<br />';
}
}
return result;
}
function pad(val, n, ch) {
val = '' + val;
while (val.length < n) {
val = ch + val;
}
return val;
}
<div id="myDiv"></div>
Since we are going for brevity here. /s
Here is some "code golf" to scratch your itch :)
var num = Number(prompt("Please enter a number between 50 and 100")) || 100;
num = num < 50 ? 50 : (num > 100 ? 100 : num);
document.getElementById('myDiv').innerHTML = Array
.apply(null, Array(num - 1))
.map(function(x, i) { return (i < 9 ? '0' : '') + (i + 1); })
.reduce(function(s, x, i) { return s + x + (i % 4 === 3 ? '<br />' : ' '); }, '');
<div id="myDiv"></div>