Javascript for loop check condition - javascript

I want to create a function that will generate a random number between 0 to 9 which is not in the array.
My code so far:
var myArr = [0,2,3,4];
console.log("Arr: " + myArr);
function newNum(){
console.log("test");
for (var i = 0; i < 10; i++) {
var n = myArr.includes(i)
// I want to return n if it's not present in the array
}
return n;
}
newNum()
I want to return only 1 number. How do I do this?
Thanks.

What about this?
const invalidValues = [0,2,3,4];
const getRandomInt = (min, max) => {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
}
const getValidRandomInt = (min, max) => {
while(true) {
let temp = getRandomInt(min,max)
if(!invalidValues.includes(temp)) {
return temp;
}
}
}
console.log(getValidRandomInt(0,10))

var myArr = [0,2,3,4];
function newNum(){
for (var i = 0; i < 10; i++) {
if (!myArr.includes(i)) {
return i;
}
}
// return -1 if all numbers present in array..
return -1;
}
newNum();

Generate the number within the range by using Math.random() then loop and check whether the number generated is in the array or not, if not in the array return the number:
function getRandomArbitrary(min, max, arr) {
arr = new Set(arr);
while(true){
let val = Math.floor(Math.random() * (max - min) + min);
if(!arr.has(val)){ return val;}
}
}
console.log(getRandomArbitrary(0, 10, [4,3,2]));

Answer:
Use Math.random() * (max - min) + min to get a number within a range.
You can wrap it with Math.floor to round down to an integer, or alternatively use a bitwise OR ( | ) for small numbers.
function newNum(n_arr) {
let r = () => Math.random()*9 | 0,
n = r();
while(n_arr.includes(n)) {
n = r();
}
return n;
}
Example:
var myArr = [0,2,3,4];
function newNum(n_arr){
let r = () => Math.random()*9 | 0,
n = r();
while(n_arr.includes(n)) {
n = r();
}
return n;
}
let result = newNum(myArr);
console.log(result);

var myArr= [0,2,5];
function randomNumber(myArr, n){
n ? n : 1;
var num = Math.random() * n;
if(myArr.indexOf( num ) !==-1 ) {
return randomNumber( myArr, n );
}
return num;
}
randomNumber(myArr, 10);

If you want to return the first number missing in the array, from your code above, you could just check if every value of i exists in the array and the moment that value doesn't exist, return it.
var myArr = [0,2,3,4]; // original array
function newNum(){
for (var i = 0; i < 10; i++) { // loop through i from 0-9
if (myArr.indexOf(i) === -1){ // check for the first missing number
return i; //return it
}
}
}
newNum()

Related

Not able to get value after Do...While loop

