Hello together,
I have a problem testing equality of one line of a 2D array against a possible new line.
My goal is to add a new line only if a line with the same elements does not yet exist.
To achieve this I wrote the following code:
class Evaluation {
constructor() {
this.lines = [];
}
addLines(cell) {
for (let newLine of cell.neighbors) {
// Suchen, ob es diese Zeile schon gibt
let pushIt = true;
for (let i = 0; i < this.lines.length; i++) {
let lineExists = 0;
for (let j = 0; j < newLine.length; j++) {
if (this.lines[i].includes(newLine[j])) {
//passenden Merker setzen
lineExists += 1;
}
}
if (lineExists == newLine.length) {
pushIt = false;
}
}
if (pushIt) {
this.lines.push(newLine);
}
}
}
}
cell is an object that contains a 2D array neighbors. Each element cell.neighbors[i] is an array of 4 p5.Vectors. I have 64 instances of cell objects, Evaluation.addLines is called for each of them.
The cells live in a 444 grid.
Evaluation.lines should become a list of all straight lines covering 4 cells, each line should be present once.
After calling addLines for all 64 cells Evaluation.lines is a list of all straight lines covering 4 cells, each line is present 4 times.
I do not care for the order of elements in each line and I can not ensure that the order is equal in 2 representations of any given line.
That is why I thought it would be a good idea to loop over all existing lines (for(let i…) with a nested inner loop (for(let j…) where I count how many of the vectors in newLine are present in that particular existing line.
If all Vectors are present (lineExists == newLine.length) I set the pushIt-flag false to not push that line into the lines-array.
While debugging I saw that sometimes pushIt is set to false, but after adding the neighbors of all 64 cells I still get 304 lines instead of the 76 lines I expect.
Can anybody tell me where my error lies and point me in the right direction please?
Best regards from Germany
PS: I edited the title to include “of vectors”