JavaScript arr.indexOf() always gives -1 - javascript

I have a random number generator and a pick of one of the numbers inside. I'm trying to get the position of the number, So I used index.of() but it always shows '-1'.
I thought this would be the most direct way of finding the location of a particular number within an array. Am I wrong?
const shuffle = arr => {
let a = arr.slice(0); // take a copy
for (let i = a.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[a[i], a[j]] = [a[j], a[i]];
}
return a;
};
var arr = [];
var UserNumber = 10;
var BallNumber = 4;
var RandomNumber = Math.floor(Math.random() * UserNumber) + 1;
while (arr.length < BallNumber) {
var r = Math.floor(Math.random() * UserNumber) + 1;
if (arr.indexOf(r) === -1) {
arr.push(r);
}
console.log(r);
}
var selected = shuffle(arr).slice(0, 1);
document.write("<p> The random Number to choose is " + selected + "</p>");
document.write("<p> The Random Numbers are " + arr + "</p>");
document.write("<p> The position is " + arr.indexOf(selected) + "</p>");

Array.prototype.slice returns an array:
var selected = shuffle(arr).slice(0, 1)
Here, selected is now an array with a single element. But objects are never === to anything besides themselves, and since indexOf uses === to determine indicies, it'll always return -1.
Extract the first value from the shuffled array instead:
var selected = shuffle(arr)[0]
const shuffle = arr => {
let a = arr.slice(0); // take a copy
for (let i = a.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[a[i], a[j]] = [a[j], a[i]];
}
return a;
};
var arr = [];
var UserNumber = 10;
var BallNumber = 4;
var RandomNumber = Math.floor(Math.random() * UserNumber) + 1;
while (arr.length < BallNumber) {
var r = Math.floor(Math.random() * UserNumber) + 1;
if (arr.indexOf(r) === -1) {
arr.push(r);
}
}
var selected = shuffle(arr).slice(0, 1)[0];
document.write("<p> The random Number to choose is " + selected + "</p>");
document.write("<p> The Random Numbers are " + arr + "</p>");
document.write("<p> The position is " + arr.indexOf(selected) + "</p>");

slice returns an array, so you'll have to grab the first element, something like:
const shuffle = (arr) => {
let a = arr.slice(0); // take a copy
for (let i = a.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[a[i], a[j]] = [a[j], a[i]];
}
return a;
};
var arr = [];
var UserNumber = 10;
var BallNumber = 4;
var RandomNumber = Math.floor(Math.random() * UserNumber) + 1;
while (arr.length < BallNumber) {
var r = Math.floor(Math.random() * UserNumber) + 1;
if (arr.indexOf(r) === -1) {
arr.push(r);
}
console.log(r);
}
var selected = shuffle(arr).slice(0, 1);
document.write("<p> The random Number to choose is " + selected + "</p>");
document.write("<p> The Random Numbers are " + arr + "</p>");
document.write("<p> The position is " + arr.indexOf(selected[0]) + "</p>");

Related

How to generate unique random numbers