Question: Create a function that takes a positive integer and returns the next bigger number that can be formed by rearranging its digits. For example:
12 ==> 21
513 ==> 531
2017 ==> 2071
//nextBigger(num: 12) // returns 21
//nextBigger(num: 513) // returns 531
//nextBigger(num: 2017) // returns 2071
I am trying to compare two Array and get correct array as answer. In do...while loop I am comparing the two array by increment second array by one.
function nextBigger(n){
let nStrg = n.toString();
let nArr = nStrg.split('');
function compareArr(Ar1,Ar2){
if(Ar2.length>Ar1.length){
return false;
}
for(let i=0; i<Ar1.length; i++){
let num = Ar1[i];
for(let j=0; j<Ar2.length; j++){
if(Ar2.lastIndexOf(num) !== -1){
Ar2.splice(Ar2.lastIndexOf(num), 1);
break;
}
else{
return false;
break;
}
}
}
return true;
}
let nextNumArr;
let m = n;
do{
let nextNum = m+1
m=nextNum
let nextNumStrg = nextNum.toString();
nextNumArr = nextNumStrg.split('')
console.log(compareArr(nArr, nextNumArr))
}
while(compareArr(nArr, nextNumArr) == false)
console.log(nextNumArr)
return parseInt(nextNumArr.join())
}
nextBigger(12);
This gives me empty array at the end;
[2,0,1,7].join() will give you '2,0,1,7', can use [2,0,1,7].join('') and get '2017'
All looks a bit complicated. How about:
const nextLarger = num => {
const numX = `${num}`.split(``).map(Number).reverse();
for (let i = 0; i < numX.length; i += 1) {
if ( numX[i] > numX[i + 1] ) {
numX.splice(i, 2, ...[numX[i+1], numX[i]]);
return +(numX.reverse().join(``));
}
}
return num;
};
const test = [...Array(100)].map(v => {
const someNr = Math.floor(10 + Math.random() * 100000);
const next = nextLarger(someNr);
return `${someNr} => ${
next === someNr ? `not possible` : next}`;
}).join('\n');
document.querySelector(`pre`).textContent = test;
<pre></pre>
See also
function nextbig(number) {
let nums = []
number.toString().split('').forEach((num) => {
nums.push(parseInt(num))
})
number = nums
n = number.length
for (var i = n - 1; i >= 0; i--) {
if (number[i] > number[i - 1])
break;
}
if (i == 1 && number[i] <= number[i - 1]) {
return 'No greater possible'
}
let x = number[i - 1];
let smallest = i;
for (let j = i + 1; j < n; j++) {
if (number[j] > x &&
number[j] < number[smallest])
smallest = j;
}
let temp = number[smallest];
number[smallest] = number[i - 1];
number[i - 1] = temp;
x = 0
for (let j = 0; j < i; j++)
x = x * 10 + number[j];
number = number.slice(i, number.length + 1);
number.sort()
for (let j = 0; j < n - i; j++)
x = x * 10 + number[j];
return x
}
console.log(nextbig(12))
console.log(nextbig(513))
console.log(nextbig(2017))
In compareArr you are deleting elements as you find them, which is correct to do, to make sure duplicates actually occur twice etc. However, that also deletes the elements from nextNumArr in the calling context, because the array is passed by reference and not by value. You need to do a manual copy of it, for example like this: compareArr(nArr, [...nextNumArr]).
I have used a different approach, first I search for all possible combinations of the given numbers with the permutator function. This function returns an array of possible numbers.
Then I sort this array of combinations and look for the index of the given number in the main function.
Once I have this index I return the position before the given number.
function nextbig(num){
function permutator(inputArr){
let result = [];
const permute = (arr, m = []) => {
if (arr.length === 0) {
result.push(m)
} else {
for (let i = 0; i < arr.length; i++) {
let curr = arr.slice();
let next = curr.splice(i, 1);
permute(curr.slice(), m.concat(next))
}
}
}
permute(inputArr)
return result;
}
let arrNums = num.toString().split('')
let combinations = permutator(arrNums).map(elem => parseInt(elem.join("")))
combinations.sort((a, b) => {
return b - a
})
let indexOfNum = combinations.findIndex(elem => elem === num)
let nextBigIndex = indexOfNum <= 0 ? 0 : indexOfNum - 1
return (combinations[nextBigIndex])
}
console.log(nextbig(12))
console.log(nextbig(517))
console.log(nextbig(2017))

how can you Given two integers a and b, which can be positive or negative,and find the sum of all the numbers between including them too and return it

function getSum( a , b){
} //so how do you get along this
A for-loop does the sum.
Assuming a < b
let sum = 0,
a = -3,
b = 4;
for (let i = a; i <= b; i++) {
sum += i;
}
console.log(sum);
Just start a loop from the lowest number till the highest number. Keep on adding all the numbers and return the sum.
The idea is to create a loop between a and b and add all of them in a 3rd variable.
But first, you need to determine what is the start and the end of the loop, I create a min, max var for that depending if a > b or not and loop from min to max:
function getSum(a, b) {
const min = a < b ? a : b;
const max = a < b ? b : a;
let sum = 0;
for(let i = min; i <= max; i++) {
sum += i;
}
return sum;
}
Just we need to identify the start and end index. and you can default your result to 0, otherwise you may get NaN error.
function getSum(a, b) {
var startindex = a > b ? b : a;
var endindex = a > b ? a : b;
var result = 0;
for(var i = startindex; i <= endindex; i++) {
result = result + i;
}
return result;
}
I think you can simply use the formula in this topic. This doesn't even require to use a for loop. In your code you use a instead of alpha and b instead of beta.
var num_1 = 20;
var num_2 = 30;
console.log( getSum(num_1, num_2) );
function getSum(a,b) {
return (a+b)*(b-a+1)/2
}
const GetSum = (a, b) => {
let min = Math.min(a, b),
max = Math.max(a, b);
return (max - min + 1) * (min + max) / 2;
}

