Brainfuck compare 2 numbers as greater than or less than - brainfuck

How can I compare two numbers with an inequality? (greater than or less than)
I want to compare single digits
For example
1 2
5 3
9 2
etc.

This is the best way to compare two numbers.Why because, if you are intelligent enough, you can use the same code in bigger programs.It's highly portable.
Assume we have two numbers a,b.
we have two blocks : if( a>=b ) and else,
Hope its enough.
0 1 0 a b 0
Make the array like this. And point to the (4) i.e. point to the a
+>+< This is for managing if a=0 and b=0
[->-[>]<<] This is a magic loop. if a is the one which
reaches 0 first (a<b),then pointer will be at(4).
Else it will be at (3)
<[-
// BLOCK (a>=b)
//You are at (2) and do whatever you want and come back to (2).
//Its a must
]
<[-<
// BLOCK(a<b)
//You are at (1) and do whatever you want and come back to (1).
//Its a must
]
It will not affect the following program code as both the code blocks will end up in (1) You can do further coding assuming that pointer will reach (1)
Please remove the documentation if you copy the code. Because code contains some valid brainfuck symbols like < . , etc.

Once you know which is the distance between the two numbers you should or decrement both of them in the same loop iteration and then check both for being zero: you will understand which one is the smaller.
Eg:
+++++ > +++ < [->-< check is first is zero, then second]
(this is just to give you a hint, you will have to take care about equal numbers and similar issues.

I was thinking about this too, and while I'm sure this isn't the best solution, at least it can answer the question of which number is larger =)
The program asks for two characters, outputs '<' if the first is smaller, '>' if it is larger, and '=' if they are equal. After outputting one char, the program halts by asking for additional input.
+>,>,<<[>-[>>>]<[>>-[>++++++++++[->++++++<]>.,]++++++++++[->++++++<]>+.,]<-[>>>]<<[>>>++++++++++[->++++++<]>++.,]<<<]
Hopefully somewhat clearer:
+ init (0) to 1
>, read (1)
>, read (2)
<<[ loop forever
>-[>>>] decrement (1) going to (4) if (1) != 0
<[ goto (0) == 1 if (1) reached 0 (otherwise goto (3))
>>-[>++++++++++[->++++++<]>.,] decrement (2) printing lessthan if larger than 0
++++++++++[->++++++<]>+., if (2) == 0 print '='
]
<-[>>>] decrement (2) going to (5) if (2) != 0
<<[ goto (0) == 1 if (2) reached 0 (otherwise goto (3))
>>>++++++++++[->++++++<]>++., print largerthan since (2) reached 0 first
]
<<< goto(0)
]

I made a solution, that gives you back a boolean and the pointer always at the same point.
This is how it looks like at the beginning:
0 0 0 a b 0 0
p
And these are the two possible outputs:
0 0 0 0 0 1 0 #true
p
0 0 0 0 0 0 0 #false
p
The code:
>>>>
[ # while cell != 0
- # decrement a
[ # if a != 0
>- # decrement b
[ # if b != 0
< # go left
<-< # undo the finally-block;
] # finally-block
<[-]> # clear a
>+> # res = 1; move to end-position
<<< # undo the finally-block
] # finally-block
>[-]>> # clear b; res = 0; move to end-position
] #
minified version:
>>>>[-[>-[< <-<]<[-]>>+><<<]>[-]>>]

Given two numbers A and B, the following code will print A if A is greater than B, B if B is greater than A and C if both are equal.
>>>>>>>>>++++++[>+++++++++++<-]>[>+>+>+<<<-]>+>->
<<<<<<<<<<<,>,<
[->-<[>]<<]>>>[>>]>>>>>>>>.

No such thing exists in BF. The > and < in BF move the pointer to the right and to the left, respectively.

Related

How to recursively get the number of elements until reached all squares in 5 x 5 grid in scala

