Home >Web Front-end >JS Tutorial >Codewars - Two to One

Codewars - Two to One

Barbara Streisand
Barbara StreisandOriginal
2025-01-06 08:50:42921browse

Salutations.

Codewars - Two to One

I'm posting Codewars challenges and my thought process in this series. I'm using JS and Node 18 whenever possible. Just for the sake of clarity, I'm making fair use of them.

Ok, this was juicy. In essence, you have to remove duplicates in a string, order what's left and join two strings. Not exactly in that order. Actually, I did it in the exact opposite way. And I also built an utility function for a very specific step (removing duplicates).


First, concatenate two strings. Easy:

let longest = s1 + s2;

Second, split up the letters:

let array = new Array(s1.length + s2.length);
for (let i = 0 ; i < s1.length + s2.length ; i++ ){
    array[i] = longest[i];
  }

Third, sort the letters:

array = array.sort((a, b) => a.localeCompare(b));
// (a, b) => a.localeCompare(b)  THIS IS REDUNDANT, but I leave it as a reminder

Fourth, remove duplicates:

function keepFirstLetter(array){
  let arrayFixed = new Array(array.length);
  let counter = 0;
  arrayFixed[0] = array[0];


  for (let i = 0 ; i < array.length ; i++ ){
    if (arrayFixed[counter] != array[i]){
      counter++;
      arrayFixed[counter] = array[i];
    }
  }

  return arrayFixed;
}

Fifth, clean up:

array = array.join("");

Last, place every piece of the puzzle together:

function longest(s1, s2) {
  let array = new Array(s1.length + s2.length);

  let longest = s1 + s2;

  for (let i = 0 ; i < s1.length + s2.length ; i++ ){
    array[i] = longest[i];
  }

  array = array.sort((a, b) => a.localeCompare(b));

  array = keepFirstLetter(array);

  array = array.join("")

  return array;
}

function keepFirstLetter(array){
  let arrayFixed = new Array(array.length);
  let counter = 0;
  arrayFixed[0] = array[0];

  for (let i = 0 ; i < array.length ; i++ ){
    if (arrayFixed[counter] != array[i]){
      counter++;
      arrayFixed[counter] = array[i];
    }
  }

  return arrayFixed;
}

It's definitely NOT performant. I don't like that second loop. And it's not so clean either. Someday I'll need to revisit this one.

Be well. Drink water ???.

Previous

The above is the detailed content of Codewars - Two to One. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:Starting with semver `.0`Next article:Starting with semver `.0`