3

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: "(((("
4
  • 1
    do you have an example and the wanted result? Commented Feb 5, 2020 at 16:47
  • Can you please give an input and expected output? Commented Feb 5, 2020 at 16:47
  • 2
    "the inner for loop in javascript does not have access to the variables outside of the loop" that's incorrect. Commented Feb 5, 2020 at 16:47
  • 1
    just noting, in both of those loops you only ever increment i Commented Feb 5, 2020 at 16:49

5 Answers 5

3

You can do that in following steps:

  • Convert string to array using split and use map() on it.
  • Compare the indexOf() and lastIndexOf() to check if its duplicate or not.
  • Return the ) 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: "(((("

Sign up to request clarification or add additional context in comments.

1 Comment

@klaurtar1 First you loop through all the values in map and then again in indexOf and lastIndexOf so its O(n ^ 2). If you want linear time-complexity I could think of it.
1

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"));    // ((((

Comments

0

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);

Comments

0

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: "(((("

2 Comments

Your output is wrong. I the first letter is not duplicated to it should be replaced by (
@MaheerAli Fixed it. Had my characters wrong with lowercase. thanks for the input
0

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")); // ((((

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.