Brainfuck interpreter loop trouble - javascript

I am currently making a brainfuck and have encountered a problem with loops.
I followed some advice from this but I can't seem to get it working.
Here is my code so far:
<html>
<body>
<font face="consolas">
<script>
var brPos = 0;
var k = 0;
var loop = [];
var printtape = "";
var out = "";
var i = 0;
var pointer = 0;
var tape = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];
var source = prompt("Code").split("");
while (i<source.length+1){
if (source[i] == "<"){
pointer--;
} else if (source[i] == ">"){
pointer++;
} else if (source[i] == "+"){
tape[pointer]++;
} else if (source[i] == "-"){
tape[pointer]--;
} else if (source[i] == ","){
tape[pointer] = prompt("Input").charCodeAt(0);
} else if (source[i] == "."){
out += String.fromCharCode(tape[pointer]);
} else if (source[i] == "["){
loop.push(pointer);
if (tape[pointer] == 0){
brPos = i;
while (k >= 0) {
if (source[brPos] == "[") {
k++;
} else if (source[brPos] == "]") {
k--;
}
}
i = brPos;
brPos = 0;
loop.pop();
}
} else if (source[i] == "]"){
i=loop[loop.length-1];
}
i++;
for (j=0;j<tape.length;j++) {
if (tape[j] > 255) {
tape[j] = 0;
} else if (tape[j] < 0) {
tape[j] = 255;
}
}
console.log(tape);
console.log(loop);
}
printtape = "";
printtape += "|";
for (i=0;i<tape.length;i++) {
if (tape[i]<10) {
printtape += "00"+tape[i]+"|";
}
if (tape[i]>=10&&tape[i]<100) {
printtape += "0"+tape[i]+"|";
}
if (tape[i]>=100) {
printtape += tape[i]+"|";
}
}
printtape += "<br>";
printtape += "  ";
for (i=0;i<pointer;i++) {
printtape += "    ";
}
printtape += "^";
document.write(printtape);
alert(out);
</script>
</font>
</body>
</html>
This is the offending code (I think):
} else if (source[i] == "["){
loop.push(pointer);
if (tape[pointer] == 0){
brPos = i;
while (k >= 0) {
if (source[brPos] == "[") {
k++;
} else if (source[brPos] == "]") {
k--;
}
}
i = brPos;
brPos = 0;
loop.pop();
}
} else if (source[i] == "]"){
i=loop[loop.length-1];
}
When I run the code (in IE) with a brainf*ck loop in it, it doesnt end the while loop and eventually crashes and I don't know why.
P.S. I know someone in the comments is going to say that the <font> tag is invalid HTML, and I should use CSS, but it works, it's quicker than CSS and I really don't care.

There's nothing I know about Brainfuck parsing, but the code logic fails and you get infinite loop because brPos is a constant inside the loop. You make the same comparations and get to the k++ line over and over again. brPos has to be changed if you ever wanna get out of there.

Related

JS Alert when items collected?

