Adding new unique number to the array [duplicate] - javascript

This question already has answers here:
How to randomize (shuffle) a JavaScript array?
(69 answers)
Closed 8 years ago.
I have array of few random numbers ( I do not know which ones it's going to be and how many of them, but it's mainly in range from 1 to 15, should not be more )
How to add new random number to this which should be as close as possible to this range and which will be unique ( can not be the same as one of the existing numbers )?
It's in javascript, example array:
var myarray = [4,5,1,9,6];

A function like this should work:
function addRandom(array, max)
{
if(array.length === max) {
return array;
}
var number = Math.round(Math.random() * (max - 1)) + 1;
if(array.indexOf(number) === -1) {
array.push(number);
return array;
}
return addRandom(array, max);
}
This takes your starting array and a maximum random integer. If the length of the array is already equal to the max integer, then the array is full and you won't ever find a new one. Otherwise, we make a new random number between 1 and the maximum.
To do this, we use Math.random() (which returns a float from 0-1), multiply it by one less the maximum, round the result with Math.round(), and add 1. If you say our max is 15, then this takes a float from 0 to 1 and multiplies it by 14 so you get 0 to 14. This is then rounded to an integer and we add 1 so we have a range of 1 to 15.
Finally, we use Array.indexOf() (IE 9+) to see if the number already exists. If it doesn't, then we use Array.push() to append the number and then return the new array. Otherwise, we will run the function again and generate a new number.
Use my JSFiddle to test this. I start with an array with length 5, and loop through it 15 times. You will see in the console that a random number is appended each time until every number is generated. An example out put is:
[4, 5, 1, 9, 6, 8]
[4, 5, 1, 9, 6, 8, 15]
[4, 5, 1, 9, 6, 8, 15, 2]
[4, 5, 1, 9, 6, 8, 15, 2, 3]
[4, 5, 1, 9, 6, 8, 15, 2, 3, 12]
[4, 5, 1, 9, 6, 8, 15, 2, 3, 12, 14]
[4, 5, 1, 9, 6, 8, 15, 2, 3, 12, 14, 7]
[4, 5, 1, 9, 6, 8, 15, 2, 3, 12, 14, 7, 11]
[4, 5, 1, 9, 6, 8, 15, 2, 3, 12, 14, 7, 11, 10]
[4, 5, 1, 9, 6, 8, 15, 2, 3, 12, 14, 7, 11, 10, 13]
[4, 5, 1, 9, 6, 8, 15, 2, 3, 12, 14, 7, 11, 10, 13]
[...]

Related

Mutating elements in an array in Javascript

Ok so I want to subtract 9 to numbers(elements in an array) over 9:
finalCredDigits = [10, 8, 18, 9, 16, 6, 16, 5, 14, 3, 14, 6, 10, 5, 8]
Thats what I tried
finalCredDigits.forEach(arr =>{
if(arr > 9){
finalCredDigits.push(arr - 9);
}
});
Output = [10, 8, 18, 9, 16, 6, 16, 5, 14, 3, 14, 6, 10, 5, 8, 1, 9, 7, 7, 5, 5, 1]
I know its cuz the result is being pushed in the array but i want to mutate it and replace the answer with numbers over 9
If you want a similar but new array, you should use Array.map():
const finalCredDigits = [10, 8, 18, 9, 16, 6, 16, 5, 14, 3, 14, 6, 10, 5, 8];
const newFinalCredDigits = finalCredDigits.map(v => {
if (v > 9) {
return v - 9;
} else {
return v;
}
});
console.log(newFinalCredDigits.join());
console.log("Is new array?", newFinalCredDigits !== finalCredDigits);
If you want to mutate the array itself with Array.forEach(), you should use the callback's additional parameters:
const finalCredDigits = [10, 8, 18, 9, 16, 6, 16, 5, 14, 3, 14, 6, 10, 5, 8];
finalCredDigits.forEach((v, i, array) => {
if (v > 9) {
array[i] = v - 9;
}
});
console.log(finalCredDigits.join());
But functional programming usually implies preferring immutable over mutable states, so if your array is shared and we'd mutate it with Array.forEach(), it would be considered a code smell. Therefore I'd use a regular for-loop instead:
const finalCredDigits = [10, 8, 18, 9, 16, 6, 16, 5, 14, 3, 14, 6, 10, 5, 8];
{
const l = finalCredDigits.length;
for (let i = 0; i < l; ++i) {
if (finalCredDigits[i] > 9) finalCredDigits[i] -= 9;
}
}
console.log(finalCredDigits.join());
You need to assign to the array index to replace the element, not push a new element.
forEach() passes a second argument to the callback function, containing the current index. You can use this for the assignment.
const finalCredDigits = [10, 8, 18, 9, 16, 6, 16, 5, 14, 3, 14, 6, 10, 5, 8];
finalCredDigits.forEach((el, i) =>{
if(el > 9){
finalCredDigits[i] = el - 9;
}
});
console.log(finalCredDigits);
Try this
let finalCredDigits = [10, 8, 18, 9, 16, 6, 16, 5, 14, 3, 14, 6, 10, 5, 8]
finalCredDigits = finalCredDigits.map(number => {
if (number > 9) {
return number - 9
}
return number
})
console.log(finalCredDigits)

How do I turn this string into an array of numbers?

I'm writing this code where a user inputs an array in a input box, so the box pretty much contains a string that looks somewhat like this: [2, 2, 2, 2, 2, 9, 9, 9, 2, 2, 2], [2, 1, 1, 1, 1, 9, 9, 9, 1, 1, 2], [2, 1, 1,14, 1, 9, 9, 9, 1, 1, 2] etc. etc.
I want to convert this into an array of arrays of numbers so that my code can do something with this, but I'm not sure how.
Simply grabbing the value of the input box outputs something like this: '[2, 2, 2, 2, 2, 9, 9, 9, 2, 2, 2], \n[2, 1, 1, 1, 1, 9, 9, 9, 1, 1, 2], \n[2, 1, 1,14, 1, 9, 9, 9, 1, 1, 2]', and when I attempt to split it/regex replace something, either I get nothing, or I get arrays that look like this: ["2, 2, 2, 2, 2, 9, 9, 9, 2, 2, 2"]. I'm not quite sure how to fix this, and the code I am using needs it as numbers.
I don't know what to do, so any ideas would be helpful. Thanks!
You can use JSON.parse:
const str = '[2, 2, 2, 2, 2, 9, 9, 9, 2, 2, 2], \n[2, 1, 1, 1, 1, 9, 9, 9, 1, 1, 2], \n[2, 1, 1,14, 1, 9, 9, 9, 1, 1, 2]';
const arrs = JSON.parse('[' + str + ']')
console.log(arrs)

Adding one line in sudoku checker break my code

function validSolution(board){
for(i=0;i<board.length;i++){
if (new Set(board[i]).size != 9) return false
//if (new Set(getVertical(i,board)).size != 9) return false
}
return true
}
let getVertical = (num,board) => {
let result = []
for(i=0;i<board.length;i++){
result.push(board[i][num])
}
console.log(result)
return result
}
I am working on sudoku checker if I am adding the commented line of code the tests that were passing are failing :( like the first 'if' statement disappeared
sample input (should be false) and it is until adding second 'if' statement
[[5, 3, 4, 6, 7, 8, 9, 1, 2],
[6, 7, 2, 1, 9, 0, 3, 4, 8],
[1, 0, 0, 3, 4, 2, 5, 6, 0],
[8, 5, 9, 7, 6, 1, 0, 2, 0],
[4, 2, 6, 8, 5, 3, 7, 9, 1],
[7, 1, 3, 9, 2, 4, 8, 5, 6],
[9, 0, 1, 5, 3, 7, 2, 1, 4],
[2, 8, 7, 4, 1, 9, 6, 3, 5],
[3, 0, 0, 4, 8, 1, 1, 7, 9]]
The propblem is that you declare variable i without let keyword.
That means i is a global variable, so in getVertical function i store value 8 and main loop in validSolution skip to end and returns true

Mine loop doesn't work in Javascript. I have to traverse loop to array and multiply by 2

hey guys i have problem with my exercise:
"using a while loop, traverse the array and multiply each price by 2" i have this to now
var prices = [10, 15, 25, 8, 4, 55, 99, 11, 15, 25, 5, 4, 65, 5, 10, 15, 7, 8, 4, 9, 100];
while (prices < 201) {
console.log('This item costs', prices);
prices * 2
}
I don't know where the error is?
Right now you are just doing for one element. In array you have to access element with their index number. The logic for doing is that you have to loop till the end of the array and for each element have to multiply the price by 2.
I have attached the code below with proper logic.
var prices = [10, 15, 25, 8, 4, 55, 99, 11, 15, 25, 5, 4, 65, 5, 10, 15, 7, 8, 4, 9, 100];
var i=0;
//loop to double price of each element in the array
while (i < prices.length){
prices[i]=prices[i]*2;
i++;
}
console.log(prices);

Jquery difference between 2 arrays

How i can get the difference of two arrays ?
I think need compare the index and delete the position?
The array cann have letter (example Months)
// Round 1
var array1 = [];
var array2 = [10, 2, 3, 5];
//diff: 10, 2 ,3 ,5
// Round 2
var array1 = [10, 2, 3, 5];
var array2 = [10, 2, 3, 5, 2, 5, 11, 9];
//diff: 2, 5, 11, 9
// Round 3
var array1 = [10, 2, 3, 5, 2, 5, 11, 9];
var array2 = [10, 2, 3, 5, 2, 5, 11, 9, 1, 5, 12, 10];
//diff: 1, 5, 12, 10
var array1 = [10, 2, 3, 5, 2, 5, 11, 9];
var array2 = [10, 2, 3, 5, 2, 5, 11, 9, 1, 5, 12, 10];
var diffArray= array2.splice(array1.length,array2.length-array1.length);
console.log(diffArray)
assuming array1 is subArray of array2

Categories