I've got a assignment to make function that gives you a sorted array with 6 random numbers from 1 to 45. None of the array values should equal to one another.
I thought about a solution that would work in Java but the JavaScript console logs I get are pretty confusing. Could anyone help me out?
"use strict";
var numbers = [];
for(var x = 1; x <46;x++){
numbers.push(x);
}
function LottoTipp(){
var result = [];
for(var i = 0; i <6; i++){
var randomNum = Math.round(Math.random()* 45);
var pushed = numbers[randomNum];
result.push(pushed);
numbers.splice(randomNum)
}
return console.log(result) + console.log(numbers);
}
LottoTipp();
the console logs
[ 34, 7, undefined, undefined, undefined, undefined ]
[ 1, 2, 3, 4, 5, 6 ]
There were three problems:
If you want to remove one item of an array you have to splice it by the items index and give a deletecount.
In your case: numbers.splice(randomNum, 1);
You have to use Math.floor instead of Math.round, because Math.floor always down to the nearest integerer, while Math.round searches for the nearest integer wich could be higher than numbers.length.
After removing one item the length of the array has been changed. So you have to multiply by numbers.lenght instead of 45.
In your case: var randomNum = Math.floor(Math.random()* numbers.length);
"use strict";
var numbers = [];
for(var x = 1; x < 46; x++){
numbers.push(x);
}
function LottoTipp(){
var result = [];
for(var i = 0; i < 6; i++){
var randomNum = Math.floor(Math.random()* numbers.length);
var pushed = numbers[randomNum];
result.push(pushed);
numbers.splice(randomNum, 1);
}
return console.log(result) + console.log(numbers);
}
LottoTipp();
If you only want an array with random unique numbers I would suggest doing it like this:
<script>
var array = [];
for(i = 0; i < 6; i++) {
var number = Math.round(Math.random() *45);
if(array.indexOf(number) == -1) { //if number is not already inside the array
array.push(number);
} else { //if number is inside the array, put back the counter by one
i--;
}
}
console.log(array);
</script>
There is no issue with the console statement the issue is that you are modifying the numbers array in your for loop. As you are picking the random number between 1-45 in this statement:-
var randomNum = Math.round(Math.random()* 45);
and you expect that value would be present in the numbers array at that random index. However you are using array.splice() and providing only first parameter to the function. The first parameter is the start index from which you want to start deleting elements, find syntax here. This results in deleting all the next values in the array.Therefore if you pick a random number number say.. 40, value at numbers[40] is undefined as you have deleted contents of the array.
if you want to generate unique set of numbers follow this post.
hope it helps!
Just add the number in the result if it is unique otherwise take out a new number and then sort it. Here is an implementation:
let result = []
while(result.length < 6) {
let num = Math.round(Math.random() * 45);
if(!result.includes(num)) {
result.push(num);
}
}
result.sort((a,b) => {
return parseInt(a) - parseInt(b);
});
console.log(result);
Related
So I need to get the highest 3 values from an array, though I don't know how many values I need to check since that number will change periodically, I tried running this loop but it doesn't work.
numbers = new array();
numbers = (6,34,6623,22,754,2677,12)
var num1 = 0
var num2 = 0
var num3 = 0
for (var i=0; i<numbers.length;i++) {
if num1<numbers[i] {
num1 = numbers[i]
} else if num2<numbers[i] {
num2 = numbers[i]
} else if num3<numbers[i] {
num3 = numbers[i]
}
}
All of the other answers propose the correct and fast way to do this, i.e. to sort the array in descending order and take the first three elements.
If you're interested why your code did not work: The problem is that you need to keep track of each of the last found max values if a new one is found. You need to change your code to something like this:
const numbers = [6, 34, 6623, 22, 754, 2677, 12]
let max = 0;
let oneLowerToMax = 0;
let twoLowerToMax = 0;
for (let i = 0; i < numbers.length; i++) {
if (numbers[i] > max) {
twoLowerToMax = oneLowerToMax;
oneLowerToMax = max;
max = numbers[i];
}else if(numbers[i] > oneLowerToMax) {
twoLowerToMax = oneLowerToMax;
oneLowerToMax = numbers[i];
}else if(numbers[i] > twoLowerToMax) {
twoLowerToMax = numbers[i];
}
}
console.log(max, oneLowerToMax, twoLowerToMax) // prints 6623, 2677, 754
Sort the array in descending order and then get all 3 element by its index:
let numbers = new Array(6,34,6623,22,754,2677,12);
numbers.sort(function(a, b){return b-a});
console.log(numbers[0], numbers[1], numbers[2]);
you can sort array
var numbers = [1,65,8,98,689,12,33,2,3,789];
var topValues = [... numbers].sort((a,b) => b-a).slice(0,3);
there is a simpler way you can achieve this.
first, run a sort() on your array, then pick the highest ones.
const myArray = [7,4,99,10,55,1];
console.log(myArray.sort((a,b)=>b-a).slice(0, 3)) // [99, 55, 10]
Simply sort your array in descending order, then slice the first three values.
Note: .sort().reverse() is the speediest approach for sorting in descending order. See https://stackoverflow.com/a/52030227/129086
function getTopThree(arr) {
// spread avoids modifying the original array
return [...arr].sort().reverse().slice(0, 3);
}
getTopThree(numbers);
Whenever your numbers array is updated or changed, call getTopThree(numbers) again.
What is the simplest way to get 50 random unique elements from an array of 1000 elements ?
text = new Array();
for(i=0;i<1000;i++){ text[i]=i; } //array populated
// now I need to get 50 random unique elements from this array.
The obvious (to me) way is to shuffle the array, then take the first fifty elements. This question has a good way to shuffle an array, and you can then slice the first fifty elements. This guarantees the elements will be unique.
So, using the function there:
fisherYates(text);
text = text.slice(0, 50);
Good algorithms explained in this topic (in C but you can easily to do same in JS)
Look into the Fisher-Yates algorithm, I think this will work for you.
This assumes you mean random indexes and not indexes with unique values.
One way is to copy the array and prune off the ones you use:
function getRandomIndexes( arr, cnt){
var randomArr = [],
arrCopy = arr.slice(),
i,
randomNum ;
for (i=0;i<arrCopy.length;i++) {
randomNum = Math.floor( arrCopy.length * Math.random());
randomArr = randomArr.concat( arrCopy.splice(randomNum ,1) );
}
return randomArr;
}
var myNums = [], i, randSet;
for (i=0;i<10;i++){
myNums.push(i);
}
randSet = getRandomIndexes(myNums, 5);
Another way is to keep track of the indexes you use and keep looking until you find one you did not use. I find the while loop to be scary, and personally would not use this solution if random indexes needed approaches close to the array length.
function getRandomIndexes( arr, cnt){
var randomArr = [],
usedNums = {},
x;
while (randomArr.length<cnt) {
while (usedNums[x]===true || x===undefined) {
x = Math.floor( Math.random() * arr.length);
}
usedNums[x] = true;
randomArr.push( arr[x] );
}
return randomArr;
}
var myNums = [], i, randSet;
for (i=0;i<10;i++){
myNums.push(i);
}
randSet = getRandomIndexes(myNums, 5);
In case you meant unique values:
Demo
var old_arr = [0,1,2,3,4,5,6,7,8,9], new_array = [];
for (var i = 0; i < 5; i++) {
var rand_elem = old_arr[Math.floor(Math.random() * old_arr.length)];
if (arrIndex(old_arr[rand_elem], new_array) == -1) {
new_array.push(rand_elem);
} else {
i--;
}
}
function arrIndex(to_find, arr) {//own function for IE support
if (Array.prototype.indexOf) {
return arr.indexOf(to_find);
}
for (var i = 0, len = arr.length; i < len; i++) {
if (i in arr && arr[i] === to_find) {
return i;
}
}
return -1;
}
In case you meant unique indexs:
Generate random indexes and store the indexes in an array and make checks to prevent duplicates
Start removing the elements of the array after you get them, (you might have problems if you cache the length, so don't)
var arr = [];
while(arr.length < 51){
var ind = Math.floor(Math.random()*1000);
if(!(ind in arr))
arr.push(ind)
}
You'll have 50 random unique numbers in the array arr, which you could use as index
EDIT:
As #ajax333221 mentioned, the previous code doesn't do to get unique elements from the array, in case it contains duplicates. So this is the fix:
var result_arr = [];
while(result_arr.length < 51){
var ind = Math.floor(Math.random()*1000);
if(text[ind] && !(text[ind] in result_arr))
result_arr.push(text[ind]);
}
Being 'text' the array populated with 1000 values
Math.random() * 1000;
Generate 50 random numbers and use them as the position in the array.
Just started learning javascript.
Input could be something like.
1, 5, 2, 7
and my task is to figure out how many numbers is missing between the lowest number and highest number.
var sorted = statues.sort();
var ticker = 0;
var plusser = sorted[0] + 1;
var plusser1 = sorted[1] + 1;
var plusser2 = sorted[2] + 1;
var plusser3 = sorted[3] + 1;
if(sorted[1] != plusser) {
ticker++
}
if(sorted[2] != plusser1) {
ticker ++;
}
if(sorted[3] != plusser2) {
ticker ++;
}
if(sorted[4] != plusser3) {
ticker ++;
}
this works great if there only is 4 numbers of input however, that ain't always the case and i am sure this can be coded cleaner if you use some sort of loop. Can you guys help me?
Find the max and min number and loop through array and check if a number is not part of array.
var arr = [1, 5, 2, 7];
var numberMissing = 0;
for(var i = Math.min.apply(Math, arr) + 1 ; i < Math.max.apply(Math, arr); ++i){
if(arr.indexOf(i) === -1){
console.log(i);
++numberMissing;
}
}
console.log("Missing Number : " + numberMissing);
task is to figure out how many numbers is missing between the lowest number and highest number
Sort the numbers : This will give the smallest number and largest number.
Subtract largest number and smallest number : This will give total numbers that could be included that range. Lets say this is N
Subtract Array Length with N : This will give number of missing number in the given array.
Since the question is to count and not to list all the missing numbers, we can take this approach. Following is the code example.
var input = [1,5,2,7];
var sortedInput = input.sort(); // this will work only for single digit array.
var firstNum = sortedInput[0],
lastNum = sortedInput[sortedInput.length-1],
numbersInRange = lastNum - firstNum +2; // +2 to include the numbers that are the range
var missingNumbers = numbersInRange - input.length;
console.log(missingNumbers)
If the array contains unique numbers (ie - 5 can't appear twice), you can use simple math:
var statues = [1, 5, 2, 7];
var result =
Math.max.apply(Math, statues) - Math.min.apply(Math, statues) + 1 // the amount of items that should be in the array
-
statues.length; // the current amount of items
console.log(result);
If you want the numbers as well, create a map of the existing numbers, and then create an array, that contain all numbers that don't exist in the initial array:
var statues = [1, 5, 2, 7];
function getMissingNumbers(arr) {
var result = [];
var map = arr.reduce(function(map, n) { // create a map of existing numbers
map[n] = true;
return map
}, {});
var max = Math.max.apply(Math, arr); // find the max
var min = Math.min.apply(Math, arr); // find the min
for(var i = min; i < max; i++) { // run from min to max
map[i] || result.push(i); // add only numbers that don't exist in the map
}
return result;
}
var result = getMissingNumbers(statues);
console.log('Missing items: ', result);
console.log('Number of missing items: ', result.length);
Here is a simple solution you can try :
var a = [1,5,2,7];
a.sort((a, b) => a-b)
.reduce((acc, element, index) => {
if(index) acc = acc + element - a[index-1] - 1; return acc;
}, 0);
In a multi-dimensional array, how can I add a new dimension that is the sum of all of previous values of one of the other dimensions?
What I have:
var myarray = [[5,"a"],[10,"a"],[3,"a"],[2,"a"]];
What I want:
var newArray = [[5,"a",5],[10,"a",15],[3,"a",18],[2,"a",20]];
I am trying to turn this example (second answer, second code block):
var myarray = [5, 10, 3, 2];
var result = myarray.reduce(function(r, a) {
if (r.length > 0)
a += r[r.length - 1];
r.push(a);
return r;
}, []);
// [5, 15, 18, 20]
And apply it like this:
var myarray = [[5,"a"],[10,"a"],[3,"a"],[2,"a"]];
var result = myarray.reduce(function(r, a) {
if (r.length > 0)
a += r[0][r.length - 1];
r[2].push(a);
return r;
}, []);
// [[5,"a",5],[10,"a",15],[3,"a",18],[2,"a",20]];
But I can't find an effective way to separate out the first value in order to run reduce on it. I tried foreach, but that isn't returning an array:
var firstValue = myarray.forEach(function(value, index) {
console.log(value[0]);
})
So, I'm thinking take that foreach output and turn it into an array somehow to operate on, then push it back in. But it's seeming very convoluted. Can anyone point me in the right direction?
Thanks.
For reducing the array and only pulling the first element from each array, you actually need to build an array with the foreach loop.
Create an array outside the loop and use array.push(value) to build the other array.
var firstValues = [];
myarray.forEach(function(value, index) {
firstValues.push(value);
});
My preferred solution:
Since you're already looping through the array, you can instead do a lot of the logic within just one loop.
var currentSum = 0;
myarray.forEach(function(value, index) {
currentSum += value[0]; //add to the running sum
value.push(currentSum); //append the running sum to the end of this inner array
});
Here's a demo via jsfiddle
a simple for loop should do it
var sum = 0;
for (var i = 0; i < myarray.length; i++) {
sum = sum + (myarray[i][0]);
myarray[i].push(sum);
}
console.log(myarray);
Fiddle link
I need to iterate from 0 to 30, but I want to do this with help of forEach:
new Array(30).forEach(console.log.bind(console);
Of course this does not work, therefor I do:
new Array(30).join(',').split(',').forEach(console.log.bind(console));
Is there other ways to fill empty arrays?
Actually, there's a simple way to create a [0..N) (i.e., not including N) range:
var range0toN = Object.keys(Array.apply(0,Array(N)));
Apparently Object.keys part can be dropped if you only want to get a proper array of N elements.
Still, like others said, in this particular case it's probably better to use for loop instead.
if you want all of item have same value, do this
var arrLength = 4
var arrVal = 0
var newArr = [...new Array(arrLength)].map(x => arrVal);
// result will be [0, 0, 0, 0]
You could try using a for loop. new Array is not a best practise
var index, // we use that in the for loop
counter, // number of elements in array
myArray; // the array you want to fill
counter = 30;
myArray = [];
for (index = 0; index < counter; index += 1) {
myArray[index] = [];
/*
// alternative:
myArray.push([]);
// one-liner
for (index = 0; index < counter; index += 1) myArray.push([]);
*/
}
If you simply want to iterate, then use for loop like this
for (var i = 0; i < 30; i += 1) {
...
...
}
Actually, if you are looking for a way to create a range of numbers, then you can do
console.log(Array.apply(null, {length: 30}).map(Number.call, Number));
It will create numbers from 0 to 29. Source : Creating range in JavaScript - strange syntax
If you insist foreach
var data = [1, 2, 3];
data.forEach(function(x) {
console.log(x);
});