I have created a maze game where the user must collect all the coins in the maze, however I am trying to make an alert appear once the user has collected all the coins, not in any particular order just in general. The alert is being very troublesome at the moment and not working correctly and I'm not sure where I am going wrong based off my research into the matter. I am new to JavaScript so apologies for any clear mistakes.
EDIT I GOT TOLD TO REPHRASE MY QUESTION MORE DIRECTLY - SO THIS ISN'T A DUPLICATE QUESTION. I ALSO HAVE A MAP DECLARDED BUT CANNOT UPLOAD AS IT'S TOO MUCH CODE.
Also, when I say not working correctly, it will appear at random counts as supposed to when the last reward has been collected.
var el = document.getElementById('game');
function drawWorld(){
el.innerHTML = '';
for(var y = 0; y < map.length ; y = y + 1) {
for(var x = 0; x < map[y].length ; x = x + 1) {
if (map[y][x] === 1) {
el.innerHTML += "<div class='borders'></div>";
} else if (map[y][x] === 2) {
el.innerHTML += "<div class='reward'></div>";
} else if (map[y][x] === 3) {
el.innerHTML += "<div class='ground'></div>";
} else if (map[y][x] === 5) {
el.innerHTML += "<div class='character'></div>";
} else if (map[y][x] === 4) {
el.innerHTML += "<div class='ship'></div>";
}
}
el.innerHTML += "<br>";
}
winGame();
}
function restartGame(){
window.location.reload();
}
function winGame(){
if (!map[5].includes(2) && !map[2].includes(2) &&
!map[3].includes(2) && !map[2].includes(2) && !map[4].includes(2)
&& !map[2].includes(2))
alert("Well done!");
}
drawWorld();
document.onkeydown = function(event){
if (event.keyCode === 37){
if ( map[character.y][character.x-1] !== 1){
map[character.y][character.x] = 3;
character.x = character.x - 1;
map[character.y][character.x] = 5;
drawWorld();
}
} else if (event.keyCode === 38){
if ( map[character.y-1][character.x] !== 1){
map[character.y][character.x] = 3;
character.y = character.y - 1;
map[character.y][character.x] = 5;
drawWorld();
}
} else if (event.keyCode === 39){
if ( map[character.y][character.x+1] !== 1){
map[character.y][character.x] = 3;
character.x = character.x + 1;
map[character.y][character.x] = 5;
drawWorld();
}
} else if (event.keyCode === 40){
if ( map[character.y+1][character.x] !== 1){
map[character.y][character.x] = 3;
character.y = character.y + 1;
map[character.y][character.x] = 5;
drawWorld();
}
}
console.log(map)
}

Encode letter to number

I feel like I am failing everything this semester. but I was wondering if you all could help me with a JS project. We have been tasked with essentially converting numbers to letters and vica versa using textareas in HTML. I was able to do the numbers to letters function, but am having difficulties going the other way. what I have for all is:
var $ = function(id) {
return document.getElementById(id);
};
window.onload = function() {
$("btnDecode").onclick = fnDecode;
$("btnEncode").onclick = fnEncode;
$("btnClear").onclick = fnClear;
};
function fnDecode() {
var msg = $("textin").value;
if (msg === "") {
$("textin_span").innerHTML = "* Please enter a message to decode *";
$("textin").focus;
return;
} else {
$("textin_span").innerHTML = "";
}
var nums = msg.split(",");
var outstr = "";
for(var i=0; i < nums.length; i++) {
var n2 = parseInt(nums[i]);
if (isNaN(n2)) {
outstr += "?";
} else if (isNallN(nums[i])) {
} else if (n2 === 0) {
outstr += " ";
} else if (n2 < 1 || n2 > 26) {
outstr += "?";
} else {
outstr += String.fromCharCode(n2+64);
}
$("textout").value = outstr;
}
}
function isNallN(s) {
//parse string to check all characters are digits
}
function fnEncode() {
var msg = $("textin").value.toUpperCase();
$("textin").value = msg;
if (msg === "") {
$("textin_span").innerHTML = "* Please enter numberse to decode *";
$("textin").focus;
return;
} else {
$("textin_span").innerHTML = "";
}
var c;
var outstr = "";
for (var i=0; i<msg.length; i++);
c = msg.charCodeAt(i);
if (typeof c === "number") {
outstr += "99";
}else if (c === " ") {
outstr += 0;
/*} else if (c[i] >= "A" && c[i] <= "Z") {
outstr += "99";*/
} else {
outstr += String.charCodeAt(c - 64);
}
$("textout").value = outstr;
//var x = msg.charAT(i);
}
obviously isNallN is not complete, but he promised us if we could figure out fnEncode we should be able to do isNallN with no issues (which I am hoping is true lol) What am doing wrong though in fnEncode? Every time I run it, it gives me "99" even when I put letters in.

Nothing happens after Prompt

