Skip to content

Instantly share code, notes, and snippets.

@netgfx
Last active October 6, 2019 06:02
Show Gist options
  • Select an option

  • Save netgfx/5057b052ec49077800a5be33b1bbbbc8 to your computer and use it in GitHub Desktop.

Select an option

Save netgfx/5057b052ec49077800a5be33b1bbbbc8 to your computer and use it in GitHub Desktop.
Pattern find in String solution
/**
The cake is round, and decorated with M&Ms in a circle around the edge. But while the rest of the cake is uniform, the M&Ms are not: there are multiple colors, and every minion must get exactly the same sequence of M&Ms. Commander Lambda hates waste and will not tolerate any leftovers, so you also want to make sure you can serve the entire cake.
To help you best cut the cake, you have turned the sequence of colors of the M&Ms on the cake into a string: each possible letter (between a and z) corresponds to a unique color, and the sequence of M&Ms is given clockwise (the decorations form a circle around the outer edge of the cake).
Write a function called answer(s) that, given a non-empty string less than 200 characters in length describing the sequence of M&Ms, returns the maximum number of equal parts that can be cut from the cake without leaving any leftovers.
**/
var pattern = "aaabbbcccddd"; //"abccbaabccba"; //"AZAZZZZAZAZZZZ"; //"aaaaabaaaaab"; //"abcabcabcabc"; //"AABBCCAABBCC";//"AZAZZZZAZAZZZZ";
var candidate = [];
var poi = 0;
var successRate = 0;
var diff = 0;
var chars;
var root;
function detectSequence() {
var test = ["A", "Z"].join("");
var test2 = pattern.split(test);;
////////////
chars = pattern.split("");
root = chars[0];
candidate.push(root);
for (var i = 1; i < chars.length; i++) {
if (chars[i] === root) {
if (candidate.length === 0) {
candidate.push(chars[i]);
} else {
if (diff !== 0) {
poi = i;
var result = checkCandidate();
if (result === true) {
break;
} else {
continue;
}
} else {
candidate.push(chars[i]);
}
}
} else {
diff += 1; // has differentiated from root at least once
candidate.push(chars[i]);
poi = 0;
}
}
window.console.log("sequence is ", candidate.join(""));
}
function checkCandidate() {
var index = 0;
successRate = 0;
for (var j = 0; j < candidate.length; j++) {
if (chars[poi + j] === candidate[index]) {
successRate += 1;
} else {
candidate.push(chars[poi]);
poi = 0;
break;
}
index += 1;
}
// double check //
var notYet = false;
var str = candidate.join("");
var parts = "|" + pattern + "|";
parts = parts.split(str);
for (var i = 1; i < parts.length - 1; i++) {
if (parts[i] !== "") {
notYet = true;
}
}
/////////////////
if (successRate === candidate.length && notYet === false) {
return true;
} else {
// to defeat false positives
if (poi !== 0) {
candidate.push(chars[poi]);
poi = 0;
}
return false;
}
}
detectSequence();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment