I encountered an interesting challenge recently.
The task was to create a bracelet of length n using a set of specified colors, following certain conditions:
- No two adjacent beads should have the same color (e.g., R R).
- A pattern of three consecutive beads should not be repeated in the bracelet (e.g., R G B Y R G B, R G R G R).
Given input - colors = ["R", "G", "B", "Y"], n = 8
Expected output - ["R", "G", "B", "Y", "R", "G", "R", "Y"]
If it is not possible to form a bracelet of length n
, the function should return false
.
After pondering on the problem, I came up with the following solution:
function generateBracelet(colors, n) {
const bracelet = [colors[0]];
const threeBeads = {};
const cLen = colors.length;
let j = 1;
while (n > bracelet.length) {
let bLen = bracelet.length;
if (bracelet[bLen - 1] === colors[j]) {
console.log("hasSameAdjecent");
j++;
j === cLen && (j = 0);
continue;
}
const newThree = bracelet.slice(bLen - 2, bLen).join("") + colors[j];
console.log(newThree);
if (Object.keys(threeBeads).length && threeBeads[newThree]) {
console.log("hasThree");
j++;
j === cLen && (j = 0);
continue;
}
bracelet.push(colors[j]);
bLen = bracelet.length;
bLen >= 3 && (threeBeads[bracelet.slice(bLen - 3, bLen).join("")] = 1);
j++;
j === cLen && (j = 0);
}
console.log(threeBeads);
return bracelet;
}
console.log(generateBracelet(["R", "G", "B", "Y"], 8));
//["R", "G", "B", "Y", "R", "G", "Y", "R"]
This led to the inevitable question: "Is there a way to optimize this solution?"
I am still contemplating the best approach to tackle this problem.
Any suggestions or alternative solutions would be greatly appreciated.