Skip to content

Instantly share code, notes, and snippets.

@VisualMelon
Last active June 14, 2022 13:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save VisualMelon/50ad520ad47ad58be8cd1e4ba0e36bb9 to your computer and use it in GitHub Desktop.
Save VisualMelon/50ad520ad47ad58be8cd1e4ba0e36bb9 to your computer and use it in GitHub Desktop.
LilyPadBinTreeGenerator
/*
Each nightmare example is a binary tree, where the leaf (odd indexed) nodes return you to only the first or last node.
The first node takes you to the last node, and the last node takes you to the root of the binary tree.
Ultimately, you have a 'one-way' (descending) binary tree where all the leaves point to the top.
This means that you have to traverse the binary tree floor(l/2) times (once for each leaf node), which means you must visit the top of the tree as many times.
*/
using System;
class P{
static void Main()
{
for (int i = 1; i < 10; i++)
{
var prob = nightmare(i);
Console.WriteLine($"[{string.Join(",", prob)}]");
}
}
static int[] nightmare(int n)
{
// length is 2 (for head and tail) + size of the binary tree (2^n-1)
int l = 2 + ((1 << n) - 1);
var res = new int[l];
// head goes to tail
res[0] = l - 1;
// tail goes to the middle node ('root' of the binary tree; in effect the tail is just a root with only one child)
res[l - 1] = l / 2;
// start filling from the middle node
int i0 = l / 2;
int d0 = l / 4;
fill(i0, d0);
void fill(int i, int d)
{
if (d == 0)
{
// leaf node: return to either the start or finish (but no-where else) depending on which is further away
res[i] = Math.Max(i, l - i - 1);
}
else
{
// non-leaf: branch
res[i] = d;
fill(i - d, d / 2);
fill(i + d, d / 2);
}
}
return res;
}
}