I have a grid 5 x 5 grid. And my initial position is at (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
I have a method that finds all possible position in 'L' shape from that position
So from (0,0).
So either
( x + 2 )( y + 1 )
or
( x + 1 )( y + 2 )
We have two positions
0 0 0 0 0
0 0 0 0 0
0 # 0 0 0
0 0 0 0 0
# 0 0 0 0
or
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 # 0 0
# 0 0 0 0
Then my method will call it self from the list of all the possible moves and finds the position of each one.
The recursion only breaks if the last position in the possible moves list is the same as the initial position.
So the possible moves for position:
(0)(0) is List((1,2),(2,1))
List((possible moves for (1,2) ), (possible moves for (2,1) ) )
and so on:
My method so far
def CountTour(dimension: Int, path: Path): Int = {
// possibleMoves returns list of possible moves
val Moves = possibleMoves(dimension, path, path.head).contains(path.last)
// if the last element is not the same as first position, and has visited the whole graph, then break the recursion
if (legalMoves && path.size == (dimension * dimension)) {
1
} else {
// else call the same method again with each possible move
val newList = for (i <- legal_moves(dimension, path, path.head)) yield i
count_tours(dimension,newList)
}
}
However this won't work. How can i fix it?
It looks to me like you don't actually have any working code for this yet. I say this because A) the code you posted has lots of holes, and B) I didn't get a straight answer when I asked what output you're currently getting. For these reasons (and because this looks like a homework assignment) I'm not going to post an answer with real code but, instead, I'll describe what I think should work.
The goal is to write a function (actually a method) that takes the dimension of the playing board, and a starting point on it, and returns a count of all paths (successive moves) that exhaust the board (no returning to an already visited square).
1st - From any starting point there are 8 different positions that can be moved to (2 steps to the east/west/north/south and then 1 step to the left/right). I'd write a procedure that takes the grid dimensions and a starting point. It first creates a collection (maybe a List) of all 8 possible new locations and then keeps only those that fall within the grid (i.e. no negative numbers or coordinates larger than the grid dimension).
2nd - That list will have to be checked against the list of places that have already been visited and any duplicates removed. I'd use the diff method. Note that ...
possible_moves diff already_been_there // one result
already_been_there diff possible_moves // different result
One of those is the one you want.
3rd - Now you have a list of all permissible moves. If that list is empty then you're at the end of the road and there are no more moves to make. Return 1 because you've found one path that exhausts the board.
4th - If the list is not empty then you want to re-call this same procedure (recursion) with a new starting point and an updated list of already-been-there squares. The problem is that this list has at least one, and maybe as many as eight, new locations. How can you invoke the recursive call a different number of times with each iteration? Well, what you want to do is change your list from a list of new locations to a list of returned values from the recursive call. You know how to turn a List[A] into a List[B]? (Hint: it rhymes with "nap".)
5th - If you've gotten this far then you have a list of numbers, each is a count of how many ways to exhaust the board from each new starting point. Add them together and you've got a count of how many ways to exhaust the board from this starting point, and that's the number you return.
If I've described your goal correctly, and I've coded it up correctly, then you can check my work. For a 5X5 board, starting at 0,0, I came up with 625,308 different paths. (17 lines of code, but I wasn't trying to be terribly concise.)

How Jump instruction is executed based on value of Out- The Alu Output

Figure from The Elements of Computer System (Nand2Tetris)
Have a look at the scenario where
j1 = 1 (out < 0 )
j2 = 0 (out = 0 )
j3 = 1 (out > 0 )
How this scenario is possible as out < 0 is true as well as out > 0 but out = 0 is false. How out can have both positive and negative values at the same time?
In other words when JNE instruction is going to execute although it theoretically seems possible to me but practically its not?
If out < 0, the jump is executed if j1 = 1.
If out = 0, the jump is executed if j2 = 1.
If out > 0, the jump is executed if j3 = 1.
Hopefully now you can understand the table better. In particular, JNE is executed if out is non-zero, and is skipped if out is zero.
The mnemonic makes sense if those are match-any conditions, not match-all. i.e. jump if the difference is greater or less than zero, but not if it is zero.
Specifically, sub x, y / jne target works the usual way: it jumps if x and y were equal before the subtraction. (So the subtraction result is zero). This is what the if(out!=0) jump in the Effect column is talking about.
IDK the syntax for Nand2Tetris, but hopefully the idea is clear.
BTW, on x86 JNZ is a synonym for JNE, so you can use whichever one is semantically relevant. JNE only really makes sense after something that works as a compare, even though most operations set ZF based on whether the result is zero or not.

Detect contiguous numbers - MATLAB

I coded a program that create some bunch of binary numbers like this:
out = [0,1,1,0,1,1,1,0,0,0,1,0];
I want check existence of nine 1 digit together in above out, for example when we have this in our output:
out_2 = [0,0,0,0,1,1,1,1,1,1,1,1,1];
or
out_3 = [0,0,0,1,1,1,1,0,0,1,0,1,1,1,1,1,1,1,1,1,0,0,0,1,1,0];
condition variable should be set to 1. We don't know exact position of start of ones in outvariable. It is random. I only want find existence of duplicate ones values in above variable (one occurrence or more).
PS.
We are searching for a general answer to find other duplicate numbers (not only 1 here and not only for binary data. this is just an example)
You can use convolution to solve such r-contiguous detection cases.
Case #1 : To find contiguous 1s in a binary array -
check = any(conv(double(input_arr),ones(r,1))>=r)
Sample run -
input_arr =
0 0 0 0 1 1 1 1 1 1 1 1 1
r =
9
check =
1
Case #2 : For detecting any number as contiguous, you could modify it a bit, like so -
check = any(conv(double(diff(input_arr)==0),ones(1,r-1))>=r-1)
Sample run -
input_arr =
3 5 2 4 4 4 5 5 2 2
r =
3
check =
1
To save Stackoverflow from further duplicates, also feel free to look into related problems -
Fast r-contiguous matching (based on location similarities).
r-contiguous matching, MATLAB.

how to count number of results in scratch

I am using scratch. I acquire two values from the user and have to find the numbers divisible by 2 & 3 between those values . How can I count those numbers without using arrays ( just by using basic operations) ?
If you only need to count those numbers, arrays are not needed. Just iterate through the range and count:
Here's what you can do (do mind me, I am not good at creating questions and variables) ...
when flag clicked
ask (starting number is?) and wait
set (startrange) to (answer)
ask (ending number is?) and wait
set (endrange) to (answer)
set (counter) to (startrange)
set (divisibleby2) to (0)
set (divisibleby3) to (0)
set (divisibleby6) to (0)
repeat until counter = endrange
if (counter) mod 6 = 0
change (divisibleby6) by (1)
else
if (counter) mod 3 = 0
change (divisibleby3) by (1)
else
if (counter) mod 2 = 0
change (divisibleby2) by (1)
say (join (The number of numbers from the two inputs that are divisible by 2, 3 is) ((divisibleby2) + ((divisibleby3) + (divisibleby6)))
So, why is a divisibleby6 variable needed? It is because some numbers are divisible by 2 and 3 simultaneously, which means, the number would be recorded twice if the code was altered. However, if you want this to happen, this would be the code for you:
hen flag clicked
ask (starting number is?) and wait
set (startrange) to (answer)
ask (ending number is?) and wait
set (endrange) to (answer)
set (counter) to (startrange)
set (divisibleby2) to (0)
set (divisibleby3) to (0)
repeat until counter = endrange
if (counter) mod 3 = 0
change (divisibleby3) by (1)
if (counter) mod 2 = 0
change (divisibleby2) by (1)
say (join (The number of numbers from the two inputs that are divisible by 2, 3 is) ((divisibleby2) + (divisibleby3))

Is there any way to reverse the order of bits in matlab

What I am trying is getting binary value of a number e.g
de2bi(234)
Which results me in having this answer :
0 1 0 1 0 1 1 1
now what I want is that is its reverse order without changing its values like this :
11101010
i have tried bitrevorder() function but i am not having my desired answer. any help and suggestions will be appreciated.
Example:
>>de2bi(234)
ans = 0 1 0 1 0 1 1 1
>> fliplr(ans)
ans =
1 1 1 0 1 0 1 0
Use the function fliplr. It can be used to reverse the order of array.
Try using the flag 'left-msb' (according to the documentation in http://www.mathworks.com/help/comm/ref/de2bi.html)
The commands below show how to convert a decimal integer to base three without specifying the number of columns in the output matrix. They also show how to place the most significant digit on the left instead of on the right.
t = de2bi(12,[],3) % Convert 12 to base 3.
tleft = de2bi(12,[],3,'left-msb') % Significant digit on left
The output is
t =
0 1 1
tleft =
1 1 0
You just need to use the 'left-msb' option in de2bi:
>>de2bi(234, 'left-msb')
ans =
1 1 1 0 1 0 1 0
You can use a more simple command called dec2bin which produces the desired result:
>> dec2bin(234)
ans =
11101010
Here is the docs: http://www.mathworks.com/help/matlab/ref/dec2bin.html?refresh=true
While this is an old question, I needed to do the same thing for a CRC checksum and feel I should share the results.
In my case I need to reverse 16bit numbers, so, I've tried three methods:
1) Using fliplr() to reverse as per the suggestions:
uint16(bin2dec(fliplr(dec2bin(data,16))))
To test out the speed I decided to try and checksum 12MB of data. Using the above code in my CRC, it took 2000 seconds to complete! Most of this time was performing the bit reversal.
2) I then devised a more optimal solution, though not a one line code it is optimised for speed:
reverse = uint16(0);
for i=1:16
reverse = bitor(bitshift(reverse,1), uint16(bitand(forward,1)));
forward = bitshift(forward,-1);
end
Using the same CRC code, but with this used instead of (1), it took a little over 500 seconds to complete, so already it makes the CRC calculations four times faster!
3) That is still too much time for my liking, so instead I moved everything to a mex function. This allows the use of code from the bit twiddling examples that are floating around for optimum performance. I moved the whole CRC code to the mex function and used the following two other functions to do the bit reversal.
unsigned char crcBitReverse8(unsigned char forward) {
return (unsigned char)(((forward * 0x0802LU & 0x22110LU) | (forward * 0x8020LU & 0x88440LU)) * 0x10101LU >> 16);
}
unsigned short crcBitReverse16(unsigned short forward) {
unsigned char inByte0 = (forward & 0xFF);
unsigned char inByte1 = (forward & 0xFF00) >> 8;
return (unsigned short )((crcBitReverse8(inByte0) << 8) | (crcBitReverse8(inByte1)));
}
Just for comparison, it took just 0.14 seconds to compute the CRC for the same 12MB data chunk (and there is no mistake in the calculation, the CRC checksums for all three methods match what is expected).
So basically, if you have to do this a lot of times (e.g. for CRC) I seriously suggest you write a mex function for doing the reversal. For such a simple operation, native MATLAB code is embarrassing slow.
why not use bitget?
>> bitget( 234, 8:-1:1 )
ans =
1 1 1 0 1 0 1 0