undefined elements inside an array which has randomized numbers inside it - javascript

so I created this script to generate an array of 5 random numbers where the numbers must be unique, but I get +2 undefined elements. There are 5 numbers which are unique but the length of the array isn't anymore 5
let arr = [];
while (arr.length <= 5) {
let x = Math.floor(Math.random() * 11);
if (arr.includes(x) === false) {
arr.push(x);
}
arr.length += 1;
}
console.log(arr);
Thanks in advance guys.

You should remove the arr.length += 1 line. The array length will be automatically incremented each time a new element is pushed, no need to modify it by yourself: this is a bad practice.

the length is not 5 because this loop runs 6 times, arr.length = 0,1,2,3,4,5. and you have a 3 undefined elements because of ( arr.length += 1; ) this skips step 1,3,5.

let arr = [];
while (arr.length<5){
let x = Math.floor(Math.random()*11);
if (arr.includes(x) === false){
arr.push(x);
}
}
console.log(arr);

Related

creating a function that only returns odd numbers [duplicate]

This question already has answers here:
How do I extract even elements of an Array?
(8 answers)
How to do a script for odd and even numbers from 1 to 1000 in Javascript?
(8 answers)
Closed 2 years ago.
I've spent an embarrassing amount of time on this question only to realize my function is only right 50% of the time. So the goal here is to return only the odd numbers of all the numbers in between the two arguments. (for instance if the arguments are 1 and 5 i'd need to return 2 & 3) the function I wrote is completely dependent on the first argument. if it's even my function will return odds, but if the first number is odd it'll return evens. does anyone know how i can fix this?
function oddNumbers(l, r) {
const arr = [];
const theEvens = [];
for (let i= l; i<r; i++) {
arr.push(i)
}
console.log(arr)
for (let i= 0; i < arr.length; i+= 2 ) {
const evens = arr[0] + i;
theEvens.push(evens);
}
theEvens.forEach(item => arr.splice(arr.indexOf(item), 1));
console.log(arr)
}
oddNumbers(2, 20);
I modified the code a bit to return only odd numbers
We use the % operator that behaves like the remainder operator in math:
so when we say i % 2 if the number is even the result of the operation will be 0
but when the "i" is an odd number the result will be 1
so now we can filter the even from the odd numbers using this operation
function oddNumbers(l, r) {
const arr = [];
for (let i= l; i<r; i++) {
if(i % 2 !== 0) arr.push(i);
}
console.log(arr);
}
oddNumbers(2, 20);
You can loop from initial to end parameters and get odd numbers using modulo, try this:
let result = [];
let returnOdd = (n1, n2) => {
for(i = n1; i < n2; i++){
if(i % 2 != 0){
result.push(i)
}
}
return result;
}
console.log(returnOdd(2, 20));
You could use the filter method.
This method creates a new array based on the condition it has. In this case it will to go through all the numbers in the array, and check if the number is odd (though the remainder operator).
For example:
1 % 2 = 1 ( true, keep in the new array )
2 % 2 = 0 ( false ignore in the new array )
function OddNumbers(start, end) {
// Create an array from the given range
const nums = Array(end - start + 1).fill().map((_, idx) => start + idx);
// Use filter to return the odd numbers via the % operator
return nums.filter(num => num % 2);
}
console.log(OddNumbers(2,20))

If statement involving modulo behaving erratically [duplicate]

