get always 10 numbers from randoms - Javascript [duplicate] - javascript

This question already has answers here:
Want to produce random numbers between 1-45 without repetition
(4 answers)
Closed 4 years ago.
I need help with my code. I want to get 10 random numbers every time it rolls and it can't have duplicated, this is my code:
for(let j = 1; j <= 21; j++) {
const number = (Math.floor((Math.random() * j) + 1))
const genNumber = array.indexOf(number);
if (genNumber === -1) {
array.push(number);
}
}
I have no idea how I can get exactly 10 numbers every time, anyway it can be written with js or jquery it doesnt metter for me. Hope I can get help here.

I don't really understand what your code is intended to do, but to get exactly 10 unique random numbers I'd use a Set and loop until it's filled. I have no idea why you loop 21 times for 10 items though...
let s = new Set();
while (s.size < 10) {
s.add((Math.floor(Math.random() * 21 /* ??? */) + 1));
}
console.log([...s]);

You're almost there, but instead of using a for loop, use a while loop that continues as long as there are less than 10 things in the array:
const array = [];
const j = 21; // Pick numbers between 1 and 21 (inclusive)
while (array.length < 10) {
const number = (Math.floor((Math.random() * j) + 1))
const genNumber = array.indexOf(number);
if (genNumber === -1) {
array.push(number);
}
}
console.log(array);

Related

find the trailing zeroes of the factorial [duplicate]

This question already has answers here:
factorial with trailing zeros, but without calculating factorial
(4 answers)
Closed 3 months ago.
the question asks that how many zeros are their at the end of the digit,
for example if factorial of 5 is 120 then result is 1 because there is only one zero at the end if there was 2 zeros then result is 2.
so I have traied this logic in javascript to solove this problem, and for different numbers its working but for some test cases its not showing the desired output.
Can't figure out why am getting the error, if any one has a better optimized code please do share and point out the mistake that am doing
const fun=(n)=>
{
let fact = 1;
let counter = 0;
for (let i = 1; i <= n; i++) {
fact *= i
}
while (fact % 10 == 0) {
let val = fact / 10;
fact = val;
counter++
}
return counter
}
console.log(fun(5))
Your function works for all numbers as long as they don't become too big, javascript has a hard time with big numbers. One easy way to fix it is to count the zeros while doing the factors.
const fun=(n)=>
{
let fact = 1;
let counter = 0;
for (let i = 1; i <= n; i++) {
fact *= i;
if(fact % 10 == 0){
fact/=10;
counter++;
}
}
return counter
}
console.log(fun(24));
This still has a limit, but might be high enough.

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

Random Number List Missing Number 1

I have an issue with a function I have written: although it mostly works, there is one issue where sometimes the number 1 isn't added to the list. The code is supposed to make a list of numbers from 1 - 10, however the number 1 is sometimes missing, where I presumably the issue is it is being overwritten when number 10 is already there before number 1
The code is written using the Code.org AppLab, written in a pseudo-code that is similar to JavaScript.
function randomizer(stringName, numbersShuffled) {
//This creates a string of Numbers that will eventually be converted to a list
for (var i = 0; i < numbersShuffled; i++) {
var tempNum = randomNumber(1, numbersShuffled);
console.log(numbersShuffled);
if (stringName.includes(tempNum)) {
console.log(stringName);
if (tempNum == 1 && stringName.includes(10)) {
tempNum = randomNumber(1, numbersShuffled);
}
while ((stringName.includes(tempNum))) {
tempNum = randomNumber(1, numbersShuffled);
}
}
stringName = (stringName + " ") + tempNum;
}
console.log(stringName);
The issue is that usually the number 1 is missing if number 10 is already in place in the list.enter code here

Sum of Array of Odd numbers - JS

Given the triangle of consecutive odd numbers:
1
3 5
7 9 11
13 15 17 19
21 23 25 27 29
// Calculate the row sums of this triangle from the row index (starting at index 1) e.g.:
rowSumOddNumbers(1); // 1
rowSumOddNumbers(2); // 3 + 5 = 8
I tried to solve this using for loops:
function rowSumOddNumbers(n){
let result = [];
// generate the arrays of odd numbers
for(let i = 0; i < 30; i++){
// generate sub arrays by using another for loop
// and only pushing if the length is equal to current j
let sub = [];
for(let j = 1; j <= n; j++){
// if length === j (from 1 - n) keep pushing
if(sub[j - 1].length <= j){
// and if i is odd
if(i % 2 !== 0){
// push the i to sub (per length)
sub.push(i);
}
}
}
// push everything to the main array
result.push(sub);
}
// return sum of n
return result[n + 1].reduce(function(total, item){
return total += item;
});
}
My code above is not working. Basically I was planning to 1st generate an array of odd numbers less than 30. Next I need to create a sub array base on the length of iteration (j) that would from 1 - n (passed). Then finally push it to the main array. And then use reduce to get the sum of all the values in that index + 1 (since the index starts at 1).
Any idea what am I missing and how to make this work?
Most code problems involve some analysis first in order to spot patterns which you can then convert into code. Looking at the triangle, you'll see the sum of each row follows a pattern:
1: 1 === 1 ^ 3
2: 3 + 5 = 8 === 2 ^ 3
3: 7 + 9 + 11 = 27 === 3 ^ 3
... etc
So from the analysis above you can see that your code could probably be simplified slightly - I won't post an answer, but think about using Math.pow.
No need for any loops.
function rowSumOddNumbers(n) {
// how many numbers are there in the rows above n?
// sum of arithmetic sequence...
let numbers_before_n_count = (n - 1) * n / 2;
let first_number_in_nth_row = numbers_before_n_count * 2 + 1;
let last_number_in_nth_row = first_number_in_nth_row + 2 * (n - 1);
// sum of arithmetic sequence again...
return n * (first_number_in_nth_row + last_number_in_nth_row) / 2;
}

Categories