Programming two trains to intersect without positional data or communication (logic puzzle) [closed] - algorithm

Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 12 years ago.
Improve this question
A helicopter drops two trains, each on a parachute, onto a straight infinite railway line.
There is an undefined distance between the two trains.
Each faces the same direction, and upon landing, the parachute attached to each train falls to the ground next to the train and detaches.
Each train has a microchip that controls its motion. The chips are identical.
There is no way for the trains to know where they are.
You need to write the code in the chip to make the trains bump into each other.
Each line of code takes a single clock cycle to execute.
You can use the following commands (and only these):
MF - moves the train forward
MB - moves the train backward
IF (P) - conditional that is satisfied if the train is next to a parachute. There is no "then" to this IF statement.
GOTO

Make each train move forwards slowly until it finds a parachute. When the back train finds the parachute of the front train, make it move forwards faster to catch up with the front train.
1. MF
2. IF(P)
3. GOTO 5
4. GOTO 1
5. MF
6. GOTO 5
If you want to make it take less time for the trains to reach each other, at the cost of some extra lines of code, you can unroll the second loop.

label1: MF
If (P)
{
// Do nothing (because of no then?)
}
ELSE
{
MF;
MB;
GOTO label1;
}
label 2:MF
GOTO label2;
GO forward 2 times, backward 1 times until meet the other train's parachute go forward like crazy (to bump into the other - it's still Forward then backward - meaning it's go slower). I use MF one time in label 2, mean it take 2 clock cycle to go one step forward.
In label1 it took 5 clock cycle to go forward one steps. So if we use more MF in label2 two of them will bump into eachother faster.
No variable used.

Related

How to improve the performance of an alpha-beta minimax method in Ruby?

I’ve been a programming student for about six months. I’d been wanting to write a chess game since a long time, and finally made it. I’m very happy with the result, however, there’s a point I don’t know how to address. The AI is based on an alpha-beta pruning #minimax method that chooses the best move on the basis of the best possible outcome for the current player, with a depth default value of 3, which means the computer can think ahead 3 turns. The computer does choose the correct move, but the method in its current implementation is very slow.
#provisional makes and 'unmakes' a possible move, and returns the value returned from the code block. The evaluation function #evaluate is very simple, it’s just a sum of the material value of the pieces and their location values according to how are they placed on the board.
I’d really appreciate some light here, as I don’t know how to get a faster version of this method.
Thank you so much for your time.
This is the method:
def minimax(move, depth, alpha, beta, maximizing_player)
return board.evaluate if depth.zero?
board.provisional(move, color) do
if maximizing_player
best_minimizing_evaluation = Float::INFINITY
board.generate_moves(:black).each do |possible_move|
evaluation = minimax(possible_move, depth - 1, alpha, beta, false)
best_minimizing_evaluation = [best_minimizing_evaluation, evaluation].min
beta = [beta, evaluation].min
break if beta <= alpha
end
best_minimizing_evaluation
else
best_maximizing_evaluation = -Float::INFINITY
board.generate_moves(:white).each do |possible_move|
evaluation = minimax(possible_move, depth - 1, alpha, beta, true)
best_maximizing_evaluation = [best_maximizing_evaluation, evaluation].max
alpha = [alpha, evaluation].max
break if beta <= alpha
end
best_maximizing_evaluation
end
end
end
With an initial depth value of 3, it takes between 15 and 50 seconds for the method to resolve and return the chosen move; this is a lot, and makes the game barely enjoyable. Changing the depth value to 2, the times are more reasonable, being about a third of the previous times, but I’d really like to keep the depth at 3. With a depth of 1, of course, it takes less than a second.
I realize that some improvements can be made, however, I don’t know how to:
Will a negamax version of this method significantly improve its performance?
I’m aware of the Tail Recursion Optimization, however, is it possible in this case? I don’t know if it is a tree-generating method like this.
I’ve been told that pre-sorting the moves somehow before they are evaluated can improve the performance in alpha-beta minimaxes, but, how can I sort the moves? I can’t sort them by the immediate outcome, because, for instance, sometimes it’s worth to sacrifice a piece to win a better position. I could sort them by best possible outcome in 2 turns... but then I'd be computing twice, once for the sorting of the moves, and once for the actual move evaluation.
It's implementing a transposition table worth it? I mean, there are tons of potential positions, and they easy can make a file really big. For example, in a day, the program generated a 100 MB text file, and I didn't notice a huge performance improvement, as the computer don't always makes the same moves, and neither do I. The different position for a chess game are innumerable, unlike in a game like Tic Tac Toe.
Thank you so much.

