I have a list of co-ordinates of squares of a grid: Grid
Each square is defined by a class:
class Square {
constructor(x, y) {
this.x = x;
this.y = y;
}
}
This is how the app works: First there is a list of randomly generated squares shown, and then the user has to click the squares from memory. (Not necessarily in order)
An example of how the question/answer array would be: (just an example, they are actually randomly generated)
const arr = [new Square(1, 1), new Square(2, 1)]
now, whenever the user clicks on a box, it goes into another array:
var selectedBlocks = [new Square(2, 1), new Square(1, 1)]
In this case, since the squares selected are equal, the function should return true.
What I've tried - I can't manage to get it without a double-for loop O(n^2). Is it possible to optimise for atleast O(n)?
-
what about this scenario: you store just x and y into the arr constant like this-> ["1,2","1,1"], when the user clicks on each square you can check the current selected like this arr.includes(selected), I mean don't store whole selected, validate that on each user selectbarzin.A– barzin.A2021年12月31日 04:50:34 +00:00Commented Dec 31, 2021 at 4:50
-
You can just track what user select. when the user select a square check whether that is right or wrong and if user select the wrong one just return false. don't compare at the end of selection, do as per selection by userJayamal Jayamaha– Jayamal Jayamaha2021年12月31日 04:52:48 +00:00Commented Dec 31, 2021 at 4:52
3 Answers 3
I forgot that there were few built in methods and i wrote this i guess (nlogn) Time complexity code
class Square {
constructor(x, y) {
this.x = x;
this.y = y;
}
pri(){
return this.x + this.y;
}
}
let inp = [new Square(2,1), new Square(2,3), new Square(1,3)]
let opt = [new Square(1,3), new Square(2,1), new Square(2,3)]
inp.sort((a, b) => {
return a.pri() - b.pri();
});
opt.sort((a, b) => {
return a.pri() - b.pri();
});
// assuminng they are of same len
let flag = true
for(i=0; i<inp.length ; i++){
if(inp[i].x != opt[i].x || inp[i].y != opt[i].y){
flag = false
break
}
}
console.log(flag)
3 Comments
You can use Array.some to find is item already selected or not
class Square {
constructor(x, y) {
this.x = x;
this.y = y;
}
}
const arr = [new Square(1, 1), new Square(2, 1)];
const selectedBlocks = [new Square(2, 1), new Square(1, 1)];
const isSelected = (block) => {
return selectedBlocks.some(
(item) => item.x === block.x && item.y === block.y
);
};
console.log(isSelected(new Square(2, 1)));
console.log(isSelected(new Square(2, 2)));
console.log(isSelected(new Square(1, 1)));
1 Comment
Quoting from the answer on another question, the answers to that one may also help. If you just need to know whether A and B has same entries, simply use
JSON.stringify(A.concat().sort()) === JSON.stringify(B.concat().sort())
Link to the original answer is here.