create array by conditions - javascript

I want to insert numbers to an array by the next following:
the number should be between 1-5
the first number can't be 1, the second can't be 2, etc..
chosen number can't be inserted to another index
for example:
[1,2,3,4,5]
I randomize the first number: 1 [condition 2 doesn't exists: 1 can't be in the first index, so I randomize again and got 4).
so new array:
0 - 4
1 -
2 -
3 -
4 -
I randomize a number to the second cell and got 4, but 4 was inserted to the first element [condition 3], so I randomize again and got 2, but 2 can't be the second element [condition 2], so I randomize again and got 5.
0 - 4
1 - 5
2 -
3 -
4 -
etc
I tried to init a vec by the numbers (1-5):
var array = new Array();
array[0] = 1;
array[1] = 2;
array[2] = 3;
array[3] = 4;
array[4] = 5;
var newarr = new Array();
function getRandomInt (min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
$(document).ready(function() {
for (var i = 0; i < 5; i++) {
var rand;
// check condition 2
while((rand = getRandomInt(1, 5)) == (i+1));
newarr[i] = rand;
//array.splice(i, 1);
}
// print the new array
for (var i = 0; i < 5; i++) {
alert((i+1) + '->' + newarr[i]);
}
});
but I need to add condition 3 to my code,
any help appreciated!

Try this:
$(document).ready(function() {
for (var i = 0; i < 5; i++) {
var rand;
// check condition 2
while((rand = getRandomInt(1, 5)) == (i+1) || $.inArray(rand, newarr)) // Also check, if generated number is already in the array
newarr[i] = rand;
//array.splice(i, 1);
}
// print the new array
for (var i = 0; i < 5; i++) {
alert((i+1) + '->' + newarr[i]);
}
});
But beware. If you generate for example this array:
[2, 1, 4, 3]
You will end up having an endless while loop, since the only available number is 5, but it can't be inserted in that position.

var values = [1,2,3,4,5];
var output = [];
for(var i=0;i<5;i++)
{
do{
var index = Math.floor(Math.random() * values.length);
}while(values[index] == i +1);
output[i] = values[index];
values.splice(index, 1);
}
console.log(output);
Demo : http://jsfiddle.net/aJ8sH/

Related

JavaScript how to modify numbers in array

I'm want to generate an array with 5 random numbers from 1 to 100, then check if the number is even, if not I want to modify it by adding 1.
EXAMPLE:
array = [7, 13, 2, 60, 93]
And the outcome should be
modified_array = [8, 14, 2, 60, 94] but I'm stuck..
I'd appreciate it if somebody will help me with fixing it. Thanks!
const array = []
const modified_array = []
while (array.length < 5) {
i = (Math.floor(Math.random() * 100) + 1);
array.push(i);
for (i in array);
if (i % 2 !== 0) {
modified_array.push(i)
}
}
console.log("array");
console.log(array);
console.log("-------------------------")
console.log("modified_array");
console.log(modified_array);
Why not take the half max value and multiply with 2?
const array = [];
while (array.length < 5) {
array.push(2 * (Math.floor(Math.random() * 50) + 1));
}
console.log(...array);
You just need one variable and one for loop to work with this solution. When you are appending the element to the array just check it then if it is even. If it is not then just increment its value
for(i = 0; i<5; i++) {
array.push((Math.floor(Math.random() * 100) + 1))
if(array[i] % 2 != 0) {
array[i] += 1
}
}
console.log(array)
Just add 1 to the current value if it is not an even number else add the value as it is to the modified array.
const array = []
const modified_array = []
while (array.length < 5) {
i = (Math.floor(Math.random() * 100));
array.push(i);
if (i % 2 !== 0) {
modified_array.push(i + 1);
}else{
modified_array.push(i);
}
}
console.log(...array);
console.log(...modified_array);

Change given amount of money to bills

Change the given amount of money into minimum number of bills.
Inputs:
Amount: positive integer;
Bills: a sorted list of distinct positive integers (e.g. [1, 5, 10]).
Assumptions:
Amount does not exceed 100.
At most 4 bill values.
Must return 0 if the amount cannot be changed.
Examples:
Amount: 17, bills: [1, 5, 10], answer: 4 -> 10+5+1+1
Amount: 17, bills: [2, 4], answer: 0
Here's the code I have so far
function sort(array) {
for (var i = array.length - 1; i >= 0; i--) {
for (var j = 0; j < i; j++) {
if (array[j + 1] > array[j]) {
var z = array[j];
array[j] = array[j + 1];
array[j + 1] = z;
}
}
}
return array;
}
function change(amount, bills) {
sort(bills);
var result = [];
while (amount > 0) {
for (var i = 0; i < bills.length; i++) {
if (amount >= bills[i]) {
amount -= bills[i];
result.push(bills[i]);
i--;
}
}
}
return result.length;
}
console.log(change(17, [1, 5, 10])); // Expect: 4
console.log(change(17, [2, 4])); // Expect: 0
console.log(change(18, [2, 4])); // Expect: 5
//console.log(change(17, [3, 5])); // Expect: 5
There are 2 problems
One is that if the amount cannot be divided it doesn't return 0 but just lags out because it's an infinite loop.
Second is that in the last example, 17,[3,5] my code takes the 5 3 times and then realises that it can't do the remaining 2 and lags out, instead of doing 3 4 times and adding a 5.
Would really appreciate suggestions, or fixed code. Please keep it fairly simple I am just a starter.
If fixed your change function and added comments to explain my changes, let me know if you have any doubts
function change (amount, bills) {
//Asign sorted array of bills to possibleBills
var possibleBills = sort(bills);
var result = [];
//Asign amount to currentAmount
var currentAmount = amount;
//Sort through possibleBills
for (var i = 0; i < possibleBills.length; i++) {
//Perform action inside while loop if the current bill value can be substracted from currentAmount
while (currentAmount - possibleBills[i] >= 0) {
currentAmount -= possibleBills[i];
result.push(possibleBills[i]);
//End loop and return the length of result if currentAmount reaches 0
if (currentAmount === 0) {
return result.length;
}
}
}
//Return 0 if the amount couldn't be changed with the given bills
if (currentAmount > 0) {
return 0;
}
return result.length;
};
function change(amount, bills) {
const billsDesc = bills.sort((a, b) => b - a);
const give = {}
let remaining = amount;
for (const bill of billsDesc) {
const qty = Math.floor(remaining/bill);
give[bill] = qty;
remaining -= qty*bill;
}
give.totalQty = Object.values(give).reduce((curr, prev) => curr + prev, 0);
return remaining === 0? give.totalQty : 0;
}
console.log(`${change(17, [1, 5, 10])} should equal 4`);
console.log(`${change(17, [2, 4])} should equal 0`);
console.log(`${change(18, [2, 4])} should equal 5`);

How to get all possible combinations of an integer array items?

I have an array of numbers. In this array each number is repeating for "r" times.
This function is generating the array:
var n = 8;
var k = 4;
var r = 3;
var comb = n * r / k;
function getNumbers() {
var array = new Array();
for (i = 0; i < r; i++) {
for (j = 0; j < n; j++) {
array.push(j);
}
}
return array;
}
The numbers from this array I want to split them in "comb=n*r/k" uniq small arrays with the length of k;
for this I made the following function:
function InsertNumber(array) {
var finalarray = GetArrays(comb);
for (j = 0; j < array.length; j++) {
for (i = 0; i < finalarray.length; i++) {
if (ContainX(array[j], finalarray[i])) {
if (finalarray[i].length <= k) {
finalarray[i].push(array[j]);
Console.log(array[j]);
var index = array.indexOf(array[j]);
array.splice(index, 1);
InserNumber(array);
}
}
}
}
ShowTable(finalarray);
}
function GetArrays(x) {
var array = new Array();
for (i = 0; i < x; i++) {
var smallArray= new Array();
array.push(smallArray);
}
return array;
}
function ContainX(array,element) {
var result = false;
for (i = 0; i < array.length; i++) {
if (element === array[i]) {
result = true;
}
}
return result;
}
finaly I want to display all the small arays items in a table using this function:
function ShowTable(array) {
document.write("<table>")
for (i = 0; i < array.lenght; i++) {
document.write("<tr>")
for (j = 0; j < array[i].legth; j++) {
document.write("<td>" + array[i][j] + "</td>")
}
document.write("</tr>")
}
document.write("</table>")
}
I think that the step by step algorithm to get the expected result may be ok, but I am not able to see the result in browser because of the recursive function InsertNumber().
Can you help me with a better method to generate all combinations of all numbers in an array, where the the array items may repeat for r times?
I am open for any solution which can fix my issue.
Edit:
Exemple: mainArray=[0,0,1,1,2,2];
I want to split this array in:
arr1=[0,1];
arr2=[0,2];
arr3=[1,2];
this 3 arrays are containing all items of mainArray and are uniq!!!.
In this exemple: n=3, k=2, r=2, comb=n*r/k=3;
n=total unique numbers from `mainArray [0,1,2]`;
k=length of small arrays
r= number of repetition of each unique n;
comb= the number of small arrays;
**Edit2- Exemple2:**
mainArray=[0,0,1,1,2,2,3,3,4,4]
arr1=[0,1];
arr2=[0,2];
arr3=[1,3];
arr4=[2,4];
arr5=[3,4];
n=5, unique numbers in main array;
k=2, length of small array;
r=2, repetition of each number in main array;
comb=5*2/2=number of combinations which must result!.
(all the items from mainArray are spllited in small arr is such a way to not have small array with same items)
This proposal works with an array and a given length for the part array.
Distribution of values with length = 2
0 0 1 1 2 2 3 3 4 4
0 1
0 2
1 3
2 4
3 4
Distribution of values with length = 3
0 0 0 1 1 1 2 2 2 3 3 3 4 4 4 5 5 5 6 6 6 7 7 7
0 1 2
0 1 3
0 2 4
1 3 5
2 4 6
3 5 7
4 6 7
5 6 7
The key feature is to splice the used value and increase the position with length - 1 for the next item to push to the part array. If the position p is outside of the array, then the position is set to the last element of the array.
function getParts(array, length) {
var r = [],
values,
i, p;
while (array.length > length) {
values = [];
p = 0;
for (i = 0; i < length; i++) {
if (p >= array.length) {
p = array.length - 1;
}
values.push(array.splice(p, 1)[0]);
p += length - 1;
}
r.push(values);
}
r.push(array);
return r;
}
function print(o) {
document.write('<pre>' + JSON.stringify(o, 0, 4) + '</pre><hr>');
}
print(getParts([0, 0, 1, 1, 2, 2], 2));
print(getParts([0, 0, 1, 1, 2, 2, 3, 3, 4, 4], 2));
print(getParts([0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6, 7, 7, 7], 3));

Creating "m x n" Two Dimensional array in javascript

Would like to create a two dimensional m x n array in javascript, based on the number of columns, that is inputed as an argument in my function, the rows would be created from another argument which would be an array.
What I look to achieve - Desired Result:
var arr = [0,1,2,3,4,5,6,7,8,9]
function TwoDimensionalArray(numRows, numCols) {
//Magic happens here!
}
TwoDimensionalArray(arr, 4);
As you can see the is a 3 x 4 matrix below and a desired result
[[0,1,2,3], [4,5,6,7],[8,9]]
The input size doesn't make the difference, the number of columns is the key factor and the determinant factor.
What I have currently - Not Desired Result:
var arr = [0,1,2,3,4,5,6,7,8,9,10,11,12,13]
function TwoDimensionalArray(numRows, numColumns) {
var twoD = [];
for (var row = 0; row < numRows.length; ++row) {
var cardIndex = numRows[row]
// console.log(numRows[row]);
var columns = [];
for(var j =0; j < numColumns; ++j) {
columns[j] = cardIndex;
}
twoD[cardIndex] = columns;
}
return twoD;
};
var matrixTwoD = TwoDimensionalArray(arr, 4);
console.log(matrixTwoD);
console.log(matrixTwoD[0][0]);
console.log(matrixTwoD[0][1]);
console.log(matrixTwoD[0][2]);
console.log(matrixTwoD[0][3]);
My current code creates an array that repeats each of the elements 4 times each until the number 13 with a column size of 4: [[0,0,0,0], [1,1,1,1]....[13,13,13,13]]
Maybe am doing something wrong in my for loop or not approaching the problem correctly. But anything to point me in the right direction to get the above desire result.
Bouns
Also would anyone also be kinda to point me to additional resources for matrix algebra pertaining to this sort of problem and anything in general that would help for self study.
Thanks a bunch!
Keep it simple, slice the input Array into sections of numCols length
function TwoDimensionalArray(arr, numCols) {
var arr2d = [],
i;
if (numCols) // safety first!
for (i = 0; i < arr.length; i += numCols)
arr2d.push(arr.slice(i, i + numCols));
return arr2d;
}
if (numCols) prevents an infinite loop in the case numCols was not provided or is 0
for (i = 0; i < arr.length; i += numCols) counts up from 0 in numCols, e.g. i = 0, 4, 8, 16, ... until we reach a number greater than arr.length
arr.slice(i, i + numCols) creates a sub-Array of Array starting from (including) index i and ending at (excluding) index i + numCols, i.e. we get a numCols long Array starting with the item at index i of arr
arr2d.push appends a new item to the end of arr2d
Putting all these together, we can see that we are building a new Array arr2d from sections of the Array arr
calculate columns required and then use slice method of array.
start index = (numColumns * i)
end index = numColumns * (i + 1)
var arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
function TwoDimensionalArray(numRows, numColumns) {
var columns = [];
for (var i = 0; i !== Math.ceil(numRows.length / numColumns); i++) {
columns[i] = numRows.slice((numColumns * i), numColumns * (i + 1))
//console.log((numColumns * i) + " " +numColumns * (i + 1))
}
return columns;
};
var matrixTwoD = TwoDimensionalArray(arr, 4);
console.log(matrixTwoD);
console.log(matrixTwoD[0][0]);
console.log(matrixTwoD[0][1]);
console.log(matrixTwoD[0][2]);
console.log(matrixTwoD[0][3]);

Loop through looped sequence of numbers

There is an array of numbers [1,2,3,4,5,6,7,8,9,10]
I need to get all numbers from this sequence that are different from current for more than 2 items, but looped.
For example if current number is one, so new list should have everything except 9,10,1,2,3, or if current number is four so new list should be everything except 2,3,4,5,6.
Is there any technique how to make this, without creating multiple loops for items at start and at the end?
Thank you.
var a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var exclude = function (start, distance, array) {
var result = [];
for (var i = 0; i < array.length; i++) {
var d = Math.min(
Math.abs(start - i - 1),
Math.abs(array.length + start - i - 1)
)
if (d > distance) {
result.push(array[i]);
}
}
return result;
}
I think this performs what you asked:
// Sorry about the name
function strangePick(value, array) {
var n = array.length
, i = array.indexOf(value);
if (i >= 0) {
// Picked number
var result = [value];
// Previous 2 numbers
result.unshift(array[(i + n - 1) % n]);
result.unshift(array[(i + n - 2) % n]);
// Next 2 numbers
result.push(array[(i + 1) % n]);
result.push(array[(i + 2) % n]);
return result;
} else {
return [];
}
}
Some tests:
var array = [1,2,3,4,5,6,7,8,9,10];
console.log(strangePick(1, array)); // [9,10,1,2,3]
console.log(strangePick(4, array)); // [2,3,4,5,6]
You may use javascript array.slice:
function get_offset_sequence(arr, index, offset) {
var result = [];
if (index - offset < 0) {
result = arr.slice(index - offset).concat(arr.slice(0, index + offset + 1));
}
else if (index + offset > arr.length - 1) {
result = arr.slice(index - offset).concat(arr.slice(0, Math.abs(arr.length - 1 - index - offset)));
}
else {
result = arr.slice(index - offset, index + offset + 1)
}
return result;
}
Example of use:
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var index = 1;
var offset = 2;
for (var i=0; i < 10; i++) { console.log(i, arr[i], get_offset_sequence(arr, i, offset)) }

Categories