[알고리즘] 2024-02-15(목)

dev-riverkim·2024년 3월 13일
0

8 kyu - 5 without numbers !!

Write a function that always returns 5

Sounds easy right? Just bear in mind that you can't use any of the following characters: 0123456789*+-/

Good luck :)

Solution

function unusualFive() {
  return 'five!'.length
}

8 kyu - Invert values

Given a set of numbers, return the additive inverse of each. Each positive
becomes negatives, and the negatives become positives.

invert([1,2,3,4,5]) == [-1,-2,-3,-4,-5]
invert([1,-2,3,-4,5]) == [-1,2,-3,4,-5]
invert([]) == []

You can assume that all values are integers. Do not mutate the input array/list.

Solution

function invert(array) {
  const result = array.map(item=>{
    return item > 0 ? -(item) : -(item)
  });
   return result ;
}
const invert = array => array.map(num => -num);
function invert(array) {
   return array.map( x => x === 0 ? x : -x);
}

8 kyu - Counting sheep...

Consider an array/list of sheep where some sheep may be missing from their
place. We need a function that counts the number of sheep present in the
array (true means present).

For example,

[true,  true,  true,  false,
  true,  true,  true,  true ,
  true,  false, true,  false,
  true,  false, false, true ,
  true,  true,  true,  true ,
  false, false, true,  true]

The correct answer would be 17.

Hint: Don't forget to check for bad values like null/undefined

Solution

function countSheeps(sheep) {
  let count = 0;

  sheep.map((index)=>{
    return index === true ? count++ : false
  })  
  return count;
}
function countSheeps(arrayOfSheeps) {
  return arrayOfSheeps.filter(Boolean).length;
}
function countSheeps(arrayOfSheep) {
  var count = 0;
  
  arrayOfSheep.forEach( function (sheep) {
    if (sheep)
      count++;
  });
  
  return count;
}
function countSheeps(arrayOfSheep) {
  // TODO May the force be with you
  var num = 0;
  
  for(var i = 0; i < arrayOfSheep.length; i++)
    if(arrayOfSheep[i] == true)
      num++;
      
  return num;
}
profile
dev-riverkim

0개의 댓글