Javascript check random number duplicated - javascript

I have this random number from 1 to 10 and an array from 1 to 10 but missing an 8 and 2. I want JS to figure that out and push either 8 or 2 into the array.
Javascript:
var arr = [1, 3, 5, 6, 9, 4, 7, 10];
var num = Math.floor((Math.random() * 10) + 1);
for (i = 0; i < arr.length; i++) {
while (num == arr[i]) {
num = Math.floor((Math.random() * 10) + 1);
}
arr.push(num);
Unfortunately, it does make a new number but duplicate with the previous compared number. Please help.

You can look for the missing numbers and random an element in that array:
var arr = [1, 3, 5, 6, 9, 4, 7, 10];
// Build array of missing numbers
var missingNumbers = [];
for (var i = 1; i <= 10; i++) {
if (arr.indexOf(i) < 0) {
missingNumbers.push(i);
}
}
// Pick one of them at random
var randomNumber = missingNumbers[Math.floor(Math.random() * missingNumbers.length)];
// Push it into the array
arr.push(randomNumber);
// Show results
console.log(randomNumber);
console.log(arr);
.as-console-wrapper {
max-height: 100% !important;
}

You can try this as well
var arr =[1,3,5,6,9,4,7,10];
var num=parseInt((Math.random()*10)+1)
while(arr.indexOf(num)!=-1){
num=parseInt((Math.random()*10)+1);
}
arr.push(num)
console.log(arr)
In above example I am taking a number randomly and checking in loop that, The number is present in the array or not
while(arr.indexOf(num)!=-1)
if number will not be there then inside loop again I am generating again a number and checking. When I got a number which is not present then the loop body will not be execute and I am pushing that number in array.
As you said that only one number you want either 8 or 2

I figured it out.
var arr = [1, 3, 5, 6, 9, 4, 7, 10];
var num = Math.floor((Math.random() * 10) + 1);
for (i = 0; i < arr.length; i++) {
while (num == arr[i]) {
num = Math.floor((Math.random() * 10) + 1); }
arr.push(num);}
basically if it is duplicated, I simply put i=0 to loop again until it is unique. It might not be efficient.

The function find returns an array filled with all the duplicated numbers. It's optimized
function find(a, b) {
let result = [];
for(let i=0; i<a.length; i++) {
let num = NumbersList[i];
if(b[num] == 0) {
b[num] = 1;
} else if (b[num] == 1) {
b[num] = 2;
result.push(num);
}
}
console.log("Duplicated numbers: " +result.length);
return result;
}
var NumbersList = new Array();
var value = 30000;
for(let i=0; i<value; i++) {
let x = Math.floor((Math.random() * value) + 1);
NumbersList.push(x);
}
var map = new Array(NumbersList.length).fill(0);
var t0 = performance.now();
find(NumbersList, map);
var t1 = performance.now();
console.log("Call to find with " +value+ " numbers took " + (t1 - t0) + " milliseconds.");

Related

Get pair of elements from array whose value is equal to specific sum using javascript

Given an array as [2, 7, 5, 3, 9] I was trying to find the pair of values from the array whose sum would be equal to 12 and below is the code that I wrote
let arr1 = [2, 7, 5, 3, 9]
let addSum = 12;
for (let i = 0; i < arr1.length; i++) {
let diff = addSum - arr1[i];
if (arr1.includes(diff)) {
console.log('Arr pair has value' + diff + ': ' + arr1[i]);
}
}
but the issue i'm facing is the value are duplicated in the console as given below -
Arr pair has value5: 7
Arr pair has value7: 5
Arr pair has value9: 3
Arr pair has value3: 9
if i already have (5,7) it should not be repeated as (7,5) how can I do that?
Only print the cases where diff is less than arr[i].
let arr1 = [2, 7, 5, 3, 9]
let addSum = 12;
for (let i = 0; i < arr1.length; i++) {
let diff = addSum - arr1[i];
if (diff < arr1[i] && arr1.includes(diff)) {
console.log('Arr pair has value ' + diff + ': ' + arr1[i]);
}
}
The simplest solution would be to remove the other item index from the array when found:
let arr = [2, 7, 5, 3, 9]
let addSum = 12;
for (let i = 0; i < arr.length; i++){
let diff = addSum - arr[i];
const index = arr.indexOf(diff);
if (index !== -1) {
console.log('Arr pair has value' + arr[index] + ': '+arr[i]);
arr.splice(index, 1);
i--; // to avoid skipping the next one from the array indicies shifting down
}
}
Another solution with better time complexity (O(n) instead of O(n ^ 2)) would be to put the items into a Set instead, assuming duplicates aren't an issue:
const set = new Set([2, 7, 5, 3, 9]);
let addSum = 12;
for (const item of set) {
const diff = addSum - item;
if (set.has(diff)) {
console.log('Arr pair has value' + item + ': '+diff);
set.delete(diff);
}
}
If duplicates are a possibility you need to account for, use a Map (or object) instead, where the values are the number of times the key (the number) has been found in the original array. When a key that matches a diff is found, log only if the value is greater than 0, and decrement that value.
If you just want to strip duplicates from your list of results, store each diff in an array and check if the diff or the diff's difference already exist as a pair:
let arr1 = [2, 7, 5, 3, 9]
let addSum = 12;
let diffs = [];
for (let i = 0; i < arr1.length; i++) {
let diff = addSum - arr1[i];
if (arr1.includes(diff)) {
diffs.push(diff);
if (!diffs.includes(addSum - diff)) {
console.log('Arr pair has value ' + diff + ':' + arr1[i]);
} else {
diffs.push(arr1[i]);
}
}
}

Writing my own reverse array function without defining a new empty array

I am trying to write a function which reverses the elements of an array without defining a new empty array in the function.
let arrayValue = [1, 2, 3, 4, 5]
function remove(array, index) {
return array.slice(0, index).concat(array.slice(index + 1));
}
function reverseArrayInPlace(array) {
for (i = array.length - 2; i >= 0; i--) {
let removedCharacter = array[i];
array = array.concat(removedCharacter);
array = remove(array, i);
}
return array;
}
When I console.log(reverseArrayInPlace(arrayValue)) I am getting the reverse order of [5, 4, 3, 2, 1].
However when I try to just do reverseArrayInPlace(arrayValue) and then console.log(arrayValue), I am getting [1, 2, 3, 4, 5] which is the value defined at the beginning.
Is there a way of updating the arrayValue binding in the function and then when it is console.log outside the function, it is showing the reversed order?
// show cases of even and odd lengths
const x = [1,2,3,4];
const y = [1,2,3,4,5];
for (let i = 0; i < x.length / 2; i++) {
const tmp = x[i];
x[i] = x[x.length - 1 - i];
x[x.length - 1 - i] = tmp;
}
for (let i = 0; i < y.length / 2; i++) {
const tmp = y[i];
y[i] = y[y.length - 1 - i];
y[y.length - 1 - i] = tmp;
}
console.log(x);
// [4, 3, 2, 1]
console.log(y);
// [5, 4, 3, 2, 1]
The MDN docs for Array's slice and concat methods explain that these methods return new arrays, rather than modifying the existing arrays. If you are looking for a built-in Array method for modifying arrays, splice will do the job. However, it's going to be more complicated to implement this using splice than to just use a for loop as the other answers suggest.
You could just swap values symmetrically around the midpoint of the array, like
const arr = [0,1,2,3,4];
const len = arr.length;
for(let i = 0; i < len/2; i++){
let temp = arr[i];
arr[i] = arr[len-1-i];
arr[len-1-i] = temp;
}
console.log(arr);
function reverseArrayInPlace(array) {
for (let i = 0; i < array.length / 2; i++) {
const oppositeArrayIndex = array.length - (i + 1);
const oppasiteArrayValue = array[oppositeArrayIndex];
array[oppositeArrayIndex] = array[i];
array[i] = oppasiteArrayValue;
}
}

Fibonacci Sequence - Starts at a specific # in javascript

//var myInputNumber=10;
function fibonacci(num) {
let fib = [1,1];
for (let i = 2; i <= num; i++) {
fib.push(fib[i-1] + fib[i-2]);
}
return fib;
}
console.log(fibonacci(10));
Complete javascript newbie here. I need help with a homework project. I have this work and displays up to the x (for easier display) Fibonacci numbers.
Here is the results from the above code: [ 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89 ]
What I want to be able to do is specify the starting number/point (>=10, for example), and have it only display numbers from that point going forward.
So if my input number is 10, I want this result [ 13, 21, 34, 55, 89 ].
Use array filter and in the callback function return those element which are greater than the number passed as argument
function fibonacci(num) {
let fib = [1, 1];
for (let i = 2; i <= num; i++) {
fib.push(fib[i - 1] + fib[i - 2]);
}
return fib.filter(function(item) {
return item > num
});
}
console.log(fibonacci(10));
just add another variable then
function fibonacci(num) {
let result = [];
let fib = [1,1];
for (let i = 2; i <= num; i++) {
let temp = fib[i-1] + fib[i-2];
fib.push(temp);
if(result>=num)
result.push(temp)
}
return result;
}
You may also want to define a limit to stop. The rest is pretty much similar to your existing code
function fibonacci(num, limit) {
let fib = [1,1];
for (let i = num; i <= limit; i++) {
fib.push(fib[i-1] + fib[i-2]);
}
return fib;
}

Count number of values in array between two input values

As the title suggests, I want to create a function the counts the number of values in my array between two values that have been entered by the user. So for example, if the array was [1, 4, 6, 7, 8, 6] and the user entered 5 as their first value and 7 as their second value, they would be greeted with an alert that said
"total number of values = 3".
You can create an extremely clean solution to this problem by utilizing the second property of Array#filter (which sets the this binding given to your callback of choice):
var array = [1, 4, 6, 7, 8, 6]
function inRange (x) {
return this[0] <= x && x <= this[1]
}
var result = array.filter(inRange, [5, 7]).length
console.log('Total number of values:', result)
All you need is a simple for loop.
var total = 0;
var num1 = 5;
var num2 = 7;
var array = [1,4,6,7,8,6];
for(var a = 0; a < array.length; a++) {
if(array[a] >= num1 && array[a] <= num2) {
total++;
}
}
alert("Total numbers of values = " + total);
This will loop through the array, detect nums within the range, tally up a value, and output it in a alert.
You can use Array.prototype.filter(), RegExp.prototype.test() with RegExp constructor with class from-to, where from is 5, to is 7, get .length of resulting array
var from = 5;
var to = 7;
var len = arr.filter(RegExp.prototype.test.bind(new RegExp(`[${from}-${to}]`))).length;
You can alternatively use .toString(), .match()
var arr = [1,4,6,7,8,6];
var from = 5;
var to = 7;
var res = arr.toString().match(new RegExp(`[${from}-${to}]`, "g"));
var len = res.length;
console.log(res.length);
You may do as follows;
var arr = [1,4,6,7,8,6],
input = [5,7],
result = arr.reduce((r,n) => n >= input[0] && n <= input[1] ? ++r : r, 0);
console.log(result);
var array = [1, 4, 6, 7, 8, 6];
function countNumber(arr,a,b){
let count = 0;
for (const number of arr){
if (number >= a && number <= b){
count ++;
}
}
return count;
}
console.log(countNumber(array, 5, 7));

The numbers in my javascript will not add

So I need the code to use addition on random numbers in the array. If the sum is greater then ten, it should say "over" else it would be "under."
`
function arraries(){
var oneten = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
document.getElementById('demo').innerHTML = addy(oneten);
}
function addy(oneten){
var n;
var output;
var sum = "";
for (i = 0; i < 4; i++){
n = Math.floor((Math.random() * 10) + 1);
sum += parseFloat(oneten[n])}
if (sum > 10){
return "over";
}
else { return "under";}
}
The problem here is that the debugger decipher the numbers as strings. While running the sum would equal "1234" instead of 10 (which is 1 + 2 + 3 + 4) and thus it will always return "over". How can I make sure that the data will be treat as actually numbers instead of strings? I used parseFloat and parseInt but I got the same results
Mabybe you can try to set sum = 0, because like this js will concatenate into a string instead of into a int
Shouldn't you declare the sum variable as a number? Also, you don't need parseFloat function, the oneten array elements are already typeof number.
Another thing - Math.random() * 10) + 1 loss numbers from the 1 - 10 range and in your case it will return undefined because there's no item in the oneten array with index 10. Use Math.random() * 10 instead, which will return numbers from 0 - 9 range.
function arraries() {
var oneten = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
document.getElementById('demo').innerHTML = addy(oneten);
}
function addy(oneten) {
var n;
var output;
var sum = 0;
for (i = 0; i < 4; i++) {
n = Math.floor((Math.random() * 10));
sum += oneten[n];
}
console.log(sum);
if (sum > 10) {
return "over";
} else {
return "under";
}
}
arraries();
<p id='demo'></p>
type coercion in javascript
var s = "1";
var i = 1;
var i = i+1;
// 2 int + int = int
var s2 = s+1;
// "11" str + int = str
var s3 = i+"1";
// "11" int + str = str

Categories

Resources