This question already has answers here:
Looping through array and removing items, without breaking for loop
(17 answers)
Closed 2 years ago.
I'm making a function to create a list of prime numbers from 0 to num. I start off with a list of integers from 2 to num, and iterate over each one that goes from 2 to i < num; if at any point item % i === 0, the item is removed from the list. This works fine:
function getPrimes(num) {
// get list of ints from 2 to num
let primes = [...Array(num + 1).keys()];
primes = primes.splice(2);
let lastNumber = primes[primes.length - 1];
// make iterable, run its loop
// for each number in primes
for (let number of primes) {
// use iterable to remove if not prime
for (let i = 2; i < num; i++) {
if (number % i === 0) {
primes.splice(primes.indexOf(number), 1);
}
}
}
// add back two
primes.unshift(2);
return primes;
But when I try and make the iterable for each number only to up to Math.floor(num / 2) for the sake of efficiency, it breaks the code somehow:
function getPrimes(num) {
// get list of ints from 2 to num
let primes = [...Array(num + 1).keys()];
primes = primes.splice(2);
let lastNumber = primes[primes.length - 1];
// make iterable, run its loop
// for each number in primes
for (let number of primes) {
// use iterable to remove if not prime
for (let i = 2; i < Math.floor(num / 2); i++) {
if (number % i === 0) {
primes.splice(primes.indexOf(number), 1);
}
}
}
// add back two
primes.unshift(2);
return primes;
When I tried it out, getPrimes(10) gives me [ 2, 3, 5 ]. So seven is missing from the list of prime numbers from 0 to 10. Why is that? I checked and 7 modulo 2, 3, and 4 returns 1, 1, and 3, respectively. So why is the code in the loop running that removes 7 from primes? It's the only place in the code where I put that I wanted to remove a number from the array.
The first issue is that you are looping while removing items, which causes some items to be skipped. Loop backwards instead, so that only items that have already been checked are shifted. Second, num / 2 should be changed to Math.sqrt(number), as that is the maximum factor that needs to be checked before we can be sure that a number is prime. With this method, there is no need to add 2 back to the array.
function getPrimes(num) {
// get list of ints from 2 to num
let primes = [...Array(num + 1).keys()];
primes = primes.splice(2);
let lastNumber = primes[primes.length - 1];
// make iterable, run its loop
// for each number in primes
for(let i = primes.length - 1; i >= 0; i--){
let number = primes[i];
// use iterable to remove if not prime
for (let j = 2; j * j <= number; j++) {
if (number % j === 0) {
primes.splice(i, 1);
break;
}
}
}
return primes;
}
console.log(...getPrimes(10));

I need to remove items from array until there is only one

I have made array and all but i only need function that clears every second item from list and doing that job until there is only 1 item left for example i need something to do in array from 1-10 including 1 and 10 the result need to be 5?
Any sugestions it is similar like this but only need it for javascript not python
How to delete elements of a circular list until there is only one element left using python?
I am using this inside html body tag
var num = prompt("type num");
var array = [];
for (i = 1; i <= num; i++) {
array.push(i);
}
document.write(array + "<br>");
I tried this so far but this does not finish jobs great
while (i--) {
(i + 1) % 2 === 0 && array.splice(i, 1)
}
It does only first time deleting and leave array 1 3 5 7 9 i need it to be only 5 in this case because prompt is 10 in my case
The circular part makes it pretty tricky. Your loop condition should be on array length > 1, and within the loop you have to manually mess with the counter once it exceeds the length of the array - 2. If it's equal to arr.length, you want to skip the first element of the array the next time around, otherwise begin with the first element. Sorry I'm not explaining it better, here is the code.
var arr = [1,2,3,4,5,6,7,8,9,10];
var i = 1;
while (arr.length > 1) {
console.log("removing " + arr[i]);
arr.splice(i, 1);
var left = arr.length - i;
if (left == 0)
i = 1;
else if (left == 1)
i = 0;
else
i++;
}
console.log("result " + arr[0]);
Edit - This is almost exactly The Josephus Problem or see the episode from Numberphile on Youtube
There is a short recursive way to solve it. The parameter n is the largest number (similar to an array of n numbers from 1 to n), and k being the number of positions to skip at a time, (every other being 2).
var josephus = (n, k) => {
if (n == 1) return 1;
return (josephus(n - 1, k) + k-1) % n + 1;
};
console.log(josephus(10, 2));
while(array.length > 1) {
array = array.filter((_, index) => index % 2 === 0);
}
Basically, get rid of every second index as long as the length is greater than 1. The callback for filter allows value as the first parameter and index as the second, per MDN.

Addition with carryover in arrays in pure Javascript

I want to create simple addition of array with carryover. Also need carryover and result value for display.
Something like this:-
e.g var input = [[0,0,9],[0,9,9]];
var carryover = [];
var result = [];
Thanks...
The two parts you might have been struggling with, I assume would be how you get the carry, and how you get the result..
result [diget] = t % 10;
The % 10 part is what is called modulus, here I'm doing a modulus by 10, so that gets you the 10's unit value.
carryover [diget] = Math.trunc(t / 10);
For the carryover, you just then divide by 10, and then we strip the decimals,. That's what Math.trunc does.
var input = [[0,0,0,9],[0,9,9]];
var carryover = [];
var result = [];
var digetlength = Math.max(input[0].length, input[1].length);
//lets padd inputs to be same size
input[0].unshift(
...new Array(digetlength - input[0].length).fill(0));
input[1].unshift(
...new Array(digetlength - input[1].length).fill(0));
for (var diget = digetlength - 1; diget >= 0; diget -= 1) {
var t = input[0][diget] + input[1][diget];
if (diget < digetlength - 1)
t += carryover[diget + 1];
result [diget] = t % 10;
carryover [diget] = Math.trunc(t / 10);
}
result.unshift(carryover[0]);
console.log('result: ' + result.join(', '));
console.log('carry: ' + carryover.join(', '));
1.turn both numbers into array of digits, reverse them.
2.determine the end index of the for-loop with max length of above 2 arrays.
3.create the 3rd carryover digits array of zeros (don't forget the extra digit).
4.Add the respective digits from step1 and step3,
as you iterate through each of digits from right to left,
4.1 if the sum is greater than 9 then add 1 into next carryover slot.
5. you should have array of carried over digits when the for-loop is done
count the number of 1s you have in them.
function numberOfCarryOperations(num1, num2) {
const dd1 = [...num1.toString()].reverse()
const dd2 = [...num2.toString()].reverse()
const end = Math.max(dd1.length, dd2.length)
const carry = Array(end+1).fill(0)
for (let i = 0; i < end; i++) {
//console.log(i,(Number(dd1[i]?dd1[i]:0)),Number(dd2[i]?dd2[i]:0),carry)
if (((Number(dd1[i]?dd1[i]:0)) + Number(dd2[i]?dd2[i]:0) + carry[i]) > 9) {
carry[i+1] = 1
}
//console.log('-----',carry)
}
//console.log(num1, num2,carry)
return carry.reduce((sum,curr)=>sum+curr)
}
Here is my attempt. It will accept the following as input:
Any number of input arrays
The input arrays don't all need to have the same number of items
I've added code comments to explain what goes on, I hope they're informative enough to explain the answer.
const
input = [
[0,0,9],
[0,9,9],
[1,0,9,9]
];
function getMaxArrayLength(values) {
// Determine the number of items in the longest array. Initialize the reduce with 0.
return values.reduce((maxLength, array) => {
// Return the largets number between the last largest number and the
// length of the current array.
return Math.max(maxLength, array.length);
}, 0);
}
function sumValues(values) {
const
// Determine the number of items in the longest array.
maxLength = getMaxArrayLength(values),
result = [],
carry = [];
// Loop over the length of the longest array. The value of index will be substracted from
// the length of the input arrays. Therefore it is easier to start at 1 as this will
// return a proper array index without needing to correct it.
for (let index = 1; index <= maxLength; index++) {
const
// Get the carryover value from the last sum or 0 in case there is no previous value.
carryValue = (carry.length === 0) ? 0 : carry[carry.length-1],
// Sum up all the values at the current index of all the input arrays. After summing up
// all the values, also add the carry over from the last sum.
sum = values.reduce((sum, array) => {
// Determine the index for the current array. Start at the end and substract the
// current index. This way the values in the array are processed last to first.
const
arrayIndex = array.length - index;
// It could be the current array doesn't have as many items as the longest array,
// when the arrayIndex is less than 0 just return the current result.
if (arrayIndex < 0) {
return sum;
}
// Return the accumulated value plus the value at the current index of the
// current source array.
return sum + array[arrayIndex];
}, 0) + carryValue;
// The carry over value is the number of times 10 fits into the sum. This should be rounded
// down so for instance 5/10=.5 becomes 0.
carry.push(Math.floor(sum / 10));
// Push the remainder of the sum divided by 10 into the result so 15 % 10 = 5.
result.push(sum % 10);
}
// Return the carry over and the result, reverse the arrays before returning them.
return {
carryOver: carry.reverse(),
result: result.reverse()
};
}
const
result = sumValues(input);
console.log(`Carry over: ${result.carryOver}`);
console.log(`Result: ${result.result}`);

Convert random positive values of an array to negative

I'm a JS newcomer. I have a scrambled array of numbers and need to convert random positive values of the array into negative. At that point I only know how to randomize the array:
var myArray = [1,2,3,4,5,6,7,8,9,10];
myArray.sort(function() {
return 0.5 - Math.random()
})
But need the result look something like this:
[8,-2,3,9,-5,-1,4,7,6,-10]
Please suggest. Thank you!
myArray.forEach(function(i,j){
if(i>0){
var negative=i*(-1);/*convert your positive values to negative*/
myArray[j]=negative;
}
})
Modified Fisher–Yates shuffle to randomly negate the item
function shuffle2(arr) {
var i, j, e;
for (i = 0; i < arr.length; ++i) { // for every index
j = Math.floor(Math.random() * (arr.length - i)); // choose random index to right
e = arr[i]; // swap with current index
arr[i] = arr[i + j];
arr[i + j] = e;
if (.5 > Math.random()) // then, randomly
arr[i] = -arr[i]; // flip to negative
}
return arr;
}
Now can do
shuffle2(myArray); // [-5, 2, 6, -7, -10, 1, 3, -4, -9, -8]
Please note if you were to stop the loop at arr.length - 1 you will need a final random flip outside of the loop for the last index
How about adding a second random number for positiv / negative (Flipping coin):
var pos = Math.floor(Math.random()*10) % 2;
var num = Math.random() * 10;
var result;
// pos will evaluate false if it is 0
// or true if it is 1
result = pos ? num : -num;
return result;
You can transform your array using Array.prototype.map() to get random +/- like this:
myArray = myArray.map(function(item) {
return Math.random() > 0.5 ? item : -item; // random +/-
});
Map function does not modify your array but only returns new mapped one (so you have to reassign it or assign to a new variable).
As you are a new comer this is the easiest way. Used for loop and Math.floor()
First randomize the array.
Use math.random()*myArray.length and for loop to generate a random number and change the value of the index corresponding to the number value eg-
for (i = 0; i < 10; i++){
var arrVal = myArray[Math.floor( Math.random()*myArray.length);]
if(arrVal > 0){
arrVal = arrVal*(-1);
};
};

Categories