Algorithm #03 - "Is a subset?"

filoscoderΒ·2019λ…„ 11μ›” 25일
0

Toy Algorithm

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

πŸ‡ΊπŸ‡Έ Make an array method that can return whether or not a context array is a subset of an input array. To simplify the problem, you can assume that neither array will contain objects or arrays as elements within them.

  • Next level: Make the method work for arrays that contain objects and/or arrays as elements.

πŸ‡¦πŸ‡· Escriba una funcion que devuelva si cierto array dado es un subconjunto del array contextual. Para simplificar el problema, se puede suponer que ambos arrays no incluyen object/ array como elementos.

  • Proximo nivel: reconstruye la funcion para que pueda aceptar object/ array.

πŸ‡°πŸ‡· νŠΉμ • λ°°μ—΄ 쀑 μž…λ ₯ 배열이 ν•˜μœ„ 집합인지 μ—¬λΆ€λ₯Ό λ°˜ν™˜ν•  수 μžˆλŠ” ν•¨μˆ˜λ₯Ό λ§Œλ“œμ„Έμš”. 문제λ₯Ό λ‹¨μˆœν™”ν•˜κΈ° μœ„ν•΄ 두 λ°°μ—΄ λͺ¨λ‘ 객체 λ˜λŠ” λ°°μ—΄λ₯Ό μš”μ†Œλ‘œ ν¬ν•¨ν•˜μ§€ μ•ŠλŠ”λ‹€.

  • λ‹€μŒ 레벨: 객체 및/λ˜λŠ” 배열을 μš”μ†Œλ‘œ ν¬ν•¨ν•˜λŠ” μž…λ ₯ 배열에 λŒ€ν•΄ λ©”μ„œλ“œλ₯Ό λ¦¬νŽ™ν† λ§ ν•˜μ„Έμš”.

Example:

var a = ['commit','push']
 a.isSubsetOf(['commit','rebase','push','blame']) // true

 NOTE: You should disregard duplicates in the set.

 var b = ['merge','reset','reset']

b.isSubsetOf(['reset','merge','add','commit']) // true 

# START [ here ] 🏁

Array.prototype.isSubsetOf = function(arr) {
  // Your CODE
}

// Test
var a = ['commit','push']
a.isSubsetOf(['commit','rebase','push','blame'])

# 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 😱

Solution πŸ‘‡

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

SOLUTION

Array.prototype.isSubsetOf = function(arr) {
  // stringify all elements as obj's key
  var obj = objectify(arr);
console.log(obj)
  return this.reduce(function(acc, key) {
    if (!obj[key]) {
      return false;
    }
    return acc;
  }, true);

  function objectify(arr) {
    var obj = {};
    console.log(arr)
    arr.forEach(function(key) {
      obj[key] = 1; // if there is repeated [key] it overwrites
    });
    return obj;
  }
}

// Test
var a = ['commit','push']
a.isSubsetOf(['commit','rebase','push','blame']) // true

// var b = ['merge','reset','reset']
// b.isSubsetOf(['reset','merge','add','commit']) // true

// var c = ['yum', 'meal']
// c.isSubsetOf(['poo', 'loo', 'yum'])

////// Extra Credit 
// Test
var d  = ['cool', ['beans'], {0: 'yum'}];
d.isSubsetOf([{0: 'yum'}, 'cool', 'cool', 'cool', ['beans'], 'dude'])

// var e  = ['cool', ['beans'], {0: 'yum'}];
// e.isSubsetOf([{0: 'yum'}, 'dude', 'looks', 'like', 'a', 'lady'])
profile
Keep thinking code should be altruistic

0개의 λŒ“κΈ€