본문 바로가기

Programming/JavaScript

Coding Challenge #1 - Developer Skills (feat. Problem solving)

Tried

결과 값은 나오는데 Console에 한줄에 어떻게 프린트할지에서 막힘 😥

// step 1. create a function 'printForecast'

// step 2. how to take an array as an argument of the function

// step 2-2. how to log on console in the same line
// console을 매 array value마다 찍지 말고 결과 값을 another array에 담아야 하나?

// step 3. how to log a string like the example to the console

const arrOne = [17, 21, 23];

function printForecast(arr) {
  for (let i = 0; i < arr.length; i++) {
    console.log(`... ${arr[i]} degrees in ${i + 1} days `);
  }
}

printForecast(arrOne);
// ... 17 degrees in 1 days 
// ... 21 degrees in 2 days 
// ... 23 degrees in 3 days

 

Answer

Tips: 문제를 정의하고, 최대한 쪼개라!

// 1) Understanding the problem
// - Array transformed to string, separated by ...
// - What is the X days? Answer: index + 1

// 2) Breaking up into sub-problems
// - Transform array into string
// - Transform each element to string
// - Strings needs to contain day (index + 1)
// - Add ... between elements and start and end of string
// - Log string to console

const arrOne = [17, 21, 23];
const arrTwo = [12, 5, -5, 0, 4];

const printForecast = function (arr) {
  let str = '';
  for (let i = 0; i < arr.length; i++) {
    str += `${arr[i]} degrees in ${i + 1} days `;
  }
  console.log('...' + str);
};
printForecast(arrOne);
// print ...17 degrees in 1 days 21 degrees in 2 days 23 degrees in 3 days