C++
Working on a problem for school, running 3 horses in a race and whoever finishes first is the winner. the 3 horses are supposed to run in sync like this
1|--------H------|
2|-------H-------|
3|---------H-----|
However my code runs the program correctly (generate a random number between 1 and 100 and if that number is less than 50 move the horse 1 space up). but it runs the first horse, then the 2nd and the 3rd last.
tried to look this up but none of the methods seem to work (using codeblocks (latest version Windows 10) for C++).
srand(time(NULL));
Horse1();
Horse2();
Horse3();
Github file: https://gist.github.com/EthanA2020/f16a699f1b8136a1da0350ab48acdda0
I don't think your issue is with the type of function but instead the structure of your program. No matter how you program, one operation must come before the next. Developers work with this by running each operation of the object (in your case the horse movement) side by side and checking later to see the outcome.
For example, lets use your horse scenario:
while "all horses" are less than "finish"
horse 1 moves
horse 2 moves
horse 3 moves
I am sure that you are familiar with loops so we'll use that here. Some set distance must exist to determine when a horse has finished. So you'll want to continue that loop while all horses have a distance less than that value. During each loop, each horse's movement value must either change or not (determined by your random movement function).
Now once this while loop has ended, you can be sure that at least one horse has crossed the finish line. All operations have been completed and you have a data set of the horses positions. This is the point where you check to see which horses have finished (I say horses plural because there is a chance that more than one horse or even all 3 finish at the same time, so be sure to factor that in at the end).
With that, your program structure should be something like:
while "all horses" are less than "finish"
horse 1 moves
horse 2 moves
horse 3 moves
//movement of horses complete
check and print the horses with a movement value of "finish"
I think you should do:
while (!horse(rand() % 100)) {
usleep(100);
}
Where horse(int n) moves horse n 1 position and if it reached the end, it returns true (to end the race). It does nothing if an invalid n (only 1 to 3 is valid) is passed to it.
Related
I've been trying to solve this problem in HackerRank called Bowling Pins. Basically you have to code a program that predicts who will win and who will lose. The rules of the game are:
Bowling pins are position horizontally and they are represented as a string of capital i's --> "IIII" (4 pins)
You can either knock down one single pin "I" or two pins that are next to each other "II"
"X" will represent the pins that are knocked down
Last player to knock down wins
Given the string "XIIX", this is a win, since I can knock down the two middle pins.
Given the string "IXIX", is a lose, since the next player will make the last move
Now, I tried to get a basic understanding of combination game theorem. I know that I have to calculate the mex and grundy in order to know who wins and who loses without actually playing the game.
Now my question is if I have three pins "III"
mex {1,2} = 0 , this means a lose. But what happens in the case that I knock down the single middle pin?
The next player turns will look like this "IXI", he/she can either knock down the left or the right pin, regardless I get the last pin and win. right?
I'm very new to these concepts and I'm not sure if I'm implementing the Sprague–Grundy theorem correctly for this game. Can someone explain this to me?
Here's a link to the problem I'm trying to solve --> https://www.hackerrank.com/challenges/bowling-pins/problem
I think this document has a really good explanation of the relevant theory: https://web.mit.edu/sp.268/www/nim.pdf. Personally, it took me a bit to get through the document; at first I just tried reading, but I got much more out of it by writing some of the lemmas/theorems down and practicing a bit myself. I think the graphs under "From Games to Graphs" and "The Sprague-Grundy Function" sections were particularly helpful for this problem.
Here's how I started thinking about it: a set of pins is a game position. Each game position is either terminal or has followers, which are other game positions that can be moved to. Each game position can be assigned a Sprague-Grundy (SG) based on the SG values of its followers. Now try creating a graph of game positions:
The only terminal position is no pins left, which we can write as X or XX or however many X based on the number of pins you start with. This position has SG(X) = 0 because it's terminal.
The game position I can have one pin knocked down, which would make it X. So X is a follower of I, and SG(I) = mex{SG(X)} = mex{0} = 1
The game position II can have either one pin knocked down, making it XI == IX == I, or two, making it XX == X. So it has these two followers, and SG(II) = mex{SG(I), SG(X)} = mex{0, 1} = 2.
Now let's look at III, since this is where we get to start using some of the other information from the document. The followers are XII (SG of 2), XXI (SG of 1), and IXI. For this last one, we could see that it only has one follower and get the SG like that, OR we could use the Sprague-Grundy theorem. This says "the SG function for a sum of games on a graph is just the Nim sum of the SG functions of its components". For IXI, it has two games of I, each with SG of 1. When we take the nim sum (xor the binary representations), we get 0. So in conclusion, SG(III) = mex{2, 1, 0} = 3.
And you can keep going bottom to top to get other SGs by taking 1 or 2 II away at a time and calculating nim sums.
I have an animation shown on LEDs. When the button is pressed, the animation has to stop and then continue after the button is pressed again.
There is a method that processes working with the button:
void checkButton(){
GPIO_PinState state;
state = HAL_GPIO_ReadPin(GPIOC, GPIO_PIN_15);
if (state == GPIO_PIN_RESET) {
while(1){
state = HAL_GPIO_ReadPin(GPIOC, GPIO_PIN_15);
if (state == GPIO_PIN_SET){
break;
}
}
//while (state == GPIO_PIN_RESET) {
//state = HAL_GPIO_ReadPin(GPIOC, GPIO_PIN_15);
//}
}
}
GPIO_PIN_SET is the default button position. GPIO_PIN_RESET is the condition when the button is pressed. The commented section is what I tried instead of the while(1){...} loop. The checkButton() method is called in the main loop from time to time to be run. The program runs on STM32 with an extension module (here the type of an extension module does not matter).
The fact is that this method stops animation just for a moment and does not work as I would like it to. Could you correct anything about this program to make it work properly?
Could you correct anything about this program to make it work
properly?
My guess is that you are trying to add a 'human interaction' aspect to your design. Your current approach relies on a single (button position) sample randomly timed by a) your application and b) a human finger. This timing is simply not reliable, but the correction is possibly not too difficult.
Note 1: A 'simple' mechanical button will 'bounce' during it's activation or release (yes, either way). This means that the value which the software 'sees' (in a few microseconds) is unpredictable for several (tbd) milliseconds(?) near the button push or release.
Note 2: Another way to look at this issue, is that your state value exists two places: in the physical button AND in the variable "GPIO_PinState state;". IMHO, a state value can only reside in one location. Two locations is always a mistake.
The solution, then (if you believe) is to decide to keep one state 'record', and eliminate the other. IMHO, I think you want to keep the button, which seems to be your human input. To be clear, you want to eliminate the variable "GPIO_PinState state;"
This line:
state = HAL_GPIO_ReadPin(GPIOC, GPIO_PIN_15);
samples the switch state one time.
HOWEVER, you already know that this design can not rely on the one read being correct. After all, your user might have just pressed or released the button, and it is simply bouncing at the time of the sample.
Before we get to accumulating samples, you should be aware that the bouncing can last much more than a few microseconds. I've seen some switches bounce up to 10 milliseconds or more. If test equipment is available, I would hook it up and take a look at the characteristics of your button. If not, well, you can try the adjusting the controls of the following sample accumulator.
So, how do we 'accumulate' enough samples to feel confident we can know the state of the switch?
Consider multiple samples, spaced-in-time by short delays (2 controls?). I think you can simply accumulate them. The first count to reach tbr - 5 (or 10 or 100?) samples wins. So spin sample, delay, and increment one of two counters:
stateCount [2] = {0,0}; // state is either set or reset, init both to 0
// vvv-------max samples
for (int i=0; i<100; ++i) // worst case how long does your switch bounce
{
int sample = HAL_GPIO_ReadPin(GPIOC, GPIO_PIN_15); // capture 1 sample
stateCount[sample] += 1; // increment based on sample
// if 'enough' samples are the same, kick out early
// v ---- how long does your switch bounce
if (stateCount[sample] > 5) break; // 5 or 10 or 100 ms
// to-be-determined --------vvv --- how long does switch bounce
std::this_thread::sleep_for(1ms); // 1, 3, 5 or 11 ms between samples
// C++ provides, but use what is available for your system
// and balanced with the needs of your app
}
FYI - The above scheme has 3 adjustments to handle different switch-bounce durations ... You have some experimenting to do. I would start with max samples at 20. I have no recommendation for sleep_for ... you provided no other info about your system.
Good luck.
It has been a long time, but I think I remember the push-buttons on a telecom infrastructure equipment bounced 5 to 15 ms.
I am trying to parallelise a biological model in C++ with boost::mpi. It is my first attempt, and I am entirely new to the boost library (I have started from the Boost C++ Libraries book by Schaling). The model consists of grid cells and cohorts of individuals living within each grid cell. The classes are nested, such that a vector of Cohorts* belongs to a GridCell. The model runs for 1000 years, and at each time step, there is dispersal such that the cohorts of individuals move randomly between grid cells. I want to parallelise the content of the for loop, but not the loop itself as each time step depends on the state of the previous time.
I use world.send() and world.recv() to send the necessary information from one rank to another. Because sometimes there is nothing to send between ranks I use with mpi::status and world.iprobe() to make sure the code does not hang waiting for a message that was never sent (I followed this tutorial)
The first part of my code seems to work fine but I am having troubles with making sure all the sent messages have been received before moving on to the next step in the for loop. In fact, I noticed that some ranks move on to the following time step before the other ranks have had the time to send their messaages (or at least that what it looks like from the output)
I am not posting the code because it consists of several classes and it’s quite long. If interested the code is on github. I write here roughly the pseudocode. I hope this will be enough to understand the problem.
int main()
{
// initialise the GridCells and Cohorts living in them
//depending on the number of cores requested split the
//grid cells that are processed by each core evenly, and
//store the relevant grid cells in a vector of GridCell*
// start to loop through each time step
for (int k = 0; k < (burnIn+simTime); k++)
{
// calculate the survival and reproduction probabilities
// for each Cohort and the dispersal probability
// the dispersing Cohorts are sorted based on the rank of
// the destination and stored in multiple vector<Cohort*>
// I send the vector<Cohort*> with
world.send(…)
// the receiving rank gets the vector of Cohorts with:
mpi::status statuses[world.size()];
for(int st = 0; st < world.size(); st++)
{
....
if( world.iprobe(st, tagrec) )
statuses[st] = world.recv(st, tagrec, toreceive[st]);
//world.iprobe ensures that the code doesn't hang when there
// are no dispersers
}
// do some extra calculations here
//wait that all processes are received, and then the time step ends.
//This is the bit where I am stuck.
//I've seen examples with wait_all for the non-blocking isend/irecv,
// but I don't think it is applicable in my case.
//The problem is that I noticed that some ranks proceed to the next
//time step before all the other ranks have sent their messages.
}
}
I compile with
mpic++ -I/$HOME/boost_1_61_0/boost/mpi -std=c++11 -Llibdir \-lboost_mpi -lboost_serialization -lboost_locale -o out
and execute with mpirun -np 5 out, but I would like to be able to execute with a higher number of cores on an HPC cluster later on (the model will be run at the global scale, and the number of cells might depend on the grid cell size chosen by the user).
The compilers installed are g++ (Ubuntu 7.3.0-27ubuntu1~18.04) 7.3.0, Open MPI: 2.1.1
The fact that you have nothing to send is an important piece of information in your scenario. You can not deduce that fact from only the absence of a message. The absence of a message only means nothing was sent yet.
Simply sending a zero-sized vector and skipping the probing is the easiest way out.
Otherwise you would probably have to change your approach radically or implement a very complex speculative execution / rollback mechanism.
Also note that the linked tutorial uses probe in a very different fashion.
I'm studying for a uni project and one of the requirements is to include multithreading. I decided to make a prime number finder and - while it works - it's rather slow. My best guess is that this has to do with the amount of threads I'm creating and destroying.
My approach was to take the range of primes that are below N, and distribute these evenly across M threads (where M = number of cores (in my case 8)), however these threads are being created and destroyed every time N increases.
Pseudocode looks like this:
for each core
# new thread
for i in (range / numberOfCores) * currentCore
if !possiblePrimeIsntActuallyPrime
if possiblePrime % i == 0
possiblePrimeIsntActuallyPrime = true
return
else
return
Which does work, but 8 threads being created for every possible prime seems to be slowing the system down.
Any suggestions on how to optimise this further?
Use thread pooling.
Create 8 threads and store them in an array. Feed it new data each time one ends and start it again. This will prevent them from having to be created and destroyed each time.
Also, when calculating your range of numbers to check, only check up to ceil(sqrt(N)) as anything after that is guaranteed to either not go into it or the other corresponding factor has already been checked. i.e. ceil(sqrt(24)) is 5.
Once you check 5 you don't need to check anything else because 6 goes into 24 4 times and 4 has been checked, 8 goes into it 3 times and 3 has been checked, etc.
I have been working on one of those snake games and I have a switch statement that says if a key is pressed to move the snake in a direction by incrementing/decrementing, but it will only do that if I hold it. I am looking for a way to have the snakes location keep incrementing without the user holding that key. I put one case below
if(_kbhit()) {
switch(_getch()) {
case 'a' :
dir = LEFT;
x--;
I am looking for a way to have ... keep incrementing without the user
holding that key."
IMHO, you should consider the "select()" function (if it is available in your OS)
Long ago I used "select()" in vxWorks. I see from a man page this function is also available to Ubuntu Linux. (maybe it is available to your system?)
With the select statement, a thread or program can "monitor multiple file descriptors, waiting until one or more of the file descriptors become "ready" for some class of I/O operation (e.g. input possible). A file descriptor is considered ready if it is possible to perform a corresponding operation (e.g., read() without blocking, or a sufficiently small write())." (from man page)
In practice, the system I worked on had a user interface thread (one of several) issue reads and monitor the input fd (via select) for user input. Our select used a 1/2 second time out (you choose rate). Thus, every half second, if no user input occurred at that port (i.e. device), the time out would release the program to check the bits in the fd_sets.
Nothing prevents the code from doing additional activites in a timeout.
I would guess you will only need to work on readfds, and can leave the other fds empty.
In other words, with select, your code 'monitors' for some user input with a time out, and takes action on either the user input (key stroke) or because of the time out.
This sounds like what you are looking for - action without pressing a key.
Your current design sounds like it moves the snake on press event.
I think you're looking to modify the design such that press events update some current-direction flag, while some background timer thread moves the snake at some regular frame rate.
Your code only moves the snake on key press. You need to implement some kind of game loop which moves the snake at a regular interval based on a direction variable. You can then refactor your key press code to simply update the direction.
Pseudo code:
while: # loop forever
# below could be your switch statement
if direction == 0: # north
y--
if direction == 1: # east
x++
if direction == 2: # south
y++
if direction == 4: # west
x--
if _kbhit():
if _getch() == 'a':
direction == 4 # west
# etc...