-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdecode_program.js
More file actions
79 lines (72 loc) · 2.16 KB
/
Copy pathdecode_program.js
File metadata and controls
79 lines (72 loc) · 2.16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
var decode = function(toDecode) {
toDecode = toDecode.replace(/\s+/g, '');
if (toDecode == "") {
return "";
}
var mulArray = toDecode.split("*");
var currentNumber = 0;
for (var i = 0; i < mulArray.length; i++) {
var powArray = mulArray[i].split("^");
var currentPowNumber = powArray[0];
for(var j = 1; j < powArray.length; j++) {
currentPowNumber = Math.pow(currentPowNumber, powArray[j]);
}
currentNumber = ((i == 0) ? 1 : currentNumber) * currentPowNumber;
}
return decodeList(currentNumber, 0);
};
var decodeList = function(list, index) {
var head = 0;
while (list != 0 && list % 2 == 0) {
head++;
list = list / 2;
}
if (list == 0) {
return "";
}
nextIndex = index + 1;
return decodeInstruction(head, index) + decodeList((list - 1)/2, nextIndex);
};
var decodeInstruction = function(instruction, index) {
if (instruction == 0) {
return "<br/>" + writeHaltInstr(index);
}
var x = 0;
while (instruction != 0 && instruction % 2 == 0) {
x++;
instruction = instruction / 2;
}
if (instruction == 0) {
alert("something's not right with your input...");
return "";
}
instruction = ((instruction-1)/2);
if (x % 2 == 0) { //increment instruction
return "<br/>" + writeIncInstr(index, (x/2), instruction);
} else { //decrement instruction
instruction++;
var j = 0;
var k = 0;
j = calculateGreatestPowerOfTwo(instruction);
k = ((instruction / Math.pow(2, j)) - 1) / 2;
return "<br/>" + writeDecInstr(index, ((x-1)/2), j, k);
}
return instruction + "; ";
};
var calculateGreatestPowerOfTwo = function(n) {
var powerOfTwo = 0;
while (n != 0 && n % 2 == 0) {
powerOfTwo++;
n = n / 2;
}
return powerOfTwo;
};
var writeIncInstr = function(instrNo, regNo, nextInstrNo) {
return "L<sub>" + instrNo + "</sub>: R<sub>" + regNo + "</sub><sup>+</sup> → L<sub>" + nextInstrNo + "</sub>;";
};
var writeDecInstr = function(instrNo, regNo, trueNextInstrNo, falseNextInstrNo) {
return "L<sub>" + instrNo + "</sub>: R<sub>" + regNo + "</sub><sup>-</sup> → L<sub>" + trueNextInstrNo + "</sub>,L<sub>" + falseNextInstrNo + "</sub>;";
};
var writeHaltInstr = function(instrNo) {
return "L<sub>" + instrNo + "</sub>: HALT;";
};