Home > front end >  Can you use self modifying techniques to change the scope of a statement, or position of a curly bra
Can you use self modifying techniques to change the scope of a statement, or position of a curly bra

Time:10-28

This question pertains to Java specifically.

We need to traverse a tree in preorder inorder and postorder. The issue is commas.

preorder is simple: just don't append a comma before the first node is visited.

For inorder, the comma must not be placed before the bottom-most left-most node.

Or else the traversal will look something like this:

[, <0, 0>, <1, 1>, <2, 2>, <3, 3>, <4, 4>, <5, 5>, <21, 21>, <78, 78>, <88, 88>]

We are specifically not allowed to use string replace to delete the comma after the fact, or modify the parameters of the recursive function:

private int inorderTraversal(Node<K, V> node, StringBuilder str, int nodesVisited)

My theoretical solution looks like this:

        if (node != null) {
            if (nodesVisited==0)
                nodesVisited=1;

            if (node.left!=null) {
                nodesVisited = inorder(node.left, str, nodesVisited   1);
            //move curly brace A here
                if (size > 1) {
                    str.append(", ");
                    //moveCurlyBrace(A)
                }
            } //curly brace A

            str.append(node.toString());

            if (node.right!=null)
                nodesVisited=inorder(node.right, str, nodesVisited 1);
        }
        return nodesVisited;

I am aware this is a bad approach. Self-modifying code is to be avoided at all costs. However, I think this would be funny and would highlight the silliness of the requirements.

Don't tell me the correct approach because that is cheating, but how would I do this operation if possible?

CodePudding user response:

In theory, one could do this through the use of ByteBuddy, which has been a library that's existed for a long while that allows for the manipulation of bytecode at runtime.

There's also sun.misc.Unsafe, but that's getting really locked down in newer versions of Java. To wit, I think that ByteBuddy leverages Unsafe under the hood anyway, but it makes it feel less like you're holding a magnetic needle and a steady glove.

But doing it isn't something that makes a whole lot of practical sense. I don't have any handy examples since writing self-modifying code is too finicky. Worse, it makes your code unreadable and impractical to work with.

  • Related