3.1 KiB
3.1 KiB
title, id, challengeType
title | id | challengeType |
---|---|---|
Fibonacci word | 5992e222d397f00d21122931 | 5 |
Description
Write a function to return the Fibonacci Words upto N. N will be provided as a parameter to the function. The function should return an array of objects. The objects should be of the form : { N: 1, Length: 1, Entropy: 0, Word: '1' }. More details are given below :
The Fibonacci Word may be created in a manner analogous to the Fibonacci Sequence as described here:
Define F_Word1 as 1
Define F_Word2 as 0
Form F_Word3 as F_Word2 concatenated with F_Word1 i.e.: 01
Form F_Wordn as F_Wordn-1 concatenated with F_wordn-2
Instructions
Tests
- text: <code>fibWord</code> is a function.
testString: 'assert(typeof fibWord === "function", "<code>fibWord</code> is a function.");'
- text: <code>fibWord(5)</code> should return an array.
testString: 'assert(Array.isArray(fibWord(5)),"<code>fibWord(5)</code> should return an array.");'
- text: <code>fibWord(5)</code> should return <code>'+JSON.stringify(ans)+'</code>.
testString: 'assert.deepEqual(fibWord(5),ans,"<code>fibWord(5)</code> should return <code>"+JSON.stringify(ans)+"</code>.");'
Challenge Seed
function fibWord (n) {
// Good luck!
}
After Test
console.info('after the test');
Solution
function fibWord(n) {
function entropy(s) {
//create an object containing each individual char
//and the amount of iterations per char
function prob(s) {
var h = Object.create(null);
s.split(").forEach(function(c) {
h[c] && h[c]++ || (h[c] = 1);
});
return h;
}
s = s.toString(); //just in case
var e = 0, l = s.length, h = prob(s);
for (var i in h ) {
var p = h[i]/l;
e -= p * Math.log(p) / Math.log(2);
}
return e;
}
var wOne = "1", wTwo = "0", wNth = [wOne, wTwo], w = "", o = [];
for (var i = 0; i < n; i++) {
if (i === 0 || i === 1) {
w = wNth[i];
} else {
w = wNth[i - 1] + wNth[i - 2];
wNth.push(w);
}
var l = w.length;
var e = entropy(w);
if (l <= 21) {
o.push({
N: i + 1,
Length: l,
Entropy: e,
Word: w
});
} else {
o.push({
N: i + 1,
Length: l,
Entropy: e,
Word: "..."
});
}
}
return o;
}