void makeMove(int player, int move) {
int i, stones, nextPit;
// Get the number of stones in the selected pit
stones = board[player * 6 + move];
board[player * 6 + move] = 0; // Clear the pit
// Distribute the stones
nextPit = player * 6 + move + 1; // Start at the next pit
for (i = 0; i < stones; i++) {
// Skip the opponent's mancala
if (nextPit == (player ^ 1) * 6 + 6) {
nextPit++;
}
// Place a stone in the pit
board[nextPit]++;
nextPit++; // Move to the next pit
// Wrap around to to the beginning of the board
if (nextPit == BOARD_SIZE) {
nextPit = 0;
}
}
so this function takes all the stones from the chosen pit and puts the stones one by one on to the next pits
example : 4 4 4 4 4 if you choose the first pit it goes like 0 5 5 5 5 but i want it to be 1 5 5 5 4
i want this function to take all the stones from the chosen pit and put one back to the chosen pit and then start to put next pits
i am a 2 month computer engineering student im new to this i didnt try much if you can explain this code to me it would mean the world
Related
How do I make my code have an output like this:
Enter your number: 4
1 1 1 2
2 2 2 3
3 3 3 4
4 4 4 5
I can't seem to figure out how to make it so the last digit prints the next value iteration.
#include <stdio.h>
int main(){
int num;
int i = 1;
printf("Enter your number: ");
scanf("%d", &num);
for(i = 1; i<=num; i++){
for(int j = 0; j<num; ++j)
{
printf("%d ",i);
}
printf("\n");
}
Doing this using nested loops are simple and doesn't require any kind of special calculations, if-statements or other more or less fancy stuff. Just keep it simple.
Your task is:
for each row:
print "rowindex+1 and a space" n-1 times
print "rowindex+2 and a newline" 1 time
"for each row" is one simple loop.
"n-1 times" is another (nested) simple loop.
So keep it simple... just two ordinary for-loops like:
#include <stdio.h>
int main()
{
int n = 4;
for (int i = 0; i < n; i++) // for each row
{
for (int j = 0; j < n-1; j++) // n-1 times
{
printf("%d ", i + 1);
}
printf("%d\n", i + 2); // 1 time
}
return 0;
}
Here is something kind of from out in the left field, and off topic, leaving behind not only the requirements of the homework, but the C language. However, we will find our way back.
We can solve this problem (sort of) using text processing at the Unix prompt:
We can treat the smallest square
12
23
as an initial seed kernel, which is fed through a little command pipeline to produce a square of the next size (up to a single digit limitation):
We define this function:
next()
{
sed -e 's/\(.\).$/\1&/' | awk '1; END { print $0 | "tr \"[1-9]\" \"[2-8]\"" }'
}
Then:
$ next
12
23
[Ctrl-D][Enter]
112
223
334
Now, copy the 3x3 square and paste it into next:
$ next
112
223
334
[Ctrl-D][Enter]
1112
2223
3334
4445
Now, several steps in one go, by piping through multiple instances of next:
$ next | next | next | next | next
12
23
[Ctrl-D][Enter]
1111112
2222223
3333334
4444445
5555556
6666667
7777778
The text processing rule is:
For each line of input, repeat the second-to-last character. E.g ABC becomes ABBC, or 1112 becomes 11112. This is easily done with sed.
Add a new line at the end which is a copy of the last line, with each digit replaced by its successor. E.g. if the last line is 3334, make it 4445. The tr utility helps here
To connect this to the homework problem: a C program could be written which works in a similar way, starting with an array which holds the 1 2 2 3 square, and grows it. The requirement for nested loops would be satisfied because there would be an outer loop iterating on the number of "next" operations, and then an inner loop performing the edits on the array: replicating the next-to-last column, and adding the new row at the bottom.
#include <stdio.h>
#include <stdlib.h>
#define DIM 25
int main(int argc, char **argv)
{
if (argc != 2) {
fputs("wrong usage\n", stderr);
return EXIT_FAILURE;
}
int n = atoi(argv[1]);
if (n <= 2 || n > DIM) {
fputs("invalid n\n", stderr);
return EXIT_FAILURE;
}
int array[DIM][DIM] = {
{ 1, 2 },
{ 2, 3 }
};
/* Grow square from size 2 to size n */
for (int s = 2; s < n; s++) {
for (int r = 0; r < s; r++) {
array[r][s] = array[r][s-1];
array[r][s-1] = array[r][s-2];
}
for (int c = 0; c <= s; c++) {
array[s][c] = array[s-1][c] + 1;
}
}
/* Dump it */
for (int r = 0; r < n; r++) {
for (int c = 0; c < n; c++)
printf("%3d ", array[r][c]);
putchar('\n');
}
return 0;
}
#include<stdio.h>
int main(){
int n;
printf("Enter the number: ");
scanf("%d",&n);
for(int i =1; i<=n; i++){
for(int j=1;j<=n;j++) {
if(j==n)
printf("%d\t",i+1);
else
printf("%d\t",i);
}
printf("\n");
}
return 0;}
Nested loops will drive you crazy, trying figure out their boundaries.
While I usually oppose adding more variables, in this case it seems justified to keep track of things simply.
#include <stdio.h>
int main() {
int n = 4, val = 1, cnt1 = 1, cnt2 = 0;
for( int i = 1; i < n*n+1; i++ ) { // notice the 'square' calculation
printf( "%d ", val );
if( ++cnt1 == n ) // tired of this digit? start the next digit
cnt1 = 0, val++;
if( ++cnt2 == n ) // enough columns output? start the next line
cnt2 = 0, putchar( '\n' );
}
return 0;
}
1 1 1 2
2 2 2 3
3 3 3 4
4 4 4 5
A single example of desired output is hard to go by, especially when the code doesn't help... Anyway, here's the output when 'n' = 5.
1 1 1 1 2
2 2 2 2 3
3 3 3 3 4
4 4 4 4 5
5 5 5 5 6
All of these kinds of assignments are to try to get you to recognize a pattern.
The pattern you are given
1 1 1 2
2 2 2 3
3 3 3 4
4 4 4 5
is very close to
1 1 1 1
2 2 2 2
3 3 3 3
4 4 4 4
which is an easy nested loop. Write a solution to the easier pattern. Once you have that you can then you can fix it.
Hint: Notice that the only thing that changes is the last item of the inner loop.
Edit
This totally breaks the spirit of the assignment, and if you, dear student, ever try to submit something like this your professor will... probably not care, but also know full well that you didn’t do it. If I were your professor you’d lose marks, even if I knew you weren’t cheating and had written something this awesome yourself.
Single loop. Stuff added to pretty print numbers wider than one digit (except the very last). Maths, yo.
#include <stdio.h>
#include <math.h>
void print_off_by_one_square( int n )
{
int width = (int)log10( n ) + 1;
for (int k = 0; k++ < n*n ;)
printf( "%*d%c", width, (k+n)/n, (k%n) ? ' ' : '\n' );
}
int main(void)
{
int n;
printf( "n? " );
fflush( stdout );
if ((scanf( "%d", &n ) != 1) || (n < 0))
fprintf( stderr, "%s\n", "Not cool, man, not cool at all." );
else
print_off_by_one_square( n );
return 0;
}
The way it works is pretty simple, actually, but I’ll leave it as an exercise for the reader to figure out on his or her own.
Here is a different concept. Some of the answers are based on the idea that we first think about
1 1 1 1
2 2 2 2
3 3 3 3
4 4 4 4
and then tweak the logic for the item in the last line.
But we can regard it like this also:
We have a tape which goes like this:
1 1 1 1 2 2 2 2 3 3 3 3 4 4 4 4
and we are blindly cutting the tape into four-element pieces to form a 4x4 square. Suppose someone deletes the first item from the tape, and then adds 5:
1 1 1 2 2 2 2 3 3 3 3 4 4 4 4 5
Now, if we cut that tape blindly by the same process, we will get the required output:
1 1 1 2
2 2 2 3
3 3 3 4
4 4 4 5
Suppose we have a linear index through the tape, a position p starting at 0.
In the unshifted tape, item p is calculated using p / 4 + 1, right?
In the shifted tape, this is just (p + 1) / 4 + 1. Of course we substitute the square size for 4.
Thus:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv)
{
if (argc != 2) {
fputs("wrong usage\n", stderr);
return EXIT_FAILURE;
}
int n = atoi(argv[1]);
int m = n * n;
if (n <= 0) {
fputs("invalid n\n", stderr);
return EXIT_FAILURE;
}
for (int p = 0; p < m; p++) {
printf("%3d ", (p + 1) / n + 1);
if (p % n == n - 1)
putchar('\n');
}
return 0;
}
$ ./square 2
1 2
2 3
$ ./square 3
1 1 2
2 2 3
3 3 4
$ ./square 4
1 1 1 2
2 2 2 3
3 3 3 4
4 4 4 5
I have an exercise I need to submit. The user should enter 2 numbers, one of height and one of width, and the output should be a rectangle that the outer numbers are low and the inner ones are high.
So I wrote it but it does not work in some numbers, for example 9 and 3, but in most things it works.
I made 2 variables that are equal to the numbers entered by the user, this data goes down, the other 2 variables are just indicators, of the loops, they have no meaning
If anyone has a different direction how to do it, I would love to hear, just in loops ..
For example:
1 1 1 1 1 1 1 1 1
1 2 2 2 2 2 2 2 1
1 2 3 3 3 3 3 2 1
1 2 3 3 3 3 3 2 1
1 2 2 2 2 2 2 2 1
1 1 1 1 1 1 1 1 1
Thanks
#include <stdio.h>
int main() {
int row, col, u, d;
scanf("%d", &row);
scanf("%d", &col);
int row_1, col_1;
for (u = 1, row_1 = row; u <= row; u++, row_1--) {
for (d = 1, col_1 = col; d <= col; d++, col_1--) {
if (col_1 < u && row_1 > col_1)
printf("%d", col_1);
else if (u > d && row_1 >= d)
printf("%d", d);
else if(row_1 > u)
printf("%d", u);
else
printf("%d", row_1);
}
printf("\n");
}
return 0;
}
I would start by learning to describe the problem. For example:
the user enters the number of rows and columns to print (presumably 1–9 each)
for each position, print the distance to the nearest edge of the rectangle, starting from 1
The above description would quite easily lead to a solution like:
for (int row = 1; row <= num_rows; ++row) {
int y_distance = distance_to_edge(row, num_rows);
for (int col = 1; col <= num_cols; ++col) {
int x_distance = distance_to_edge(col, num_cols);
printf("%d", x_distance < y_distance ? x_distance : y_distance);
}
putchar('\n');
}
(Implementation of distance_to_edge left as exercise.)
Of course this is not the only solution; you can also take advantage of the fact that you know how the position changes (as you have attempted in your solution), but such optimisation may make it harder to get right. One easy option there is to break each loop down to two halves (the distance increases in the first half and decreases in the second)…
I want my GRID of 9x9 to have different values in range of 1-5
Its generating values but i am getting same values together three times
For Example
3 3 5 5 3 4 5 3 2
5 1 1 1 1 5 5 3 5
5 1 2 2 5 4 4 2 3
1 3 1 4 4 3 2 1 2
5 2 1 5 2 1 4 2 5
2 5 3 1 3 5 4 4 2
1 5 5 4 3 2 2 1 3
3 1 2 5 1 2 1 1 2
3 2 4 5 3 3 3 4 2
Values are repeating three times together
My Code :
int GridArr[9][9] = { 0 };
srand(time(0));
for (int i = 0; i < 9; i++)
{
for (int j = 0; j < 9; j++)
{
GridArr[i][j] = 1 + rand() % ((5 + 1) - 1);
if (GridArr[i][j] == GridArr[i+2][j] || GridArr[i][j] == GridArr[i][j+2])
{
srand(time(0));
GridArr[i][j] = 1 + rand() % ((5 + 1) - 1);
}
cout << GridArr[i][j] << " ";
}
cout << endl;
}
First off, repeating values are perfectly normal in a random sampling. There's a lot of academic research on the true nature of randomness, and what humans consider to be random is not very random at all. If you're interested, read up on stochasticity.
In any case, for your particular case, I understand you do not want >2 repeats either vertically or horizontally, right?
First off, you'll need to check the 2 previous values both horizontally and vertically. In your code, you seem to be looking forwards (i+2 and j+2) instead of backwards, in other words you're comparing with values that haven't been set yet. Furthermore, you're only checking the value two squares ahead, not the values of both squares ahead.
It looks like you're coding in c++, right? I haven't coded in c++ for a very long time, so this might not be the most efficient way of doing things, but I added a check in your code for "forbidden numbers" (either 2 horizontally or vertically previously) and added those values to a map. Then I passed that map to the number generator which picked from an array of values including all numbers except those in the map. Hope that makes sense!
#include <iostream>
#include <map>
using namespace std;
int getRandomNumber(map<int, bool> forbiddenNumbers);
int main()
{
int GridArr[9][9] = { 0 };
srand(time(0));
for (int i = 0; i < 9; i++)
{
for (int j = 0; j < 9; j++)
{
// this map will keep track of which numbers we don't want for this grid position
map<int, bool> forbiddenNumbers;
// check horizontal
if (i > 1 && GridArr[i-2][j] == GridArr[i-1][j]) {
forbiddenNumbers[GridArr[i-2][j]] = true;
}
// check vertical
if (j > 1 && GridArr[i][j-2] == GridArr[i][j-1])
{
forbiddenNumbers[GridArr[i][j-2]] = true;
}
// pass map of forbidden numbers to number generator
GridArr[i][j] = getRandomNumber(forbiddenNumbers);
cout << GridArr[i][j] << " ";
}
cout << endl;
}
}
int getRandomNumber(map<int, bool> forbiddenNumbers) {
int allowedValues[5 - forbiddenNumbers.size()];
int pos = 0;
for (int i = 1; i < 6; i++) {
if (forbiddenNumbers.count(i) > 0) {
// if this number is forbidden, don't add it to the allowed values array
continue;
}
allowedValues[pos] = i;
pos++;
}
// return a value from the allowed values
return allowedValues[rand() % pos];
}
I am having trouble trying to implement semaphores with pthreads. The scenario that I am trying to program are rats in a maze. Where rats are threads and the maze consists of rooms connected to each other. The rats have to traverse through each room with each room having a different capacity and wait time before a rat can move on. I was able to implement it with a while loop and let the threads sit and spin while waiting for a spot to free up but I need to achieve the objective with semaphores. Here's what I have:
sem_t psem, csem;
void EnterRoom(int iRat, int iRoom) {
time_t currentTime;
currentTime = time(NULL);
RoomVB[iRoom][iRat].tEntry = currentTime - startTime;
RoomVB[iRoom][iRat].iRat = iRat;
VisitorCount[iRoom]++;
sleep(roomArray[iRoom].delay);
}
void LeaveRoom(int iRat, int iRoom) {
time_t currentTime;
currentTime = time(NULL);
VisitorCount[iRoom]--;
RoomVB[iRoom][iRat].tDep = currentTime - startTime;
}
void *rat(void *ratID) {
if (sem_init(&csem, 0, 0) < 0) {
perror("sem_init");
exit(1);
}
int id;
id = (int)ratID;
int i;
for (i = 0; i < numOfRooms; i++) {
/*while (VisitorCount[i] >= roomArray[i].capacity) {
}*/
if (sem_init(&psem, 0, roomArray[i].capacity) < 0) {
perror("sem_init");
exit(1);
}
sem_wait(&psem);
EnterRoom(id, i);
sem_post(&csem);
sem_wait(&csem);
LeaveRoom(id, i);
sem_post(&psem);
}
return NULL;
}
As you can see I commented out the while loop. I had to incorporate additional information like the time it it takes for a rat to travel through rooms in a 2D array.
Error result:
Rat 0 completed maze in 5 seconds.
Rat 1 completed maze in 5 seconds.
Rat 2 completed maze in 5 seconds.
Room 0 [3 1]: 0 0 1; 1 0 1; 2 0 1;
Room 1 [2 2]: 0 1 3; 1 1 3; 2 1 3;
Room 2 [1 2]: 0 3 5; 1 3 5; 2 3 5;
Total traversal time: 15 seconds, compared to ideal time: 15 seconds.
Correct result (achieved with loop):
Rat 0 completed maze in 7 seconds.
Rat 1 completed maze in 5 seconds.
Rat 2 completed maze in 9 seconds.
Room 0 [3 1]: 0 0 1; 1 0 1; 2 0 1;
Room 1 [2 2]: 0 1 3; 1 1 3; 2 3 5;
Room 2 [1 2]: 0 5 7; 1 3 5; 2 7 9;
Total traversal time: 21 seconds, compared to ideal time: 15 seconds.
I assume I need two semaphores with the producer semaphore being initially set to n - which is the capacity of each room. Any ideas how I fix it so it works as it should?
You can't have each thread re-initialise the same two shared semaphores simultaneously. The semaphores all need to be initialised up-front, before your rats start running.
The easiest way to solve this will be to have one semaphore for each room, initialised to the capacity of that room (store the sempahore in the roomArray element for that room). Then, just have the rat wait on the semaphore when it enters the room, and post the semaphore when it exits the room.
I am with a doubt about the memory game that I need to create. I made a fixed matrix of the size [4][4].
The number of cards have to be increased according to the difficulty the user had choosen.
So here is an example of the logic:
In DIFFICULTY 1 -> There will only be 3 equal pairs into the matrix like:{1,1}{4,4}{5,5}, these numbers have to be randomized but in pairs, so after that I can complete the matrix.
DIFFICULTY 2 -> There will only be 3 equal pairs into the matrix - {1,1}{4,4}{5,5}{3,3} - and again it need to me random numbers in pairs, so after that I can complete the matrix.
DIFFICULTY 3 -> complete the matrix, of the size [4][4], with pair of numbers randomly.
Probably you should take a look at the
for(i=0;i<lim_linha;i++)
my code:
void preencher_mesa(int matriz[4][4], int dificuldade)
{
int i,j;
int cartas[7][1]; //cards
int cont =1; //count
int lim_col, lim_linha; //limit_colunm //limit_line
for(i=0; i<4; i++)
for(j=0;j<4;j++)
matriz[i][j] = 0;
if(dificuldade == 1) //difficulty == 1
{
lim_col = 3; //estabelecendo limites para que não ultrapaasse o valor da mesa
lim_linha = 2;
}
else if(dificuldade == 2)
{
lim_col = 4;
lim_linha = 2;
}
else if(dificuldade == 3)
{
lim_col = 4;
lim_linha = 4;
}
for(i=0;i<lim_linha;i++) //setando os numeros aleatórios para dentro das
{ // matrizes de acordo com o nivel de dificuldade
for(j=0; j<lim_col;j++)
{
if(dificuldade == 1)
{
int aux=0;
while(cont>=1 && cont <=8)
{
cartas[i][0] = cont;
cartas[i][1] = cartas[i][0];
cont++;
printf("[%d]\n",(rand()%1 +(cartas[i][0])));
printf("[%d]\n",(rand()%1 +(cartas[i][1])));
}
}
}
}
//Gerando numeros aleatórios em pares por isso [0] e [1]
//sorting numbers in pairs to stabilish the numbers of cards
//{1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8}
PS: the range of random number should be 1-8 and I cannot have two, or more, same pairs of numbers.
Consider DIFFICULTY LEVEL 1: You first desire to determine a random selection of three numbers from the set {1,2,3,4,5,6,7,8}, and then given a pair each of those three numbers desire to randomly place them in a 4x4 matric.
The number of ways in which 3 numbers an be chosen from 8 is known as 3 chosen from 8 and is evaluated as
8! / (3! * (8-3)!)
which reduces to
8 * 7 * 6 / (3 * 2 * 1) = 56
Therefore the pairs of digits for DIFFICULTY LEVEL 1 an be determined by enumerating these 56 possibilities and making a random selection from the integers from 1 to 56.
Now given 3 pairs of numbers, one wishes to randomly place them in a 4x4 matrix. There are:
16 * 15 / 2 = 120 ways to place the first pair;
14 * 13 / 2 = 91 ways to place the second pair;
12 * 11 / 2 = 66 ways to place the third pair; and
3 * 2 * 1 = 6 ways to select the order of the three pairs
so this means there are 120 * 91 * 66 / 6 = 120,120 ways to place the three pairs in an empty 4x4 matrix. Again, by determining an enumeration of these 120,120 possibilities and making a random selection from the integers from 1 to 120,120 one can complete the matrix determination.
Likewise for the other Difficulty Levels.