I am trying to create a function that takes in a string and changes each letters value to a "(" if the character is not duplicated in the string, and a ")" if the character does have a duplicate present in the string. I have decided to go an unconventional route to solve this problem but I am running in to an issue with a double for loop. From what I understand, the inner for loop in javascript does not have access to the variables outside of the loop. I want to loop through every item in an array twice but I'm not sure what to set the inner loops length as.
Here is my code:
function sortAndChange(word) {
const splitter = word.toLowerCase().split("");
//let jSplitter = word.toLowerCase().split("").length;
let endResult = "";
let truthArray = [];
for(i = 0; i < splitter.length; i++){
for(j = 0; j < splitter.length; j++){
console.log(j);
if(splitter[i] == splitter[j]){
truthArray.push(true);
} else {
truthArray.push(false);
}
}
console.log(truthArray);
truthArray.every(item => item === false) ? endResult += "(" : endResult += ")";
truthArray = [];
}
console.log(endResult);
}
Expected Result:
sortAndChange("Success") //expected output: ")())())"
sortAndChange("easy") //expected output: "(((("
You can do that in following steps:
split
and use map()
on it.indexOf()
and lastIndexOf()
to check if its duplicate or not.)
or (
based on ur condition. And then at last join
the array function sortAndChange(str){ let arr = str.toLowerCase().split('') return arr.map(x => { //if its not duplicated if(arr.indexOf(x) === arr.lastIndexOf(x)){ return '(' } //If its duplicated else{ return ')' } }).join(''); } console.log(sortAndChange("Success")) //expected output: ")())())" console.log(sortAndChange("easy")) //expected output: "(((("
You could take a object and keep a boolean value for later mapping the values.
This approach has two loops with O(2n)
function sortAndChange(word) { word = word.toLowerCase(); var map = [...word].reduce((m, c) => (m[c] = c in m, m), {}); return Array .from(word, c => '()'[+map[c]]) .join(''); } console.log(sortAndChange("Success")); // )())()) console.log(sortAndChange("easy")); // ((((
Look at the following snippet and comments
function sortAndChange(str) { // we create an array containing the characters on the string // so we can use Array.reduce return str.split('').reduce((tmp, x, xi) => { // we look if the character is duplicate in the string // by looking for instance of the character if (str.slice(xi + 1).includes(x.toLowerCase())) { // Duplicate - we replace every occurence of the character tmp = tmp.replace(new RegExp(x, 'gi'), ')'); } else { // Not duplicate tmp = tmp.replace(new RegExp(x, 'gi'), '('); } return tmp; }, str); } console.log(sortAndChange('Success')); //expected output: ")())())" console.log(sortAndChange('Easy')); //expected output: "(((("
This can easily be achieved using a combination of regex
and the map
construct in javascript:
const input = "this is a test"; const characters = input.toLowerCase().split(''); const transformed = characters.map(currentCharacter => { const regexpression = new RegExp(currentCharacter, "g"); if (input.toLowerCase().match(regexpression || []).length > 1) return ')' return '('; }).join(""); console.log(transformed);
1) use Array.from
to convert to array of chars
2) use reduce
to build object with key-value pairs as char in string and ( or ) as value based on repetition .
3) Now convert original string to result string using the chars from above object.
function sortAndChange(str) { const str_arr = Array.from(str.toLowerCase()); const obj = str_arr.reduce( (acc, char) => ((acc[char] = char in acc ? ")" : "("), acc), {} ); return str_arr.reduce((acc, char) => `${acc}${obj[char]}`, ""); } console.log(sortAndChange("Success")); // ")())())" console.log(sortAndChange("easy")); // ((((
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.