JSFiddle - React, Tailwind, and code Playground
by sym3tri
JavaScript
// all possible values
var possible = ['a', 'b', 'c'],
// all the inputs to process
inputs = [
'cab',
'bcab',
'ccccc',
'a',
'aa',
'ab'
];
// self executing anonymous function kicks it all off
(function (inputAry) {
// loop thru input array calling stringReduce function for each item
for (var i=0, len=inputAry.length; i < len; i++) {
alert('input: ' + inputAry[i] + ', result: ' + stringReduce(inputAry[i]));
}
// helper function to replace 2 chars with the other if valid, otherwise returns original input
function replace (char1, char2) {
if (char1 === char2) {
return char1 + char2;
}
if (!char2) {
return char1;
}
for (var i = 0; i < possible.length; i++) {
if (possible[i] !== char1 && possible[i] !== char2) {
return possible[i];
}
}
};
// main function that reduces the input string
function stringReduce(s) {
var i = 0,
tmp,
newS;
while (i < s.length-1 && s.length > 1) {
tmp = replace(s[i], s[i+1]);
if (tmp.length === 1) {
newS = s.substring(0, Math.max(0, i))
+ tmp
+ s.substring(Math.min(i+2, s.length), s.length);
s = newS;
i = Math.max(0, i-1)
}
else {
i++;
}
}
return s.length;
}
})(inputs)