How to recursively get the number of elements until reached all squares in 5 x 5 grid in scala - 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.)

Related

Why code displays error?

Can you help me and explain why this code gives a error? I would like to use XOR, but I can not. I'm trying to do this using the following formula:"A XOR B= (A AND ~B)OR(~A AND B). Can you hint what did I do wrong?
public = 'public';
password = 'passwd';
if length(public)== length(password)
public = uint8(public);
password = uint8(password);
negpublic = ~(dec2bin(public));
negpassword = ~(dec2bin(password));
score = bitor(bitand(public,negpassword),bitand(negpublic,password));
public = dec2bin(public);
password = char(password)
else
fprintf('length not ok!\n' );
end
Normally I do not provide answers for homework questions, but it seems as you are almost there. The logic is done and that was the important part I guess.
Regarding the code, there is a few of bugs here. The function dec2bin will deceit you. As far as I know, matlab does not support binary format. The dec2bin actually convert the number to an array of char :(. However, having the text in binary format is not a requirement for doing bitwise operations. I cannot really see the use for a binary format in matlab since the smallest data unit for most computer achitectures normally is one byte.
You can use the function bitcmp (bitwise complement, which is another word for bitwise NOT) to do the negation. Secondly, bitwise operations can also work on vectors. Third, it is possible to define the negation as a variable, but bit operations are among the cheapest for most processors and operating systems so this is frankly not necessary for only two uses. So the content of everything is that you can simplify things a lot.
ab = 'ab'; bb = 'bb';
ab=uint8(ab); bb=uint8(bb);
bitor(bitand(ab,bitcmp(bb)), bitand(bb,bitcmp(ab)))
Why does the code yield error?
Let's first list the error:
Error using bitand Inputs must be signed or unsigned integers of the
same class or scalar doubles.
Error in foo (line 8)
score = bitor(bitand(public,negpassword),bitand(negpublic,password));
Ok, so the following line yields the error:
score = bitor(bitand(public,negpassword),bitand(negpublic,password));
We can break this down and see that both the following expressions yields errors on their own
bitand(public,negpassword)
bitand(negpublic,password)
Why? If we look at the the first of these two a bit closer, we see that public and negpassword and non-compliant for use with bitand:
public =
112 117 98 108 105 99
negpassword =
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
These two must be, at the very least, of the same dimension. See the reference for Bit-wise OR for details.
I'm not really sure what you're trying to achieve here, but not that Matlab has its own bitxor function:
public = 'public';
password = 'passwd';
if length(public)== length(password)
public = uint8(public);
password = uint8(password);
score = bitxor(public,password);
public = dec2bin(public);
password = char(password);
else
fprintf('length not ok!\n' );
end

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.

"/usr/bin/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";?

I found this line in the if.c of unix version 6.
ncom = "/usr/bin/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
Why are there so many x's?
And why would you set this?
The code you are talking of looks like this:
ncom = "/usr/bin/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
while(c=nargv[0][i]) {
ncom[9+i++] = c;
}
ncom[9+i] = '\0';
All those x's act as a buffer, they are overridden by the following loop.
Therefore the code effectively adds "/usr/bin/" to the command in nargv[0].
With a little more context the code is doing this:
execv(nargv[0], nargv, np);
execv(ncom+4, nargv, np);
execv(ncom, nargv, np);
If the given command in nargv[0] is "foo" it will first try to run "foo" then "/bin/foo" and finally "/usr/bin/foo".
Be aware that above is a good example how to not do such things:
If the string in nargv[0] happens to be longer than the number of x's, the code will happily continue copying data. This will override other parts of the stack. The result is a good example of a buffer overflow. (You allocate a buffer of some size and write more data than allocated.)
This example will demonstrate the problem:
#include <stdio.h>
int main(){
char s[]="abcde";
int i;
for(i=0;i<100;i++){
printf("position %2d contains value %3d\n",i,s[i]);
s[i]=0;
}
puts(s);
return 0;
}
If you run it it will (most probably) output this:
position 0 contains value 97
position 1 contains value 98
position 2 contains value 99
position 3 contains value 100
position 4 contains value 101
position 5 contains value 0
position 6 contains value 0
position 7 contains value 0
position 8 contains value 0
position 9 contains value 0
position 10 contains value 0
position 11 contains value 0
position 12 contains value 12
position 1 contains value 0
position 2 contains value 0
position 3 contains value 0
position 4 contains value 0
position 5 contains value 0
position 6 contains value 0
position 7 contains value 0
[...]
It will fill the string (containing the ASCII values 97 to 101) with zeroes and continue writing the memory where it will find the position of the variable i it will also set it to zero. Now i is zero and therefore the loop starts again, overriding the the already overridden string again and again.
Not only local variables can be overriden, also the return address of a function might get overriden resulting in either a "segmentation fault" or execution of arbitrary code, which is often used by malware.

Bound constraints ignored Matlab

I have the following code working out the efficient frontier for a portfolio of assets:
lb=Bounds(:,1);
ub=Bounds(:,2);
P = Portfolio('AssetList', AssetList,'LowerBound', lb, 'UpperBound', ub, 'Budget', 1);
P = P.estimateAssetMoments(AssetReturns)
[Passetmean, Passetcovar] = P.getAssetMoments
pwgt = P.estimateFrontier(20);
[prsk, pret] = P.estimatePortMoments(pwgt);
It works fine apart from the fact that it ignores the constraints to some extent (results below). How do I set the constraints to be hard constraints- i.e. prevent it from ignoring an upper bound of zero? For example, when I set an upper and lower bound to zero (i.e. I do not want a particular asset to be included in a portfolio) I still get values in the calculated portfolio weights for that asset, albeit very small ones, coming out as part of the optimised portfolio.
Lower bounds (lb), upper bounds (ub), and one of the portfolio weights (pwgt) are set out below:
lb ub pwgt(:,1)
0 0 1.06685493772574e-16
0 0 4.17200995972422e-16
0 0 0
0 0 2.76688394418301e-16
0 0 3.39138439553466e-16
0.192222222222222 0.252222222222222 0.192222222222222
0.0811111111111111 0.141111111111111 0.105624956477606
0.0912121212121212 0.151212121212121 0.0912121212121212
0.0912121212121212 0.151212121212121 0.0912121212121212
0.0306060606060606 0.0906060606060606 0.0306060606060606
0.0306060606060606 0.0906060606060606 0.0306060606060606
0.121515151515152 0.181515151515152 0.181515151515152
0.0508080808080808 0.110808080808081 0.110808080808081
0.00367003367003366 0.0636700336700337 0.0388531580005063
0.00367003367003366 0.0636700336700337 0.0636700336700338
0.00367003367003366 0.0636700336700337 0.0636700336700337
0 0 0
0 0 0
0 0 1.29236898960272e-16
I could use something like: pwgt=floor(pwgt*1000)/1000;, but is there not a more elegant solution than this?
The point is that your bound has not been ignored.
You are calculating with floating point numbers, and hence 0 and 4.17200995972422e-16 are both close enough to 0 to let your program allow them.
My recommendation would indeed be to round your results (or simply display less decimals with format short), however I would do the rounding like this:
pwgt=round(pwgt*100000)/100000;
Note that the other results may also be 'above' the upper bound, however this will not become visible due to the insignificance.
I had issues like this with a laminate/engineering properties code, which was propogating errors all over everything. I fixed it by taking all of the values I had, and systematically converting them from double to sym, and suddenly my 1e-16 values became real zeros, that I could also eval(val) and still see as zeros! This may help, but you may have to go inside of the .m files you're running, and have the numbers convert to sym with val = sym(val).
I can't remember for certain, but I think Matlab functions MIGHT change sym to double once they receive the data for their own internal processing.

Brainfuck compare 2 numbers as greater than or less than

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.