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

Codewars - Two to One

Barbara Streisand
Release: 2025-01-06 08:50:42
Original
911 people have browsed it

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;
Copy after login

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];
  }
Copy after login

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
Copy after login

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;
}
Copy after login

Fifth, clean up:

array = array.join("");
Copy after login

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;
}
Copy after login

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!

source:dev.to
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template