Algorithm #06 - "Common Characters"

filoscoderΒ·2019λ…„ 12μ›” 7일
0

Toy Algorithm

λͺ©λ‘ 보기
6/7
post-thumbnail

πŸ‡ΊπŸ‡Έ Write a function commonCharacters(string1, string2) which takes two strings as arguments and returns a string containing the characters found in both strings (without duplication), in the order that they appeared in string1.

  • Has to return a string. Remember to skip spaces and characters you have already encountered!

πŸ‡¦πŸ‡· Escribe la funciΓ³n commonCharacters(string1, string2) que recibe dos strings como argumentos y devuelve un string que contiene los caracteres existentes en ambos strings (sin repeticion), en el orden que aparecen en string1.

  • Debe retornar un string. Recuerda eliminar los espacion y los caracteres que ya fueron encontrados!

πŸ‡°πŸ‡· 두 개의 λ¬Έμžμ—΄μ„ 인수둜 λ°›κ³  두 λ¬Έμžμ—΄(쀑볡 문자 없이)μ—μ„œ μ‘΄μž¬ν•˜λŠ” λ¬Έμžλ“€μ„ ν•©ν•œ λ¬Έμžμ—΄ λ°˜ν™˜ν•˜λŠ” ν•¨μˆ˜λ₯Ό μž‘μ„±ν•˜μ„Έμš” (commonCharacters(string1, string2)). λ°˜ν™˜κ°’μ€ λ¬Έμžμ—΄1에 λ‚˜νƒ€λ‚œ μˆœμ„œλŒ€λ‘œ λ‚˜μ˜€κ²Œ ν•˜μ‹­μ‹œμ˜€.

  • string을 λ°˜ν™˜ν•΄μ•Ό ν•œλ‹€. 띄어쓰기λ₯Ό μ œκ±°ν•˜λŠ” 것과 이미 찾은 λ¬Έμžλ“€μ„ μƒλž΅ν•΄μ•Ό ν•˜λŠ” 것을 κΈ°μ–΅ν•˜μ‹­μ‹œμ˜€!

Example:

// Test
var commonCharacters = function('acexivou', 'aegihobu');

console.log(commonCharacters);
// return -> 'aeiou'

# START [ here ] 🏁

var commonCharacters = function(string1, string2) {
  // Your CODE
};

// Test
commonCharacters("acexivou", "aegihobu"); // output> "aeiou"
commonCharacters("aeiou", "aaeeiioouu"); // output> "aeiou"
commonCharacters("i am a string", "i am also a string"); // output> "i am strng"
commonCharacters("vicapow", "wopaciv"); // output> "vicapow"

# Javascript solution πŸ†

  • Run it on your browser console window (F12) πŸ–₯
  • Please feel free to add your preference language solution πŸ‘©β€πŸ‘©β€πŸ‘§β€πŸ‘¦
  • Do your best to complete the problem 🎭
  • if you can't beat this the solution is below 😱

Click for the solution πŸ‘‡

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

SOLUTION

var commonCharacters = function(string1, string2) {
  // TODO: Your code here!
  // new result array []
  let temp = [];
  let result = "";

  if (string1 === string2) {
    result = string1;
  } else if (string1.length === 0 || string2.length === 0) {
    result = "";
  } else {
    // two for loops
    for (let i = 0; i < string1.length; i++) {
      for (let j = 0; j < string2.length; j++) {
        // if statement ? string1 char is equal to string2 char
        // && is not inside result array
        // TRUE> push to result array
        if (string1[i] === string2[j] && !temp.includes(string2[j])) {
          temp.push(string2[j]);
        }
      }
    }
    // Convert temp array into String
    result = temp.join("");
  }
  return result;
};
profile
Never gets bored of making mistakes and wonder why is that

0개의 λŒ“κΈ€