How to increment element of block after found element? - red

Given player-choices: ["rock" 0 "paper" 0 "scissors" 0]
How could I increment the value after "paper" in this block by searching for "paper"?

>> player-choices/("paper"): player-choices/("paper") + 1
== 1

Consider, also, that you may not need to use strings in your data block.
player-choices: [rock 0 paper 0 scissors 0]
player-choices/paper: player-choices/paper + 1
You can also write a generic incr func, like this:
incr: function [
"Increments a value or series index"
value [scalar! series! any-word! any-path!] "If value is a word, it will refer to the incremented value"
/by "Change by this amount"
amount [scalar!]
][
amount: any [amount 1]
if integer? value [return add value amount] ;-- This speeds up our most common case by 4.5x
; though we are still 5x slower than just adding
; 1 to an int directly and doing nothing else.
; All this just to be smart about incrementing percents.
; The question is whether we want to do this, so the default 'incr
; call seems arguably nicer. But if we don't do this it is at
; least easy to explain.
if all [
integer? amount
1 = absolute amount
any [percent? value percent? attempt [get value]]
][amount: to percent! (1% * sign? amount)] ;-- % * int == float, so we cast.
case [
scalar? value [add value amount]
any [
any-word? value
any-path? value ;!! Check any-path before series.
][
op: either series? get value [:skip][:add]
set value op get value amount
:value ;-- Return the word for chaining calls.
]
series? value [skip value amount] ;!! Check series after any-path.
]
]
And then do
incr 'player-choices/paper

You can also keep a reference to the positions of the values in the block to change them later:
player-choices: ["rock" 0 "paper" 0 "scissors" 0]
rock-pos: find/tail player-choices "rock"
paper-pos: find/tail player-choices "paper"
scissors-pos: find/tail player-choices "scissors"
change paper-pos 1 + paper-pos/1
player-choices
; == ["rock" 0 "paper" 1 "scissors" 0]

Given player-choices: ["rock" 0 "paper" 0 "scissors" 0]
How could I increment the value after "paper" in this block by searching for "paper"?
poke player-choices index? next find player-choices "paper" 1 + select player-choices "paper"
Broken down:
>> ? poke
USAGE:
POKE series index value
DESCRIPTION:
Replaces the series value at a given index, and returns the new value.
The series player-choices.
The index is position in player-choices of the value after "paper"
The value is whatever the current value is after paper added to 1
Find will return either the series where a value is found, or NONE.
>> find player-choices "paper"
== ["paper" 0 "scissors" 0]
But you want the index of next value hence:
>> index? next find player-choices "paper"
== 4
Select will return the next value of a series if it finds the value, which precedes it. Otherwise it will return none.
>> select pc "paper"
== 0
But we want to increase it by one, thus
>> 1 + select pc "paper"
== 1

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 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))

define the prompted number is prime or not

i want a code to define the prompted number by user is prime or not . since it's an assignment
i'm not allowed to use ' isprime ' predefined code .
the following approach was not useful :
N = input( 'please enter a positive enteger value = ' ) ;
Quotient = floor(N - (mod(N,2)./2)) ;
for i = 1 : Quotient
if mod(N,i ) == 0
fprintf(' your prompted number is not prime ' ) ;
if mod(N,i) ~= 0
fprintf(' your prompted number is prime ' ) ;
end
end
end
for example if i enter a prime number like 13 it results in this :
your prompted number is prime
but if i enter a Non-prime num like 12 it repeats the ' your prompted number is prime ' message for 10 times .
for i = 1 : Quotient
if mod(N,i ) == 0
That will give you every number since x mod 1 is always zero. In other words, the remainder (when you divide any positive integer by one) is zero, since all of them divide perfectly.
You need to start at 2 rather than 1.
In addition, once you've found out the number is not prime, you should stop the loop since there's no possibility of it becoming prime again after that :-) And, for efficiency, you only need to go up to the square root of the number since, if it has a factor above that, you would have already found the equivalent factor below that.
The pseudo-code for such a beast would be:
set isprime to true
set chkval to 2
while chkval * chkval <= number:
if number mod chkval is zero:
set isprime to false
exit while
end if
increment chkval
end while
if isprime:
say number, " is prime"
else:
say number, " is composite"
Try to find factors and as soon as you find one you know it's not prime:
prime = true
for f = 2:ceil(sqrt(N)) %// Start from 2 as prime numbers DO have 1 as a factor. Anything larger than sqrt(N) will have to have a corresponding factor smaller than this so there is no point checking them
if mod(N,f) == 0
prime = false;
break;
end
end
There are 2 problems with your code. First, as already explained by paxdiablo, you need to start your loop from 2. Secondly you have nested your if statements, and since they are mutually exclusive conditions, the inner condition will never trigger.

Multiply a number by 2 in Brainfuck?

Given an arbitrarily long number, how can I output its double? I know how to multiply small numbers together as long as the result is <10, but what about larger integers like 32984335, and doubling something like that? I don't know the right way to handle something like this.
This is the algorithm you need to implement:
Start the current count with 0;
Multiply the current count by ten: this can be achieved by dupping 10 times, and then adding all dupes together;
Read a digit;
If it's null proceed to 8;
Convert it to an actual number: this can be achieved by subtracting 48;
Add it to the current count;
Proceed to 2;
Duplicate the current count;
Adding the dupes together;
Divide by ten using repeated subtraction; keep quotient and remainder;
Grab the remainder;
Make it a digit (add 48);
Print it;
Grab the quotient from 10;
If it's not zero, goto 10;
The end.
All these steps consists of basic brainfuck idioms, so it should be easy to implement.
Here's a start. It will multiply a byte of input, but I think you can build off it to make it work for any number. Basically, you take in a number, and store the number to multiply by (2) in the next pointer. You loop decrementing the first number, and then nest a loop decrementing the second number; in each iteration of the inner loop, you increment the pointer to the right of your second operand. This is your result.
, take input to ptr 0
[
- decrement first operand (input)
>++ number to multiply by (2) at ptr 1
[
>+ result in ptr 2
<- decrement second operand (2)
]
<
]
>> move to result
Here is my BF code: http://ideone.com/2Y9pk8
->>+>,+
[
-----------
[
-->++++++[-<------>]<
[->+<[->+<[->+<[->+<[>----<-<+>[->+<]]]]]]>
[-<++>]<+
>,+
[
-----------
[->+<]
]
>[-<+>]<
]
<[<]
>-[<++++++++[->++++++<]>.[-]]
>[<++++++++[->++++++<]>-.[-]>]
++++++++++.[-]
<+[-<+]
->>+>,+
]
It reads each number in each line until EOF, and multiply all numbers by two..
Here is the code for multiplying a number by 2.
,[>++<-]>.
Hope this helps.

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.