Sorry, I wasn't clear enough. I need it to list all the numbers from 0 to the number inputted by the prompt into the HTML. I made some suggested changes but now I only get the result for the specific number inputted, not all the numbers up to that number. I am just starting out so please be gentle. Thanks!
$(function() {
var number = parseInt(prompt("Let me see a number:"));
var result;
for(var i = 0; i <= number; i++) {
if ( i %15 == 0) {
result = "Ping-Pong";
}
else if (i %5 == 0) {
result = "Pong";
}
else if (i %3 == 0) {
result = "Ping";
}
else {
result = number;
}
document.getElementById("show").innerHTML = result;
};
});
You can do either:
for(var i = 0; i <= number; i++) {
var digit = number[i]; // or any other assigment to new digit var
if ( digit % 5 == 0) {
return "Ping-Pong";
}
.... rest of your code here.
or
if ( number % 5 == 0) {
return "Ping-Pong";
}
.... rest of your code here.
Problem is you did nothing after the return keyword. Also you didn't declared variable as digit. I hope this is what you are looking for.
With loop:
$(function() {
var number = parseInt(prompt("Let me see a number:"));
var result;
for (var i = 0; i <= number; i++) {
if (i % 15 == 0) { // replaced `digit` with `i`
result = "Ping-Pong";
} else if (i % 5 == 0) {
result = "Pong";
} else if (i % 3 == 0) {
result = "Ping";
} else {
result = number;
}
alert(result);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
Without loop:
$(function() {
var number = parseInt(prompt("Let me see a number:"));
var result;
if (number % 15 == 0) { // replaced `digit` with `number`
result = "Ping-Pong";
} else if (number % 5 == 0) {
result = "Pong";
} else if (number % 3 == 0) {
result = "Ping";
} else {
result = number;
}
alert(result);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
Ok, I figured it out. For future reference, this is what I was trying to do:
$(function() {
var number = parseInt(prompt("Let me see a number:"));
var i
var text = "";
for(i = 1; i <= number; i++) {
if ( i %15 == 0) {
text += "<br>" + "Ping Pong" + "<br>";
}
else if (i %5 == 0) {
text += "<br>" + "Pong" + "<br>";
}
else if (i %3 == 0) {
text += "<br>" + "Ping" + "<br>";
}
else {
text += "<br>" + i + "<br>";
}
};
document.getElementById("show").innerHTML = text;
});

NaN error equation

In this javascript code I try to solve a quadratic equation, I've been working on it for an hour and this should tell me the value of a, b and c where y is a(x^2). I'm a relative javascript beginner and would love some help. Why are the values of a, b and c not numbers? The variable names are in italian, in english and in something else(Not even I know what), but I commented what they are. That's one of my bad traits as a student that usually works alone, sorry if it's not easy to understand.
<script type="text/javascript">
var equa=prompt("Scrivi l'equazione senza spazi usando x come incognita e y come x^2");
var a = 0.0; b = 0.0; c = 0.0;//ax2+bx+c
var prima = true; //before or after equal?
var ope = 1;//1add 2sub 3mul 4div
var lasto = 0.0;//last number, used for div and mul
var lastos = 3; //1a2b3c
var errore=0;//is something messed up?
for(var i = 0; i < equa.length;i=i){
if(equa.charAt(i)=='='){
prima = false;
i++;
}else if(equa.charAt(i)=='+'){
ope=1;
i++;
}else if(equa.charAt(i)=='-'){
ope=2;
i++;
}else if(equa.charAt(i)=='*'){
ope=3;
i++;
}else if(equa.charAt(i)=='/'){
ope=4;
i++;
}else{
var nume = "";//Current number in string form
while(i<equa.length && equa.charAt(i)>'0' && equa.charAt(i)<'9'){
nume+=equa.charAt(i);
i++;
}
var lasnum = 0.0;//current number in float form
var lasval = 3; //1a2b3c
if(equa.charAt(i) == 'x'){
lasnum=parseFloat(nume);
lasval = 2;
}else if(equa.charAt(i) == 'y'){
lasnum=parseFloat(nume);
lasval = 1;
}else{
lasnum = parseFloat(nume);
lasval=3;
}
i++;
if( (ope == 1 || ope == 2) && !(equa.charAt(i) =='*' || equa.charAt(i) == '/')){
if(lasval == 1){
if(prima) a+=lasnum;
else a-=lasnum;
}
else if(lasval == 2){
if(prima) b+=lasnum;
else b-=lasnum;
}
else {
if(prima) c+=lasnum;
else c-=lasnum;
}
}else if( (ope==1 || ope == 2) && (equa.charAt(i) =='*' || equa.charAt(i) == '/')){
//zitto e fermo
lasto=lasnum;
lastos=lasval;
}else if( (ope==3||ope == 4)){
if(ope==3){
if(lastos==3){
lasnum*=lasto;
}
if(lastos == 2){
if(lastval==3){
lasnum*=lasto;
lastval=2;
}
if(lastval==2){
lasnum*=lasto;
lastval=1;
}
if(lastval==1){
errore=1;
}
}
if(lastos == 1){
if(lastval == 3){
lasnum*=lasto;
lastval=1;
}else{
errore=1;
}
}
}
if(ope == 4){
if(lastos == 1){
if(lastval==3){
lasnum/=lasto;
lastval=1;
}
if(lastval==2){
lasnum/=lasto;
lastval=2;
}
if(lastval==1){
lasnum/=lasto;
lastval=3;
}
}
if(lastos == 2){
if(lastval==1){
errore=1;
}
if(lastval==2){
lasnum/=lasto;
lastval=3;
}
if(lastval==3){
lasnum/=lasto;
lastval=2;
}
}
if(lastos == 3){
if(lastval==3){
lasnum/=lasto;
}else{
errore=1;
}
}
}
if(equa.charAt(i) =='*' || equa.charAt(i) == '/'){
lasto=lasnum;
lasto=lasval;
}else{
if(lasval == 1){
if(prima) a+=lasnum;
else a-=lasnum;
}
else if(lasval == 2){
if(prima) b+=lasnum;
else b-=lasnum;
}
else {
if(prima) c+=lasnum;
else c-=lasnum;
}
lasto=0;
lastos=3;
}
}
}
}
if(errore==0){
alert("a ="+a+" b="+b+" c="+c);
}else{
alert("AOOOOOOo");
}
</script>
Since the expected input should be in the format "15y+3x+5=20" for example, then this is a simple regular expression:
var equa = prompt("Scrivi l'equazione senza spazi usando x come incognita e y come x^2");
var regex = /^([0-9.]+)y\+([0-9.]+)x\+([0-9.]+)=([0-9.]+)$/;
var matches = regex.exec(equa);
if (matches) {
var a = parseFloat(matches[1]);
var b = parseFloat(matches[2]);
var c = parseFloat(matches[3]) - parseFloat(matches[4]);
var discriminant = b*b - 4*a*c;
if (discriminant < 0) {
alert('No real solutions');
}
else {
var root = Math.sqrt(discriminant);
alert('Root: ' + ((-b + root)/(2*a)) + ', ' + ((-b - root)/(2*a)));
}
}
else {
alert("AOOOOOOo");
}

Shortening if, else if, else if ... else using loops

I have the following lines of code:
$(function(){
$("div").scroll(function() {
function hpos(id) {
var pos = $("#" + id).position();
return pos.top;
}
function final(id) {
$("#header").html($("#" + id).html()),
$("h1").css("visibility","visible"),
$("#" + id).css("visibility","hidden");
}
if (hpos(5) < 0) {
final(5);
}
else if (hpos(4) < 0) {
final(4);
}
else if (hpos(3) < 0) {
final(3);
}
else if (hpos(2) < 0) {
final(2);
}
else {
final(1);
}
});
});
Shouldn't I be able to shorten it by using a loop instead of the else if statements? I can't find a way to make the loops work with my position().
for (var i = 5; i > 0; i--){
if (hpos(i) < 0) {
final(i);
break;
}
}
would something like this work? Not tested by the way
This should be shorter:
$.each([5,4,3,2], function(i,v) {
if( hpos(v) < 0 ) {
final(v);
return false;
} else if( v === 2 ) {
final(1);
}
});
An easier way to do lots of else if statements is to use the case method.
In case you need a while version:
:)
var elemId = 5;
while (elemId > 1) {
if (hpos(elemId) < 0) {
break;
}
elemId--;
}
final(elemId);

Categories

Resources