Javascript - simple exercises

I have a task to write a function getEvenAverage, which should take only one argument - array. This function should return an average value of even numbers from this array. If in the array there aren't any even numbers the function should return null.
I'd really appreciate any feedback :-)
function getEvenAverage(tab) {
{
if (i % 2 === 0) {
for (var i = 0; i < tab.length; i++) {
sum += parseInt(tab[i], 10);
}
var avg = sum / tab.length;
} else
console.log('null');
}
}
You say you need to return something, so return it. Also move your if statement inside your for loop, and fix a few other syntax errors. And as pointed out in the comments, you should divide sum by the number of even numbers to get your avg:
function getEvenAverage(tab) {
var sum = 0;
var evens = 0;
for (var i = 0; i < tab.length; i++) {
if (i % 2 === 0) {
sum += parseInt(tab[i], 10);
evens++;
}
}
if (evens == 0) {
console.log("null");
return null;
} else {
var avg = sum / evens;
return avg;
}
}
console.log(getEvenAverage([1, 2, 3]));
You could also do it with the array reduce, with a single array traversal
const reducer = (acc, val) => {
let {
sum,
count
} = acc;
return (val % 2 === 0 ? {
sum: sum + val,
count: count + 1
} : acc);
};
const getEvenAverage = (input) => {
const initialValue = {
sum: 0,
count: 0
};
const output = input.reduce(reducer, initialValue);
if (output.count === 0) {
return null;
} else {
return output.sum / output.count;
}
};
console.log(getEvenAverage([1, 2, 3]));
Here is the correct function.
function getEvenAverage(tab) {
var sum = 0, count = 0;
for (var i = 0; i < tab.length; i++) {
if (i % 2 === 0) {
sum += parseInt(tab[i], 10);
count++;
}
}
if(sum > 0)
return (sum / count);
return null;
}
Wish You happy coding.
Other than using a for loop, you can utilize filter and reduce Array methods.
function getEvenAverage(arr) {
const newArr = arr.filter(number => number % 2 === 0);
return newArr.length > 0 ? newArr.reduce((acc, num) => acc + num) / newArr.length : null;
}
console.log(getEvenAverage([1, 2, 3, 4]));
console.log(getEvenAverage([1, 3, 5, 7]));
Try this function,
function getEvenAverage(tab) {
var numberOfEvens = 0;
var sum = 0;
for(var i=0;i<tab.length;i++){
if(tab[i]%2 == 0 ){
numberOfEvens++;
sum += tab[i];
}
}
if(numberOfEvens == 0)return null;
return sum/numberOfEvens;
}
console.log(getEvenAverage([0,1,2,3,4,5]))
console.log(getEvenAverage([1,2,3,4,5]))
console.log(getEvenAverage([0,1,11,3,4,5]))
console.log(getEvenAverage([1,5,3]))
You need only the even numbers, so first filter the array into a new array, then sum all the numbers (using reduce or a for loop) and divide by its length.
function getEvenAverage(array) {
if (!Array.isArray(array)) return null; // not a must if you're sure you pass an array
var evenArray = array.filter(function(value) {
return value % 2 === 0
});
if (evenArray.length === 0) return null;
var evenSum = evenArray.reduce(function(total, current) {
return total + current;
});
var evenAvg = evenSum / evenArray.length;
return evenAvg;
}
console.log(getEvenAverage("not an array"));
console.log(getEvenAverage([1,3,7])); // no even numbers
console.log(getEvenAverage([1,2,3])); // single even number
console.log(getEvenAverage([2,2,2])); // only even numbers
console.log(getEvenAverage([1,2,3,10,18])); // bigger array
console.log(getEvenAverage([0,1])); // 0 is also even
function getEvenAverage(arr){
var evenNumbers = []; // we use an array to hold all of our evenNumbers
for (var el of arr){ // we loop over the received array to check the received
if(el % 2 !=0){ // if the number is even
evenNumbers.push(el); // we add it to our evenNumbers array
}
}
if(evenNumbers.length == 0){ // when we have no even Number
return false; // we then return false
}
else{
// the next block of code calculates the average of the even values
return evenNumbers.reduce((pv,cv) => pv+cv,0)/evenNumbers.length;
}
}
var evenNumbers = [4,2,3,6,5,9];
getEvenAverage(evenNumbers); // returns 5.666666666666667
getEvenAverage([2,4,6,8]); // returns false

