I want get array with random unique figures.
I make cycle for
var row = [];
var count = 10;
function getRandomArbitary(min, max) {
return Math.random() * (max - min) + min;
}
function searchRandom() {
var rdm = Math.floor(getRandomArbitary(1, 20));
for (var i = 0; i < row.length; i++) {
if (rdm == row[i]) {
searchRandom();
}
}
row.push(rdm);
}
And then if I want 10 figures in array I make next cycle
for (var i = 0; i < count; i++) {
searchRandom();
}
console.log(row);
But it doesn't work (
Wouldn't it be easier to just make the function take the options as arguments and return the array ?
function randomArray(count, min, max) {
if (count > (max - min)) return;
var arr = [], t;
while (count) {
t = Math.floor(Math.random() * (max - min) + min);
if (arr.indexOf(t) === -1) {
arr.push(t);
count--;
}
}
return arr;
}
console.log(randomArray(10, 1, 20));
I think and i havent ran it on my system
but this should work
function searchRandom() {
var rdm = Math.floor(getRandomArbitary(1, 20));
for (var i = 0; i < row.length; i++) {
if (rdm == row[i]) {
searchRandom();
return;
}
}
row.push(rdm);
}
Notice the return statement after the nested searchRandom()
This will stop you from getting into incorrect cases for example lets say till now the row has [1,2]. and the next random no is 1;
in that case why you are recursively calling the search method??
you can just loop from 1 to len (or 0 to len-1), and wait until you generated the random number that is not present simply by a while loop. here is an example
var generateRandomArray = function(len, min, max) {
if(len> (max-min)) {return;}
var array = [],
getRandomArbitary = function(min, max) {
return Math.floor(Math.random() * (max - min) + min);
},
idx;
for (idx = 0; idx < len; idx++) {
var num;
while (array.includes(num = getRandomArbitary(min,max))) {}
array.push(num)
}
return array;
}
console.log('Random Array of 5 element from 10 to 20: ', generateRandomArray(5, 10,20))
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 need array with random non repeating values. I find solving with includes() but i want make without it.
CODE
function rand(min, max){
return Math.round( Math.random() * (max - min) + min);
}
function getRandArray(n, min, max) {
//n - array length
var randArr = [];
randArr[0] = rand(min, max);
for (var i = 0; i < n; i++) {
var randNum = rand(min, max);
for (var j = 0; j < randArr.length; j++){
if (randNum != randArr[j])
randArr[i] = randNum;
else
randNum = rand(min, max);
}
}
return randArr;
}
You can leverage the power of the ES6 Set to do this very easily. Since you are looking for an array output, you can simply use Array.from and pass in the set to return from the function. Here's what it would look like:
function rand(min, max){
return Math.round( Math.random() * (max - min) + min);
}
function getRandArr(n, min, max) {
var set = new Set();
// ensure that the number of unique numbers they want is possible
var maxNumsInArr = Math.min(n, max-min+1);
while(set.size < maxNumsInArr) {
set.add(rand(min, max));
}
return Array.from(set);
}
console.log(getRandArr(10, 0, 10));
console.log(getRandArr(5, 100, 399));
console.log(getRandArr(5, 0, 2)); // only 3 possible unique values, so length will be 3
If ES6 is not an option you can convert the random numbers into String keys for an object and take advantage of the fact that an object will not allow duplicate properties like this:
function rand(min, max){
return Math.round( Math.random() * (max - min) + min);
}
function getRandArr(n, min, max) {
if (n > (max - min + 1)) {
throw "Cannot create array of size " + n;
}
var res = {};
while (Object.keys(res).length < n) {
var r = rand(min, max);
res[r] = true;
}
var array = Object.keys(res);
return array;
}
console.log(getRandArr(100, 0, 10000));
You could always convert the array of Strings back to numbers with a single pass after you have the results.
Adding a property to an object will use a hash of the property name so you get O(1) time for checking if the number is unique.
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;
}
I am trying to write a function which produces four unequal random numbers in a given range, but the function is currently failing at the while (selection[i] in selection.slice().splice(i) line. This line should check whether the current (i'th) value is shared by any of the other random values but at the moment it seems to do nothing - perhaps I have used in incorrectly? Any help would be appreciated.
function contains(a, obj) {
for (var i = 0; i < a.length; i++) {
if (a[i] === obj) {
return true;
}
}
return false;
}
selected=[];
function randomSelection() {
var notselected=[];
for (var i=0; i<25; i++) {
if(!contains(selected, i)) {
notselected.push(i);
}
}
var selection=[notselected[Math.floor(Math.random() * notselected.length)],
notselected[Math.floor(Math.random() * notselected.length)],
notselected[Math.floor(Math.random() * notselected.length)],
notselected[Math.floor(Math.random() * notselected.length)]];
for (var i=0; i<selection.length; i++) {
while (selection[i] in selection.slice().splice(i)) {
alert('Hello!')
selection[i] = notselected[Math.floor(Math.random() * notselected.length)];
}
}
for (var i=0; i<selection.length; i++) {
selected.pop(selection[i]);
}
}
You can obtain a random value between two numbers using the following method
function getRandomArbitrary(min, max) {
return Math.floor(Math.random() * (max - min)) + min;
}
If the value needs to be an integer you can use the following method:
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min)) + min;
}
So, supposing that you need 4 different random integer values you could do something like that
var randoms = [];
while(randoms.length < 4) {
var random = getRandomInt(0, 25);
if(randoms.indexOf(random) === -1) {
randoms.push(random);
}
}
To randomly shuffle a set of objects (numbers in this case)
var values = [0,1,2,3,4,5,6];
function shuffle(arr){
var temp = [...arr];
arr.length = 0;
while(temp.length > 0){
arr.push(temp.splice(Math.floor(Math.random() * temp.length),1)[0]);
}
return arr;
}
console.log("pre shuffle : [" + values.join(", ") + "]");
shuffle(values);
console.log("post shuffle : [" + values.join(", ") + "]");
How would I use a function that returns the sum of a given array while getting the sum of the even numbers and sum the odd numbers? I'm not understanding how that is done. Can someone please explain a little more in depth?
Here is my entire code:
function main()
{
var evenNum = 0;
//need a total Even count
var oddNum = 0;
//need a total Odd count
var counter = 1;
var num = 0;
function isOdd(x) {
if ((num % 2) == 0)
{
return false;
}
else
{
return true;
}
}
function isEven(x) {
if ((num % 2) == 0)
{
return false;
}
else
{
return true;
}
}
for (counter = 1; counter <= 100; counter++)
{
num = Math.floor(1 + Math.random() * (100-1));
var total = 0;
for(var j = 0; j < length; j++)
total += a[j];//Array?
console.log(num);
console.log("The count of even number is " + evenNum);
console.log("The count of odd number is " + oddNum);
return 0;
}
main()
If I understand your question correctly, you need a function that returns two values, one for the sum of even numbers and one for the sum of odd numbers. It's not clear if you use even/odd referring to the index of the array or the values in array.
In both cases you can return an object that contains both values:
function sum(array) {
var evenSum = 0;
var oddSum = 0;
...calculate...
var res = {};
res.evenSum = evenSum;
res.oddSum = oddSum;
return res;
}
Hope this will help