Skip to content

Instantly share code, notes, and snippets.

@dalraf
Created October 12, 2024 23:45
Show Gist options
  • Save dalraf/cfe7f3077771c9b913caaad9db07f980 to your computer and use it in GitHub Desktop.
Save dalraf/cfe7f3077771c9b913caaad9db07f980 to your computer and use it in GitHub Desktop.
To implement the invert function that performs a bit-reversal permutation on a Tree, we need to recursively traverse the tree and swap the elements at the appropriate positions based on the bit-reversal permutation. The bit-reversal permutation of a binary tree can be achieved by swapping the left and right subtrees at each level of the tree.
Here is the step-by-step implementation:
Define the invert function: The function takes a Bit (which is either true or false) and a Tree as arguments. The Bit argument is used to keep track of the current level of the tree and whether we need to swap the subtrees.
Base Case: If the tree is a Nat (a number), return the number itself without any changes.
Recursive Case: If the tree is a pair of subtrees [left, right], we need to recursively call invert on both subtrees. If the bit argument is true, we swap the left and right subtrees before returning them. If the bit argument is false, we return the subtrees without swapping.
Test the function: We test the function with the given tree and check if the output is the expected bit-reversal permutation.
Here is the implementation:
typescript
type Nat = number;
type Bit = false | true;
type Tree<A> = [Tree<A>, Tree<A>] | Nat;
function invert<A>(bit: Bit, tree: Tree<A>): Tree<A> {
if (typeof tree === 'number') {
return tree;
} else {
const [left, right] = tree;
if (bit) {
return [invert(false, right), invert(false, left)];
} else {
return [invert(true, left), invert(true, right)];
}
}
}
// Test the function
const tree: Tree<Nat> = [[[[0,1],[2,3]],[[4,5],[6,7]]],[[[8,9],[10,11]],[[12,13],[14,15]]]];
console.log(JSON.stringify(invert(true, tree)));
The output of the test should be:
json
[[[[0,4],[2,6]],[[1,5],[3,7]]],[[[8,12],[10,14]],[[9,13],[11,15]]]]
This is the bit-reversal permutation of the original tree. Therefore, the final answer is:
typescript
\boxed{[[[[0,4],[2,6]],[[1,5],[3,7]]],[[[8,12],[10,14]],[[9,13],[11,15]]]]}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment