From e2299d52bad7bea348e35e575d012845c8cf42ab Mon Sep 17 00:00:00 2001 From: ikhnaton Date: Wed, 24 Oct 2018 08:55:43 -0400 Subject: [PATCH] Rearrange characters in a string such that no two adjacent are same --- ...ge-string-so-no-two-adjacent-chars-same.js | 47 +++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 Problem-Solving/rearrange-string-so-no-two-adjacent-chars-same.js diff --git a/Problem-Solving/rearrange-string-so-no-two-adjacent-chars-same.js b/Problem-Solving/rearrange-string-so-no-two-adjacent-chars-same.js new file mode 100644 index 0000000..280e46a --- /dev/null +++ b/Problem-Solving/rearrange-string-so-no-two-adjacent-chars-same.js @@ -0,0 +1,47 @@ +/** + * Rearrange characters in a string such that no two adjacent are same + */ +const noAdjacentCharsSame = (inString) => +{ + let inArray = inString.split(""); + let buf = []; + const outArray = []; + let ct = 0; + while (inArray.length > 0) + { + // console.log(`inArray: ${inArray.join("")} \t buf: ${buf.join("")} \t outArray: ${outArray.join("")}`); + let curChar = inArray.shift(); + if (((outArray.length > 0) && (outArray[outArray.length-1] !== curChar)) || (outArray.length === 0)) + { + outArray[outArray.length] = curChar; + if (buf.length > 0) + { + inArray = [...buf, ...inArray]; + buf = [] + } + } + else + { + buf.push(curChar); + } + } + + if (buf.length > 0) + { + return "not possible"; + } + return outArray.join(""); +}; + +if (typeof process.argv[2] !== 'undefined') +{ + console.log(process.argv[2]); + console.log(noAdjacentCharsSame(process.argv[2])); +} + +// console.log(`aaabc \t ${noAdjacentCharsSame('aaabc')}`); +// console.log(`aaabb \t ${noAdjacentCharsSame('aaabb')}`); +// console.log(`aa \t ${noAdjacentCharsSame('aa')}`); +// console.log(`aaaabc \t ${noAdjacentCharsSame('aaaabc')}`); + +module.exports = noAdjacentCharsSame; \ No newline at end of file