Javascript reduce not working after function?

Not too sure where I've gone wrong here, expecting to factorialize 5 (1*2*3*4*5 = 120) by turning 5 into a string of [1,2,3,4,5] and then using reduce to multiply the string all together. When I run the code, it just gives me [1,2,3,4,5]...
var arr = [];
function factorialize(num) {
for (var i = 1; i <= num; i++) {
arr.push(i);
}
return arr;
}
var factors = 0;
factors = arr.reduce(function(previousVal, currentVal) {
return previousVal * currentVal;
}, 0); // Expecting 120, instead result = [1,2,3,4,5]
factorialize(5);
Forgive the long route - my first week of Javascript!
arr is empty, you should give it the resulting array of the factorisation first, and you should multiply, not add, and when multiplying, the starting value is 1 not 0:
var arr = [];
function factorialize(num) {
for (var i = 1; i <= num; i++) {
arr.push(i);
}
return arr;
}
arr = factorialize(5); // give it the value
var factors = arr.reduce(function(previousVal, currentVal) {
return previousVal * currentVal; // multiply, don't add
}, 1); // start with 1 when multiplying
console.log(arr);
console.log(factors);
If you just want to calculate the factorial:
function factorial(num) {
var res = 1;
for (var i = 2; i <= num; i++) {
res *= i;
}
return res;
}
console.log('factorial(5) = ' + factorial(5));
console.log('factorial(10) = ' + factorial(10));
You are not calling factors. factorialize(5); by doing this you are just calling function factorialize(num) which will give you array(of 1...num).
(Additional info)And also in reduce you are adding + instard of multiplying * so change that too and
factors = arr.reduce(function(previousVal, currentVal) {
return previousVal + currentVal;
}, 0);
^
|_ either initialize it to 1 or remove this.
See below code. I just create array and then apply reduce on that array.
function factorialize(num) {
var arr = [];
for (var i = 1; i <= num; i++) {
arr.push(i);
}
return arr.reduce(function(previousVal, currentVal) {
return previousVal * currentVal;
});
}
console.log(factorialize(5));
var arr = [];
function factorialize(num) {
for (var i = 1; i <= num; i++) {
arr.push(i);
}
var factors = 0;
factors = arr.reduce(function (previousVal, currentVal) {
return previousVal * currentVal;
});
return factors
}
factorialize(5); // 120
You could get first the factors and then multiply in Array#reduce the factors.
I suggest to name the function what it does and move the array declaration inside of the function, because the function returns this array.
For getting the product, you need to multiply the values and use 1 as neutral start value for getting a product out of the numbers.
function getFactors(num) {
var i, arr = [];
for (i = 1; i <= num; i++) {
arr.push(i);
}
return arr;
}
var factors = getFactors(5),
product = factors.reduce(function(previousVal, currentVal) {
return previousVal * currentVal;
}, 1);
console.log(factors);
console.log(product);
Put the global variable arr inside of the function factorialize.
Get the returned array and then execute the function reduce.
You need to multiply rather than to add the numbers.
Start the reduce with initialValue = 1, this is to avoid 0 * n.
function factorialize(num) {
var arr = [];
for (var i = 1; i <= num; i++) {
arr.push(i);
}
return arr;
}
var arr = factorialize(5);
var factors = arr.reduce(function(previousVal, currentVal) {
return previousVal * currentVal;
}, 1);
console.log(factors)
Issue is with the initial value set to 0 and instead of multiplying numbers, it is being added
arr.reduce(callback, initValue)
arr = [1,2,3,4,5]
In the code provided, it accumulates in below format
arr.reduce(function(previousVal, currentVal) {
return previousVal + currentVal;
}, 0);
First call -> 0 + 1 = 1 (factors = 1)
Second call -> 0 + 2 = 2 (factors = 2)
First call -> 0 + 3 = 3 (factors = 3)
First call -> 0 + 4 = 4 (factors = 10)
First call -> 0 + 5 = 5 (factors = 15)
To achieve expected result, use below option
var arr = []; // initialize array arr
function factorialize(num) {
//for loop to push 1,2 ,3, 4, 5 to arr array
for (var i = 1; i <= num; i++) {
arr.push(i);
}
// return arr.reduce value by multiplying all values in array, default initial value is first element
return arr.reduce(function(previousVal, currentVal) {
//console log to debug and display loop values
console.log(previousVal, currentVal);
return previousVal * currentVal;
});
}
console.log("output", factorialize(5));
code sample - https://codepen.io/nagasai/pen/YaQKZw?editors=1010

'undefined' result for variable in Javascript function

something in my code is meaning that I am getting an array printed which contains only undefined values, not the random numbers I am expecting.
My code is below:
function List(max, min, numLists, numItems) {
this.max = max,
this.min = min,
this.numLists = numLists,
this.numItems = numItems,
this.generateLists = function () {
var fullArray = [];
var completeArray = [];
for (i = this.min; i < this.max; i++) {
fullArray.push(i);
}
for (i = 0; i < numItems; i++) {
var randomItem = Math.floor(Math.random() * (1 + (this.max - this.min)));
completeArray.push(fullArray[randomItem]);
}
console.log(completeArray);
}
}
var newList = new List(12, 100, 1, 15);
newList.generateLists();
The code is supposed to print a random list of number between the min and max values. I'm getting an array with 15 values in, but they are all undefined. I'm guessing this mean there is something wrong with my first 'for' loop?
If anyone has any suggestions on how I could make this better please do criticise!
Thanks in advance.
You have min and max mixed up in your arguments list. this results in an impossible boundary for your numbers (greater than 100 but less than 12). Just swap the parameters in the first line from max,min to min,max.
function List(min,max,numLists,numItems){
this.max = max,
this.min = min,
this.numLists = numLists,
this.numItems = numItems,
this.generateLists = function (){
var fullArray = [];
var completeArray = [];
for ( i = this.min ; i<this.max ; i++) {
fullArray.push(i);
}
for ( i = 0 ; i<numItems ; i++) {
var randomItem = Math.floor(Math.random() * (1+(this.max-this.min)));
completeArray.push(fullArray[randomItem]);
}
console.log(completeArray);
}
}
var newList = new List ( 12 , 100 , 1,15);
newList.generateLists();
I think you swap the position of max and min when you initiate newList.
Change the line to:
var newList = new List ( 100, 12 , 1,15);
Then it should work fine.
You were pushing fullArray[randomItem] that contains nothing. It is never initialized
function List(max, min, numLists, numItems) {
this.max = max,
this.min = min,
this.numLists = numLists,
this.numItems = numItems,
this.generateLists = function() {
var completeArray = [];
for (i = 0; i < numItems; i++) {
var randomItem = Math.floor(Math.random() * (1 + (this.max - this.min)));
completeArray.push(randomItem);
}
document.write(completeArray);
}
}
var newList = new List(12, 100, 1, 15);
newList.generateLists();
I think maybe you max and min arguments were in the wrong order. You were trying to access the fullArray with a negative index due to subtracting a larger number from a smaller one.
function List(min,max,numLists,numItems){
this.max = max,
this.min = min,
this.numLists = numLists,
this.numItems = numItems,
this.generateLists = function (){
var fullArray = [];
var completeArray = [];
for ( i = this.min ; i<this.max ; i++) {
fullArray.push(i);
}
for ( i = 0 ; i<numItems ; i++) {
var randomItem = Math.floor(Math.random() * (1+(this.max-this.min)));
console.log(randomItem)
completeArray.push(fullArray[randomItem]);
}
console.log(completeArray);
}
}
var newList = new List ( 12 , 100 , 1,15);
newList.generateLists();
I think max and min parameter are swapped
This
function List(max,min,numLists,numItems){
should be
function List(min,max,numLists,numItems){
Just replace this line;
var randomItem = Math.floor(Math.random() * (1+(this.max-this.min)));
with;
var randomItem = Math.floor(Math.random()*(fullArray.length)+1);

Categories

Resources