Created
December 26, 2018 22:37
-
-
Save misterpoloy/05ba0b8fb4603b68e35e22c629406329 to your computer and use it in GitHub Desktop.
coding exercise 1 created by misterpoloy - https://repl.it/@misterpoloy/coding-exercise-1
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function solution(given, T) { | |
let target = [] | |
// generate target array | |
for (let x = 0; x < T.length; x++) { | |
target.push(T.charAt(x)) | |
} | |
// target vs given indexes to compare | |
let target_index = 0; | |
let given_index = 0; | |
let error_counter = 0; | |
let max_errors = 1; // instead of magic numbers | |
let output = ""; | |
while (target.length > target_index) { // prevent overflow | |
if (target[target_index] === given.charAt(given_index)) { | |
// both values are correct, next | |
given_index++ | |
target_index++ | |
} else { | |
// check if less than one error | |
if (error_counter < max_errors) { | |
// validate what kind of error based on lenght | |
if (given.length === T.length) { | |
// Check if missing letter is given, else by default is REPLACE | |
let isSwap = false; | |
for (let i = 0; i < given.length; i++) { | |
// Check if swipping letters are the same value in the "given" and "T" | |
if (target[target_index] === given.charAt(i) && target[i] === given.charAt(target_index)) { | |
isSwap = true; | |
output = `SWAP ${given.charAt(given_index)} ${target[target_index]}`; | |
break; | |
} | |
} | |
if (!isSwap) { | |
// Then is Replace by default | |
output = `REPLACE ${given.charAt(given_index)} ${target[target_index]}`; | |
given_index++ // Then proceed with the next letter | |
error_counter++; | |
} else { | |
// Stop becouse only a swap is necessary | |
break; | |
} | |
} else { | |
output = `INSERT ${target[target_index]}`; | |
error_counter++; | |
} | |
} else { | |
// too much errors, "Impossible" && STOP program | |
output = "IMPOSSIBLE"; | |
break | |
} | |
target_index++ | |
} | |
} | |
return output | |
} | |
console.log("1. ", solution("nice", "niece")) | |
console.log("2. ", solution("test", "tent")) | |
console.log("3. ", solution("form", "from")) | |
console.log("4. ", solution("o", "odd")) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Live version can be found here:
https://repl.it/@misterpoloy/coding-exercise-1