DEV Community

Discussion on: Reverse a string: awful answers only

Collapse
 
kallmanation profile image
Nathan Kallman • Edited

Just shuffle the characters and see if it reversed the string! We'll get the reverse eventually.... (prepare to wait a long time for strings longer than 8 characters)

function reverseString(string, maxIterations = 10000, verbose = false) {
  const originalString = string.split("");
  let shuffledString = string.split("");
  let isReverse;
  let iteration = 1;
  do {
    for (let i = 0; i < shuffledString.length; i++) {
      let j = Math.floor(Math.random() * (string.length - i) + i);
      if (i != j) {
        shuffledString[i] = shuffledString[i] + shuffledString[j];
        shuffledString[j] = shuffledString[i].replace(shuffledString[j], "");
        shuffledString[i] = shuffledString[i].replace(shuffledString[j], "");
      }
    }
    if (verbose) console.log("Candidate string: ", shuffledString.join(""));
    isReverse = true;
    for (let i = 0; i < shuffledString.length; i++) {
      isReverse = isReverse && originalString[i] == shuffledString[shuffledString.length - 1 - i];
    }
    iteration++;
  } while (!(isReverse || iteration > maxIterations));
  if (isReverse) {
    return shuffledString.join("");
  } else {
    return false;
  }
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
gilfewster profile image
Gil Fewster

Perfect!