<script>
var
MAX = 1000;
function
waysToKAdjacentSetBits(dp, n, k,
currentIndex, adjacentSetBits, lastBit)
{
if
(currentIndex == n) {
if
(adjacentSetBits == k)
return
1;
return
0;
}
if
(dp[currentIndex][adjacentSetBits][lastBit] != -1) {
return
dp[currentIndex][adjacentSetBits][lastBit];
}
var
noOfWays = 0;
if
(lastBit == 1) {
noOfWays += waysToKAdjacentSetBits(dp, n, k,
currentIndex + 1, adjacentSetBits + 1, 1);
noOfWays += waysToKAdjacentSetBits(dp, n, k,
currentIndex + 1, adjacentSetBits, 0);
}
else
if
(!lastBit) {
noOfWays += waysToKAdjacentSetBits(dp, n, k,
currentIndex + 1, adjacentSetBits, 1);
noOfWays += waysToKAdjacentSetBits(dp, n, k,
currentIndex + 1, adjacentSetBits, 0);
}
dp[currentIndex][adjacentSetBits][lastBit] = noOfWays;
return
noOfWays;
}
var
n = 5, k = 2;
var
dp = Array.from(Array(MAX), ()=>Array(MAX));
for
(
var
i =0; i<MAX; i++)
for
(
var
j =0; j<MAX; j++)
dp[i][j] =
new
Array(2).fill(-1);
var
totalWays = waysToKAdjacentSetBits(dp, n, k, 1, 0, 1)
+ waysToKAdjacentSetBits(dp, n, k, 1, 0, 0);
document.write(
"Number of ways = "
+ totalWays +
"<br>"
);
</script>