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;
}
Related
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))
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(", ") + "]");
I'm taking the freecodecamp course one of the exercises it's to create a Factorialize function, I know there is several ways to do it just not sure what this one keeps returning 5
function factorialize(num) {
var myMax = num;
var myCounter = 1;
var myTotal = 0;
for (i = 0; i>= myMax; i++) {
num = myCounter * (myCounter + 1);
myCounter++;
}
return num;
}
factorialize(5);
This is a recursive solution of your problem:
function factorialize(num) {
if(num <= 1) {
return num
} else {
return num * factorialize(num-1)
}
}
factorialize(5)
This is the iterative solution:
function factorialize(num) {
var cnt = 1;
for (var i = 1; i <= num ; i++) {
cnt *= i;
}
return cnt;
}
factorialize(5)
with argument 5, it will return the 5! or 120.
To answer your question, why your function is returning 5:
Your function never reaches the inner part of the for-loop because your testing if i is greater than myMax instead of less than.
So you are just returning your input parameter which is five.
But the loop does not calculate the factorial of num, it only multiplies (num+1) with (num+2);
My solution in compliance with convention for empty product
function factorializer(int) {
if (int <= 1) {
return 1;
} else {
return int * factorializer(int - 1);
}
}
Here is another way to solve this challenge and I know it is neither the shortest nor the easiest but it is still a valid way.
function factorialiaze(num){
var myArr = []; //declaring an array.
if(num === 0 || num === 1){
return 1;
}
if (num < 0){ //for negative numbers.
return "N/A";
}
for (var i = 1; i <= num; i++){ // creating an array.
myArr.push(i);
}
// Reducing myArr to a single value via .reduce:
num = myArr.reduce(function(a,b){
return a * b;
});
return num;
}
factorialiaze(5);
Maybe you consider another approach.
This solution features a very short - cut to show what is possible to get with an recursive style and a implicit type conversion:
function f(n) { return +!~-n || n * f(n - 1); }
+ convert to number
! not
~ not bitwise
- negative
function f(n) { return +!~-n || n * f(n - 1); }
var i;
for (i = 1; i < 20; i++) {
console.log(f(i));
}
.as-console-wrapper { max-height: 100% !important; top: 0; }
Try this function
const factorialize = (num) => num === 0 ? 1 : num * factorialize(num-1)
Use it like this:
factorialize(5) // returns 120
Try this :
function factorialize(num) {
var value = 1;
if(num === 1 || num ===0) {
return value;
} else {
for(var i = 1; i<num; i++) {
value *= i;
}
return num * value;
}
}
factorialize(5);
// My solution
const factorialize = num => {
let newNum = 1;
for (let i = 1; i <= num; i++) {
newNum *= i
}
return newNum;
}
I love syntactic sugar, so
let factorialize = num => num <= 1 ? num : num * factorialize(num -1)
factorialize(5)
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
How can I check for matching numbers in this script, stuck here, I need to compare the array of user numbers with the array of lotto numbers and display how many numbers they got correct if any along with their prize value.
function numbers() {
var numbercount = 6;
var maxnumbers = 40;
var ok = 1;
r = new Array(numbercount);
for (var i = 1; i <= numbercount; i++) {
r[i] = Math.round(Math.random() * (maxnumbers - 1)) + 1;
}
for (var i = numbercount; i >= 1; i--) {
for (var j = numbercount; j >= 1; j--) {
if ((i != j) && (r[i] == r[j])) ok = 0;
}
}
if (ok) {
var output = "";
for (var k = 1; k <= numbercount; k++) {
output += r[k] + ", ";
}
document.lotto.results.value = output;
} else numbers();
}
function userNumbers() {
var usersNumbers = new Array(5);
for (var count = 0; count <= 5; count++) {
usersNumbers[count] = window.prompt("Enter your number " + (count + 1) + ": ");
}
document.lotto.usersNumbers.value = usersNumbers;
}
Here is a lotto numbers generator and a scoring system. I'm going to leave it to you to validate the user input.
function lottoGen(){
var lottoNumbers = [];
for(var k = 0; k<6; k++){
var num = Math.floor(Math.random()*41);
if(lottoNumbers.indexOf(num) != -1){
lottoNumbers.push(num);
}
}
return lottoNumbers;
}
function scoreIt(){
var usersNumbers = document.getElementsByName('usersNumbers').item(0);
usersNumbers = String(usersNumbers)
usersNumbers = usersNumbers.split(' ');
var matches = 0;
for(var i = 0; i<6; i++){
if(lottoNumbers.indexOf(usersNumbers[i]) != -1){matches++;}
}
return matches;
}
Hi I'm new to this and trying to learn off my own back so obviously I'm no expert but the code above makes a lot of sense to me, apart from the fact I can't get it to work.. I tried to console.log where it says RETURN so I could see the numbers but it just shows an empty array still. I assumed this was to do with it being outside the loop..
I've tried various ways but the best I get is an array that loops the same number or an array with 6 numbers but some of which are repeated..
function lottoGen(){
var lottoNumbers = [];
for(var k = 0; k<6; k++){
var num = Math.floor(Math.random()*41);
if(lottoNumbers.indexOf(num) != -1){
lottoNumbers.push(num);
}
}
return lottoNumbers;
}
Lotto JS: CODEPEN DEMO >> HERE <<
(function(){
var btn = document.querySelector("button");
var output = document.querySelector("#result");
function getRandom(min, max){
return Math.round(Math.random() * (max - min) + min);
}
function showRandomNUmbers(){
var numbers = [],
random;
for(var i = 0; i < 6; i++){
random = getRandom(1, 49);
while(numbers.indexOf(random) !== -1){
console.log("upps (" + random + ") it is in already.");
random = getRandom(1, 49);
console.log("replaced with: (" + random + ").");
}
numbers.push(random);
}
output.value = numbers.join(", ");
}
btn.onclick = showRandomNUmbers;
})();