[04.20.22] Codewars

Sum of Digits / Digital Root

Description

Digital root is the recursive sum of all the digits in a number.
Given n, take the sum of the digits of n. If that value has more than one digit, continue reducing in this way until a single-digit number is produced. The input will be a non-negative integer.
Examples
16 --> 1 + 6 = 7
942 --> 9 + 4 + 2 = 15 --> 1 + 5 = 6
132189 --> 1 + 3 + 2 + 1 + 8 + 9 = 24 --> 2 + 4 = 6
493193 --> 4 + 9 + 3 + 1 + 9 + 3 = 29 --> 2 + 9 = 11 --> 1 + 1 = 2

My answer

function digital_root(n) {
  let numberArray = `${n}`.split('').map(a => Number(a));
  let result;
  do {
    result = numberArray.reduce((a,b) => a+b,0);
    numberArray = `${result}`.split('').map(a => Number(a));
  } while (numberArray.length != 1)
  
  return result;
}

Other solutions

function digital_root(n) {
  if (n < 10) return n;
  return digital_root(
    n.toString().split('').reduce(function(acc, d) { return acc + +d; }, 0));
}

Bit Counting

Description

Write a function that takes an integer as input, and returns the number of bits that are equal to one in the binary representation of that number. You can guarantee that input is non-negative.
Example: The binary representation of 1234 is 10011010010, so the function should return 5 in this case

My answer

var countBits = function(n) {
  return n.toString(2).split('').map(a => Number(a)).filter(a => a === 1).length;
};

Other solutions

countBits = n => n.toString(2).split('0').join('').length;
var countBits = function(n) {
  return n.toString(2).replace(/0/g,'').length;
};

Where my anagrams at?

Description

What is an anagram? Well, two words are anagrams of each other if they both contain the same letters.
For example:
'abba' & 'baab' == true
'abba' & 'bbaa' == true
'abba' & 'abbba' == false
'abba' & 'abca' == false
Write a function that will find all the anagrams of a word from a list. You will be given two inputs a word and an array with words. You should return an array of all the anagrams or an empty array if there are none. For example:
anagrams('abba', ['aabb', 'abcd', 'bbaa', 'dada']) => ['aabb', 'bbaa']

My answer

function anagrams(word, words) {
  const standard = word.split('').sort().join('');
  
  let sortedArray = words.map(function(a) {
    return a.split('').sort().join('');
  });
  
  let result = [];
  let array = sortedArray.map(a => (a === standard) ? true : false);

  for(let i = 0; i < array.length; i++) {
    if (array[i]) {
      result.push(words[i]);
    }
  }
  
  return result;
}

Other solutions

function anagrams(word, words) {
  word = word.split('').sort().join('');
  return words.filter(function(v) {return word == v.split('').sort().join('');});
}
function anagrams(word, words) {
    return words.filter(function (e) {
        return e.split('').sort().join('') === word.split('').sort().join('');
    })
}

좋은 웹페이지 즐겨찾기