0
我目前正在編寫一個遞歸解決河內塔的ijvm程序。我不知道如何設置方法中調用的方法的對象引用的編號。在IJVM中編寫遞歸函數
這是java代碼,我使用「翻譯」的ijvm代碼:
public class Tower{
public static void towers(int n, int i, int j) {
int k;
if (n == 1) {
System.out.println("Move a disk from " + i + " to " + j);
} else {
k = 6 - i - j;
towers(n - 1, i, k);
towers(1, i, j);
towers(n - 1, k, j);
}
}
public static void main(String[] args){
towers(5,1,3);
}
}
這是ijvm代碼:
;BIPUSH 0 is for the object reference
BIPUSH 0
BIPUSH 5
BIPUSH 1
BIPUSH 3
INVOKEVIRTUAL tower
HALT
;the recursive method
tower 4 1
ILOAD 1
BIPUSH 1
IF_ICMPEQ L1
BIPUSH 6
ILOAD 2
ISUB
ILOAD 3
ISUB
ISTORE 4
;this is for the method towers(n - 1, i, k);
;BIPUSH 1 is for the object reference
BIPUSH 1
ILOAD 1
BIPUSH 1
ISUB
ILOAD 2
ILOAD 4
INVOKEVIRTUAL tower
;this is for the method towers(1, i, j);
;BIPUSH 2 is for the object reference
BIPUSH 2
BIPUSH 1
ILOAD 2
ILOAD 3
INVOKEVIRTUAL tower
;this is for the method towers(n-1, k, j);
;BIPUSH 3 is for the object reference
BIPUSH 3
ILOAD 1
BIPUSH 1
ISUB
ILOAD 4
ILOAD 3
INVOKEVIRTUAL tower
L1: ILOAD 3
ILOAD 2
SPRINT "Move a disk from "
IPRINT
SPRINT " to "
IPRINT
SPRINT "\n"