Related
For a project we need to check if all numbers in a card, match another card with drawn numbers.
When hardcoded with a const checkCard = card001 it goes well with .every.
When trying to choose the card a dynamic way, pulling the number from a localStorage (e.g. const card = 'card'+cardNumber), an error pops up with t.every is not a function.
The question: how to make this dynamic. We hope someone is able to help to overcome this issue.
checkCard = () => {
var cardNumber = localStorage.cardNumber;
const card001 = [14, 4, 10, 8, 12, 30, 28, 23, 16, 27, 41, 35, 43, 39, 53, 57, 46, 48, 56, 74, 68, 75, 70, 66]
const card002 = [15, 13, 8, 1, 12, 26, 20, 19, 28, 24, 38, 42, 33, 41, 59, 53, 60, 55, 51, 68, 62, 71, 70, 65]
const card003 = [11, 5, 4, 13, 9, 23, 27, 16, 18, 26, 44, 38, 40, 36, 53, 47, 56, 55, 50, 69, 65, 63, 61, 74]
const previousCallList = JSON.parse(JSON.stringify(this.previousCallList));
console.log('previousCallList: ', previousCallList)
const previousCallListNumber = JSON.parse(JSON.stringify(this.previousCallListNumber));
console.log('previousCallListNumber: ', previousCallListNumber)
//const card = 'card'+cardNumber;
const checkCard = card001
const checkDrawn = previousCallListNumber ;
const containsAll = checkCard .every(element => {
return checkDrawn.includes(element);
});
console.log(containsAll); // 👉️ true
}
}
There's a difference between these two lines:
// Point `checkCard` to the current array stored in `card001`
const checkCard = card001
// Point `checkCard` to a string "card001"
const checkCard = "card001"
When you write 'card'+cardNumber, you're creating a new string, not a reference to another variable.
If you want to dynamically pick a variable based on its name, you can define named properties on an object. For example:
const myObject = {
a: 1,
b: 2,
c: 3
};
console.log(
myObject["a"],
myObject["b"],
myObject["c"]
)
Or, with your data:
const cardNumber = "001";
const card001 = [14, 4, 10, 8, 12, 30, 28, 23, 16, 27, 41, 35, 43, 39, 53, 57, 46, 48, 56, 74, 68, 75, 70, 66]
const card002 = [15, 13, 8, 1, 12, 26, 20, 19, 28, 24, 38, 42, 33, 41, 59, 53, 60, 55, 51, 68, 62, 71, 70, 65]
const card003 = [11, 5, 4, 13, 9, 23, 27, 16, 18, 26, 44, 38, 40, 36, 53, 47, 56, 55, 50, 69, 65, 63, 61, 74]
const cardVarName = "card" + cardNumber;
log(cardVarName); // This is now the string "card001", not a reference to the card001 variable
// Store the cards in an object
const cards = { card001, card002, card003 };
// Reference a card using obj[propertyName]
log(cards[cardVarName])
function log(x) { console.log(JSON.stringify(x)); }
If you intend to use localStorage you need to familiarize yourself with the syntax, what you have now...
localStorage.cardNumber;
...should've given you an error. The following are two functions that get and set data to and from localStorage:
/*
>key< is a string assigned as an id to stored data.
If there isn't anything stored an empty array is returned/
*/
const getLS = key => JSON.parse(localStorage.getItem(key)) || [];
/*
>key< is same as above. >data< is the value that needs to
be stored.
*/
const setLS = (key, data) => localStorage.setItem(key, JSON.stringify(data));
Note that LS only stores strings which is why JSON.parse() and JSON.stringify() are used on the data. In the example the
lines concerning LS are commented out because SO snippets prohibit them -- just uncomment them when you test them in a normal environment.
Details are commented in example below
// Utility function
const log = data => console.log(JSON.stringify(data));
//const getLS = key => JSON.parse(localStorage.getItem(key)) || [];
//const setLS = (key, data) => localStorage.setItem(key, JSON.stringify(data));
/*
All arrays as parameters so function can be reusable
*/
const deckA = [14, 4, 10, 8, 12, 30, 28, 23, 16, 27, 41, 35, 43, 39, 53, 57, 46, 48, 56, 74, 68, 75, 70, 66];
const deckB = [15, 13, 8, 1, 12, 26, 20, 19, 28, 24, 38, 42, 33, 41, 59, 53, 60, 55, 51, 68, 62, 71, 70, 65];
const deckC = [11, 5, 4, 13, 9, 23, 27, 16, 18, 26, 44, 38, 40, 36, 53, 47, 56, 55, 50, 69, 65, 63, 61, 74];
/**
* find match between a given number and a
* number from one or more given arrays
* #param {number} card = Number to find
* #param {arrays} cards = One or more arrays
* #returns {array<object>} Each object is
* created like this:
* {card: 55, row: 2, col: 17}
* "card 55 is in the 3rd array index 17"
*/
const findMatch = (card, ...cards) => {
//const data = getLS('cards');
//data.push(card);
//setLS('cards', data);
// Gather ...cards into an array:
// [ [deckA], [deckB], [deckC] ]
const decks = [...cards];
/*
First, .map() runs through each sub-array and
.flatMap() compares each number of each sub-
array vs. card. If there's a match, return
a new object (see above) otherwise an empty
array is returned
*/
return decks.map((sub, row) => sub.flatMap((num, col) => num === card ? {card: card, row: row, col: col} : [])).flat();
};
log(findMatch(55, deckA, deckB, deckC));
log(findMatch(3, deckA, deckB, deckC));
log(findMatch(25, deckA, deckB, deckC));
log(findMatch(13, deckA, deckB, deckC));
I was trying to solve this problem with backtracking instead of DP...and ran into a problem that doesn't make sense to me. here is my code
function solve(A) {
let lp = 0;
const path = [];
const traverse = function (arr, i = 0) {
if (i >= arr.length) return;
for (j = i; j < arr.length; j++) {
if (path.length === 0 || arr[j] > path[path.length - 1]) {
path.push(arr[j]);
// here is the problem I don't understand, I am calling the recursive function with( j + 1)
// but somehow that reads it as j = j + 1; why is this happening?
// I would understand if it was an Array where the j would pointing to memory but it shouldn't // happen to a regular number, right?
traverse(arr, j + 1);
// this causes the j variable in the for loop to increment by 1 so I can't get back track properly.
if (path.length > lp) lp = path.length;
path.pop();
}
}
}
traverse(A);
return lp;
}
const A = [69, 54, 19, 51, 16, 54, 64, 89, 72, 40, 31, 43, 1, 11, 82, 65, 75, 67, 25, 98, 31, 77, 55, 88, 85, 76, 35, 101, 44, 74, 29, 94, 72, 39, 20, 24, 23, 66, 16, 95, 5, 17, 54, 89, 93, 10, 7, 88, 68, 10, 11, 22, 25, 50, 18, 59, 79, 87, 7, 49, 26, 96, 27, 19, 67, 35, 50, 10, 6, 48, 38, 28, 66, 94, 60, 27, 76, 4, 43, 66, 14, 8, 78, 72, 21, 56, 34, 90, 89]
const B = [1,3,4,2,5,3]
console.log(solve(A))
console.log(solve(B))
an explanation would be appreciated, thanks in advance!!!
So this the function code i came up with I do not know what is wrong with it.
It keeps giving 0 as my code.
function minValue(array) {
let min = 0;
for (let i = 0; i < array.length; i++) {
for (let j = 0; j < array[i].length; j++) {
if (array[j][i] == "string") {
min = Math.min(min, parseInt(array[j][i]));
} else {
min = Math.min(min, array[j][i]);
}
}
}
return min;
}
let matrix = [
[57, 71, 37, 99, 62, '83', '95', '54', 38, 25],
[8, 64, 100, '51', 43, 21, 21, 33, 11, 43],
[67, 25, 45, 67, 88, 72, 74, 77, 53, 38]
];
console.log(minValue(matrix));
I keep on getting 0 as my answer.
Your function doesn't work because you use 0 as the initial value, and it's smaller than all other values. Use Infinity as the initial value.
Note: you've switch between i and j here - array[j][i]. I would also remove the condition, and always convert to number (I've used the + operator here).
function minValue(array) {
let min = Infinity;
for (let i = 0; i < array.length; i++) {
for (let j = 0; j < array[i].length; j++) {
min = Math.min(min, +array[i][j]);
}
}
return min;
}
const matrix = [
[57, 71, 37, 99, 62, '83', '95', '54', 38, 25],
[8, 64, 100, '51', 43, 21, 21, 33, 11, 43],
[67, 25, 45, 67, 88, 72, 74, 77, 53, 38]
];
console.log(minValue(matrix));
Another options is to flatten matrix to a single array, map all items to numbers, and spread into Math.min():
const minValue = array => Math.min(...array.flat().map(Number));
const matrix = [
[57, 71, 37, 99, 62, '83', '95', '54', 38, 25],
[8, 64, 100, '51', 43, 21, 21, 33, 11, 43],
[67, 25, 45, 67, 88, 72, 74, 77, 53, 38]
];
console.log(minValue(matrix));
I'm trying to get my code to do this:
Original array = [1,2,3,4] swap once-> [4,2,3,1] swap again->[4,3,2,1]
Therefore result is 2
But it's not working. Here's what I have so far:
function check(arr){
var sarr = [];
var cnt = 0;
var arrL = arr.length;
// Create a second copy of the array for reference
var arrCopy = [...arr];
for(let i=0; i<arrL;i++){
var maxV = Math.max(...arr);
sarr.push(maxV);
let pos = arr.indexOf(maxV);
// Remove the found number
arr.splice(pos,1);
// Check if the index of the number in the new array is same with the copy, if not then there was a swap
let ai =arrCopy.indexOf(maxV);
let si =sarr.indexOf(maxV);
if (ai !== si && (i+1)!=arrL && pos !== 0){
cnt++;
};
}
console.log(cnt);
}
check([1, 2, 3, 4, 5, 6]);//Result should be 3
check([6,5,4,3,2,1]); //result should be 0
check([1,2,3,4]); //result should be 2
check([1,3,2,5,4,6]); //result should be 3
check([1,2,10,4,5,6,7,8,9,3,12,11]);//result should be 6
check([ 49, 37, 9, 19, 27, 3, 25, 11, 53, 42, 57, 50, 55, 56, 38, 48, 6, 33, 28, 8, 20, 31, 51, 14, 23, 4, 58, 52, 36, 22, 41, 47, 39, 2, 7, 13, 45, 1, 44, 32, 10, 15, 21, 30, 17, 60, 29, 5, 59, 12, 40, 24, 54, 46, 26, 43, 35, 34, 18, 16]);//result should be 54
Can someone please let me know what I'm doing wrong?
I would start with a copy of the array in descending order for getting the right index of the items.
For practical reasons, (or just a shorter conception of the loop with including check and decrement), I loop from the end of the array.
Then I check the value of array and reversed at the dame index and go on with the iteration.
If not the same value, the items at the wanted position i and the actual position p are swapped and the count incremented.
At the end the count is returned.
function check(array) {
var reversed = array.slice().sort((a, b) => b - a),
count = 0,
i = array.length,
p;
while (i--) {
if (array[i] === reversed[i]) continue;
p = array.indexOf(reversed[i]);
[array[i], array[p]] = [array[p], array[i]];
count++;
}
console.log(...array);
return count;
}
console.log(check([1, 2, 3, 4, 5, 6])); // 3
console.log(check([6, 5, 4, 3, 2, 1])); // 0
console.log(check([1, 2, 3, 4])); // 2
console.log(check([1, 3, 2, 5, 4, 6])); // 3
console.log(check([1, 2, 10, 4, 5, 6, 7, 8, 9, 3, 12, 11])); // 6
console.log(check([ 49, 37, 9, 19, 27, 3, 25, 11, 53, 42, 57, 50, 55, 56, 38, 48, 6, 33, 28, 8, 20, 31, 51, 14, 23, 4, 58, 52, 36, 22, 41, 47, 39, 2, 7, 13, 45, 1, 44, 32, 10, 15, 21, 30, 17, 60, 29, 5, 59, 12, 40, 24, 54, 46, 26, 43, 35, 34, 18, 16])); // 54
.as-console-wrapper { max-height: 100% !important; top: 0; }
function minimumSwaps(arr) {
var count = 0;
arr.sort((a, b) => {
if (a < b) {
count++;
}
});
return count;
}
console.log(minimumSwaps([1, 2, 3, 4, 7, 6, 5]));
I have the following code in a test case on jsPerf:
var arr = [0, 45, 96, 8, 69, 62, 80, 91, 89, 24, 6, 23, 49, 88, 26, 40, 87, 61, 83, 2, 60, 53, 43, 82, 67, 3, 65, 37, 42, 77, 73, 38, 9, 46, 75, 10, 63, 15, 47, 28, 79, 55, 59, 95, 11, 93, 70, 98, 25, 48, 30, 5, 72, 12, 84, 1, 29, 13, 50, 33, 19, 7, 31, 57, 32, 44, 74, 51, 35, 90, 86, 54, 4, 64, 92, 71, 22, 41, 16, 17, 27, 76, 39, 18, 99, 94, 36, 66, 85, 20, 21, 56, 34, 81, 14, 78, 68, 58, 97, 52];
Array.prototype.remove = function(from, to) {
var rest = this.slice((to || from) + 1 || this.length);
this.length = from < 0 ? this.length + from : from;
return this.push.apply(this, rest);
};
function quicksort( arr ) {
if ( arr.length <= 1 )
return arr;
var i = 0,
len = arr.length,
less = [],
greater = [],
random = Math.floor( Math.random() * len ),
pivot = arr[ random ];
arr.remove( random );
for ( ; i < len - 1; i++ ){
if ( arr[ i ] <= pivot )
less.push( arr[ i ] );
else
greater.push( arr[ i ] );
}
return quicksort( less ).concat( pivot, quicksort( greater ) );
};
If you copy that into your console and run quicksort( arr ), you'll see that it correctly returns a sorted array.
But for some reason, in this test case on jsPerf, my quicksort function seems to be returning only a single number ( as can be seen in 'Perparation Code Output' ). It also seems to be running way faster than it probably should.
Anybody ideas into what's going on would be greatly appreciated.
I think the problem is that you're calling that .remove() function on the original array, so it quickly strips it down to nothing. In other words, each initial call to the quicksort function removes an element.
When I make it create a copy of the array first, then it seems to work.