I’m trying to generate 5 unique random numbers between two numbers. The sixth number is a random number between another set of numbers but it doesn’t have to be unique. I tried to ensure the uniqueness of each number by placing the first randomly generated number in an array.
Then each subsequent randomly generated number is checked against the numbers in this array. Any generated number matching a number in the array will be discarded and a new one is generated until one that doesn’t match any in the array is is found. My code doesn’t work because occasionally it produces duplicates.
How is this fixed?
https://jsfiddle.net/L3h0rf5q/
var btnGen = document.getElementById('generate');
var fiveNum = document.getElementById('fiveNums');
var lastNum = document.getElementById('lastNum');
btnGen.addEventListener('click', function () {
let ranNum;
let firstFive = "";
let pb = "";
let oldNum;
ranNum = GenerateNumbers();
ranNum.sort(
(a, b) => {
if (a < b) {
return -1;
}
if (a > b) {
return 1;
}
return 0;
}
);
for(let i=0; i<ranNum.length; i++){
if(i<ranNum.length - 1){
if(ranNum[i].toString().length<2){
firstFive += "0" + ranNum[i].toString() + " " + " " + " " + " " + " " + " "
}else{
firstFive += ranNum[i].toString() + " " + " " + " " + " " + " " + " "
}
}else{
if(ranNum[i].toString().length<2){
pb = "0" + ranNum[i].toString();
}else {
pb = ranNum[i].toString();
}
}
fiveNum.innerHTML = firstFive;
lastNum.innerHTML = pb;
}
});
function GenerateNumbers() {
let randomNums = [];
let selectedNums = [];
let newNum = undefined;
for (let i = 0; i < 6; i++) {
if (i == 0) {
newNum = Math.floor(Math.random() * 75) + 1
randomNums[i] = newNum;
selectedNums.push(newNum);
}
if (i >0 && i < 5){
while (selectedNums.includes(newNum)) {
newNum = Math.floor(Math.random() * 75) + 1
}
randomNums[i] = newNum;
//add to an array
selectedNums.push(newNum);
}
if (i == 5) {
randomNums[i] = Math.floor(Math.random() * 42) + 1
}
}
return randomNums;
}
<div style="margin-left:20%; width:500px; font-weight:bold; font-size:30px;">
<button id="generate" style="margin-left:36%">Generate Numbers</button>
<br><br>
<div>
<label style="margin-left:20%">Generate Numbers</label>
<br>
<div style="background-color:black">
<span id="fiveNums" style="margin-left: 10%; width:80%; color:blue;"></span>
<span id="lastNum" style="color:blue;"></span>
</div>
</div>
the approach is to make an array with all possible values, shuffle it, and then grab 5 of them (and for that extra value you want, just calculate it separately). you can do this with plain javascript if you want:
function shuffle(arr) {
let i = arr.length;
while(i != 0) {
let j = Math.floor(Math.random() * i--);
[arr[i], arr[j]] = [arr[j], arr[i]];
}
return arr;
}
//fill arr with all possible values
var arr = [];
for(var i = 50; i <= 100; i++) arr.push(i);
//shuffle
shuffle(arr);
//grab 5
console.log(arr.slice(-5));
//and the extra one
console.log(Math.floor(Math.random() * 76) + 75);
But doing it with rando.js is a lot nicer:
console.log(randoSequence(50, 100).slice(-5));//first five
console.log(rando(75, 150));//the other one
<script src="https://randojs.com/2.0.0.js"></script>

How to find the average in javascript?

