freeCodeCamp Challenge Guide: Fibonacci word

Fibonacci word


Solutions

Solution 1 (Click to Show/Hide)
// Entrophy calculation for string with only 0 and 1
function entrophy(word) {
  function digitEntrophy(count) {
    return count < 1 ? 0
      : - count / word.length * Math.log2(count / word.length);
  }
  const numZeros = word.split('').filter(e => e === '0').length;
  const numOnes  = word.length - numZeros;
  return digitEntrophy(numZeros) + digitEntrophy(numOnes);
}

// Compute array of Fibonacci words
function fibWord(n) {
  const words = [
    { N: 1, Length: 1, Entropy: 0, Word: '1' },
    { N: 2, Length: 0, Entropy: 0, Word: '0' }
  ];

  for (let i = 3; i <= n; i++) {
    const word = words[i - 2].Word + words[i - 3].Word;
    words.push(
      { N: i, Length: word.length, Entrophy: entrophy(word), Word: word }
    );
  }

  return words;
}

// Testing
console.log(fibWord(5));
Solution 2 (Click to Show/Hide)
// Entrophy calculation for string with only 0 and 1
function entrophy(word) {
  function digitEntrophy(count) {
    return count < 1 ? 0
      : - count / word.length * Math.log2(count / word.length);
  }
  const numZeros = word.split('').filter(e => e === '0').length;
  const numOnes  = word.length - numZeros;
  return digitEntrophy(numZeros) + digitEntrophy(numOnes);
}

// Compute array of Fibonacci words
function fibWord(n) {
  return [...Array(n).keys()]
    .reduce((words, i) => {
      const word = i === 0 ? "1"
                 : i === 1 ? "0"
                 : words[i - 1].Word + words[i - 2].Word;
      words.push(
        { N: i + 1, Length: word.length, Entrophy: entrophy(word), Word: word }
      );
      return words;
    }, []);
}

// Testing
console.log(fibWord(5));
1 Like