Prove the Stack-Turing Machine is equivalent to the Classic TM [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 3 years ago.
Improve this question
Consider a “Stack-Turing Machine” variant that operates with one infinite tape and one stack. At each step through the tape, the machine reads the input from the current tape location and from the top of the stack, and then transitions states, writes to the tape, and moves along the tape (like a classic TM) and also can pop from and/or push to the stack (like a classic PDA). In other words: the classic TM has transition function: 𝛿(𝑞𝑖 , 𝑎) → (𝑞𝑗 , 𝑏, 𝐿 ∪ 𝑅) where q is state, a and b are input/output for tape the classic PDA has transition function: 𝛿(𝑞𝑖 , 𝑐) → (𝑞𝑗 , 𝑑) where q is state, c is initial top of stack, and d is newly pushed top of stack the stack-TM has transition function 𝛿(𝑞𝑖 , 𝑎, 𝑐) → (𝑞𝑗 , 𝑏, 𝐿 ∪ 𝑅, 𝑑) merging TM and PDA Prove the Stack-Turing Machine is equivalent to the Classic TM.
!(https://imgur.com/a/daJgTTb)
Not sure how to approach this.
No Code Involved; theory of computation Proof.
None, this is a theory of computation Proof.
A Stack-TM can simulate a regular TM by simply doing nothing interesting with the stack. A two-tape TM can simulate a Stack-TM by treating the second tape as a stack (only writing to the end and reading from the end by clearing off a symbol). Finally, a regular TM can simulate a two-tape TM since we know that multi-tape TMs are equivalent to single-tape TMs (assuming we know this result). Due to transitivity of the simulation relationship, all the systems are equivalent in that they can all simulate each other.

How many number of primitive operations does a 16, 32 or a 64-bit processor execute to perform logical right shift of an N-bit Binary number? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 7 years ago.
Improve this question
Recently,I have been trying to understand how the Binary Extended Euclidean Algorithm works at the processor level. This question is all about finding an Inverse element in GF(2^m) with polynomial basis.
Generally I came across the Extended Euclidean Algorithm for evaluating an inverse element but the fact is that it involves too many addition and multiplication operations. The Binary EEA algorithm requires just bit shifting operations (equivalent to division by 2--logical shift right). The algorithm is in this link, page number 8.
In step 3 and 5 of this algorithm, every iteration shifts the parameters u and b by 1 bit to the right adding zero to the MSB at the same time. The loop ends when u == 1 and returns b. My question is how many primitive operations does a processor (say a 32 bit processor for example) perform in step 3 or step 5 of every iteration?
I came across barrel shifter and I am quite confused about how fast the shifting takes place. Should I really consider these primitive operations or should I ignore them if because the shifting may be faster?
It would really help me a lot if someone would show the primitive operations for the case where the size of u is 194 bits.
In case you might be wondering about the denominator x in step 3 and 5 of the algorithm, its the polynomial representation and x means nothing but 10 in binary and parameter u is an N-bit binary number.
There is no generic answer to this question: you can use portable code that will be tedious to optimize or highly machine specific code that will be even more complicated to optimize without breaking.
If you want real performance, you have to use MMX/AVX registers on the maximum width you can get your hands on. Intel provides lightweight wrappers on low-level instructions as macros and inline functions.
Always use unsigned types for your shifting operations to avoid unnecessary steps.
Usually ther is a "right shift" assembly OP code which is able to right shift a register a given number of bits. Such an operation takes one cycle.
This assumes thet your value is already loaded to the register however.
The best answer anyway: Implement this algorithm in a low level language (C, C++) and look at the assembly code produced by the compiler.

Tic-Tac-Toe Strategy - 60's MiniVac 601 Logic

Tic-Tac-Toe seems to be a fairly solved problem space, most 100% solutions seem to search through a finite tree of possibilities to find a path to winning.
However, I came across something from a computer-simulation toy from the 60's, The MiniVac 601. http://en.wikipedia.org/wiki/Minivac_601
This 'comptuer' consisted of 6 relays that could be hooked up to solve various solutions. It had a game section, which had this description on a program for Tic-Tac-Toe, that claims to be unbeatable as long as the Minivac went first.
Since most solutions to this seem to require lots of memory or computational power, its surprising to see a solution using a computer of 6 relays. Obviously I haven't seen this algorithm before, not sure I can figure it out. Attempts to solve this on a pad and paper seem to indicate a fairly easy win against the computer.
http://www.ccapitalia.net/descarga/docs/1961-minivac601-book5&6.pdf
"with this program, MINI VAC can not lose. The human opponent may
tie the game, but he can never win. This is because of the decision
rules which are the basis of the program. The M IN IV A C is so
programmed that the machine will move 5 squares to the right of its
own last move if and only if the human opponent has blocked that last
move by moving 4 squares to the right of the machine's last move. If
the human player did not move 4 squares to the right of the machine's
last move, M IN IV A C will move into that square and indicate a win.
If the hu­ man player consistently follows the "move 4 to the right"
rule, every game will end in a tie. This program requires that M IN IV
A C make the first move; the machine's first move will always be to
the center of the game matrix. A program which would allow the human
opponent to move first would require more storage and processing
capacity than is available on M IN IV A C
601. Such a program would, of course, be much more complex than the program which permits the machine to move first"
EDIT: OK so the Question a little more explicitly: Is this a real solution to solving Tic-Tac-Toe? Does anyone recognize this algorithm, it seems very very simple to not be easily searchable.
I think it is all in the layout of the "board". If you look at the 601 units tic-tac-toe area, 9 is in the middle and 1 is top left numbered sequentially clockwise around 9.
The "computer" goes first in the 9 position. The user then goes next.
If the user hasn't gone in position 1 (top left) then that is the next position for the computer. The user then goes next. Then the computer tries to go in position 1+4 (5 - bottom right). If the position is not available it will go in 1+5 (6 - bottom middle). x + 4 is always opposite the previous move, and since the computer has the center position it will be a winning move.

AI: selecting immediate acceleration/rotation to get to a final point

I'm working on a game where on each update of the game loop, the AI is run. During this update, I have the chance to turn the AI-controlled entity and/or make it accelerate in the direction it is facing. I want it to reach a final location (within reasonable range) and at that location have a specific velocity and direction (again it doesn't need to be exact) That is, given a current:
P0(x, y) = Current position vector
V0(x, y) = Current velocity vector (units/second)
θ0 = Current direction (radians)
τmax = Max turn speed (radians/second)
αmax = Max acceleration (units/second^2)
|V|max = Absolute max speed (units/second)
Pf(x, y) = Target position vector
Vf(x, y) = Target velocity vector (units/second)
θf = Target rotation (radians)
Select an immediate:
τ = A turn speed within [-τmax, τmax]
α = An acceleration scalar within [0, αmax] (must accelerate in direction it's currently facing)
Such that these are minimized:
t = Total time to move to the destination
|Pt-Pf| = Distance from target position at end
|Vt-Vf| = Deviation from target velocity at end
|θt-θf| = Deviation from target rotation at end (wrapped to (-π,π))
The parameters can be re-computed during each iteration of the game loop. A picture says 1000 words so for example given the current state as the blue dude, reach approximately the state of the red dude within as short a time as possible (arrows are velocity):
Pic http://public.blu.livefilestore.com/y1p6zWlGWeATDQCM80G6gaDaX43BUik0DbFukbwE9I4rMk8axYpKwVS5-43rbwG9aZQmttJXd68NDAtYpYL6ugQXg/words.gif
Assuming a constant α and τ for Δt (Δt → 0 for an ideal solution) and splitting position/velocity into components, this gives (I think, my math is probably off):
Equations http://public.blu.livefilestore.com/y1p6zWlGWeATDTF9DZsTdHiio4dAKGrvSzg904W9cOeaeLpAE3MJzGZFokcZ-ZY21d0RGQ7VTxHIS88uC8-iDAV7g/equations.gif
(EDIT: that last one should be θ = θ0 + τΔt)
So, how do I select an immediate α and τ (remember these will be recomputed every iteration of the game loop, usually > 100 fps)? The simplest, most naieve way I can think of is:
Select a Δt equal to the average of the last few Δts between updates of the game loop (i.e. very small)
Compute the above 5 equations of the next step for all combinations of (α, τ) = {0, αmax} x {-τmax, 0, τmax} (only 6 combonations and 5 equations for each, so shouldn't take too long, and since they are run so often, the rather restrictive ranges will be amortized in the end)
Assign weights to position, velocity and rotation. Perhaps these weights could be dynamic (i.e. the further from position the entity is, the more position is weighted).
Greedily choose the one that minimizes these for the location Δt from now.
Its potentially fast & simple, however, there are a few glaring problems with this:
Arbitrary selection of weights
It's a greedy algorithm that (by its very nature) can't backtrack
It doesn't really take into account the problem space
If it frequently changes acceleration or turns, the animation could look "jerky".
Note that while the algorithm can (and probably should) save state between iterations, but Pf, Vf and θf can change every iteration (i.e. if the entity is trying to follow/position itself near another), so the algorithm needs to be able to adapt to changing conditions.
Any ideas? Is there a simple solution for this I'm missing?
Thanks,
Robert
sounds like you want a PD controller. Basically draw a line from the current position to the target. Then take the line direction in radians, that's your target radians. The current error in radians is current heading - line heading. Call it Eh. (heading error) then you say the current turn rate is going to be KpEh+d/dt EhKd. do this every step with a new line.
thats for heading
acceleration is "Accelerate until I've reached max speed or I wont be able to stop in time". you threw up a bunch of integrals so I'm sure you'll be fine with that calculation.
I case you're wondering, yes I've solved this problem before, PD controller works. don't bother with PID, don't need it in this case. Prototype in matlab. There is one thing I've left out, you need to have a trigger, like "i'm getting really close now" so I should start turning to get into the target. I just read your clarification about "only accelerating in the direction we're heading". that changes things a bit but not too much. that means to need to approach the target "from behind" meaning that the line target will have to be behind the real target, when you get near the behind target, follow a new line that will guide you to the real target. You'll also want to follow the lines, rather than just pick a heading and try to stick with it. So don't update the line each frame, just say the error is equal to the SIGNED DISTANCE FROM THE CURRENT TARGET LINE. The PD will give you a turn rate, acceleration is trivial, so you're set. you'll need to tweak Kd and Kp by head, that's why i said matlab first. (Octave is good too)
good luck, hope this points you in the right direction ;)
pun intended.
EDIT: I just read that...lots of stuff, wrote real quick. this is a line following solution to your problem, just google line following to accompany this answer if you want to take this solution as a basis to solving the problem.
I would like to suggest that yout consider http://en.wikipedia.org/wiki/Bang%E2%80%93bang_control (Bang-bang control) as well as a PID or PD. The things you are trying to minimise don't seem to produce any penalty for pushing the accelerator down as far as it will go, until it comes time to push the brake down as far as it will go, except for your point about how jerky this will look. At the very least, this provides some sort of justification for your initial guess.

Resources