So I'm fairly new to JavaScript but I cannot seem to find the average in my code. I want to understand why my average is not working. Any help you guys?
function getEvenOdd() {
var oddSum = 0;
var evenSum = 0;
var num = 0;
var evenAvg = 0;
var oddAvg = 0;
while (true) {
num = parseInt(prompt("Enter a number(-1 to exit)"));
if (num == -1) {
break;
}
if (num % 2 == 0) {
evenSum += num;
} else {
oddSum += num;
}
evenAvg = evenSum / num;
oddAvg = oddSum / num;
}
alert("Sum of all even numbers is: " + evenSum);
alert("Sum of all odd numbers is: " + oddSum);
alert("Average of all even numbers is : " + evenAvg);
alert("Average of all odd numbers is: " + oddAvg);
}
On your code, to calculate the oddAvg and evenAvg, you have divided evenSum and oddSum by num variable (which is input from prompt).
And as you know, average = total sum / total count, so it's not right to divide the sum by the input number variable.
Instead of that, you need to calculate the count of odd and even numbers and divide the even and odd sum by the even and odd number counts as follows.
function getEvenOdd() {
var oddSum = 0;
var evenSum = 0;
var num = 0;
var evenAvg = 0;
var oddAvg = 0;
var evenCount = 0;
var oddCount = 0;
while (true) {
num = parseInt(prompt("Enter a number(-1 to exit)"));
if (num == -1) {
break;
}
if (num % 2 == 0) {
evenSum += num;
evenCount ++;
} else {
oddSum += num;
oddCount ++;
}
}
evenAvg = evenSum / evenCount;
oddAvg = oddSum / oddCount;
alert("Sum of all even numbers is: " + evenSum);
alert("Sum of all odd numbers is: " + oddSum);
alert("Average of all even numbers is : " + evenAvg);
alert("Average of all odd numbers is: " + oddAvg);
}
getEvenOdd();
These operations are dividing the evenSum or oddSum by the last input num.
evenAvg = evenSum / num;
oddAvg = oddSum / num;
You should divide the sum by the number of even or odd inputs.
Instead of evenSum / num use evenSum/Count of Numbers entered.
How about this solution? It is aiming to store odd and even numbers into oddList and evenList.
function getEvenOdd() {
var evenAvg = 0;
var oddAvg = 0;
var oddList = [];
var evenList = [];
var num = 0;
while (true) {
num = parseInt(prompt("Enter a number(-1 to exit)"));
if (num == -1) {
break;
}
if (num % 2 == 0) {
evenList.push(parseInt(num));
} else {
oddList.push(parseInt(num));
}
evenAvg = evenList.reduce((p, c) => p + c, 0) / evenList.length;
oddAvg = oddList.reduce((p, c) => p + c, 0) / oddList.length;
}
alert("Sum of all even numbers is: " + evenList.length);
alert("Sum of all odd numbers is: " + oddList.length);
alert("Average of all even numbers is : " + evenAvg);
alert("Average of all odd numbers is: " + oddAvg);
}
getEvenOdd();

Java script random number with allowed to 2 repeat value

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

while loop. can't hardcode the while statement

function start() {
var output = "";
var index = 0;
var total = 0;
var average = 0;
var arr = []
while(arr.length < 12){
var randomnumber = Math.ceil(Math.random()*20)
if(arr.indexOf(randomnumber) > -1) continue;
arr[arr.length] = randomnumber;
}
output = output + "List of all values in the array: " + arr;
output = output + "<br/>" + "Total number of values in the array: " + arr.length + "<br/>";
while(index < arr.length) {
total = total + arr[index];
index++;
}
average = total / index;
output = output + "Total of all values: " + total + "<br/>";
output = output + "Average of all values: " + average;
document.getElementById("msg").innerHTML = output;
}
I was told I am not allowed to hardcode the statement, how to I go about changing the 'while' statement so I am not hardcoding?
Probably they mean
var arr = new Array(12);
var randIndex=0;
while(randIndex < arr.length){
var randomnumber = Math.ceil(Math.random()*20)
if(arr.indexOf(randomnumber) > -1) continue;
arr[randIndex] = randomnumber;
randIndex++;
}
Looks like a school assignment. If you are not supposed to hardcode the number of elements in array (currently 12) then you will need to get that number from user in some way. Or alternatively use a random number as shown below.
Note: there is a catch if you let the user specify the number of elements. I'll keep it for you to explore and fix.
function start(len) {
var output = "";
var index = 0;
var total = 0;
var average = 0;
var arr = []
while(arr.length < len){
var randomnumber = Math.ceil(Math.random()*20)
if(arr.indexOf(randomnumber) > -1) continue;
arr[arr.length] = randomnumber;
}
output = output + "List of all values in the array: " + arr;
output = output + "<br/>" + "Total number of values in the array: " + arr.length + "<br/>";
while(index < arr.length) {
total = total + arr[index];
index++;
}
average = total / index;
output = output + "Total of all values: " + total + "<br/>";
output = output + "Average of all values: " + average;
document.getElementById("msg").innerHTML = output;
}
// start(10); // you can get the number of elements in array from user and pass it here. I'm passing hardcoded 10 for now.
start(Math.ceil(Math.random()*20)); // alternatively passing a random number
<div id='msg'>
</div>

Javascript Loto Game

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

Categories

Resources