Noob C help - looping inside a switch/case? - c

new to programming and I've been crunching away on this assignment for weeks now.
I have a very basic understanding of C and while I'm nearly finished I think I might have made a mistake choosing a switch case for this menu system.
So the main menu gives 6 options, this option has to have a check to make sure Z1 is greater than Z2
case 5:
printf("\nEnter value Z1:\n");
scanf("%f", &Z1);
printf("\nEnter value Z2:\n");
scanf("%f", &Z2);
if (Z1 < Z2){
printf("\nZ2 must be less than Z1...\n");
}
I just want to return the program back to the beginning of the case unless Z1 is greater than Z2. After reading the other question it seems you can't loop the switch case back unless the values satisfy the if statement. I have no idea what to write as part of the if statement.
Any suggestions would be greatly appreciated, I'm tearing my hair out thinking I'm going to have to rewrite most of it.
Apologies if this is something really straight forward, I've looked for a good hour trying to find something and maybe I have seen the answer but just didn't understand it.
Thanks for your time!

a do {...} while (condition); loop would seem very adapted ; it's very close to the while loop, exept that the condition is checked only after the code into brackets has been executed ; which implies your code into brackets has to be run at least once.
Here, it would be :
do {
//get z1 and z2
} while (Z1 < Z2);

Related

(C) Minesweeper calculating function goes wrong

Hope your day going well. Thank you for visiting my post.
So I was trying to build minesweeper game, but got stuck at some problem.
Long story short, I have 2D array size 8*8. There are randomally 8 mines around the array.
I want to check: if at [row][col] there is no mine, whats the INT value it should hold.
I wrote a function that checks all the 8 options around the specific [row][col] I have.
For example:
if (game[row-1][col-1] == '*')
counter++
if (game[row][col+1] == '*')
counter++
and so on... 8 times. At the end, the function returns the counter value.
So I got stuck when I was trying to check, for example, row = 0 col = 7.
Because, row-1 gets me back to row[7], and col+1 gets me to col[0], and I don't want any of this to happen.
I've been sitting about 5 hours today, thinking of a way to fix this. But I couldn't think of any possibility rather than (approximately) 23 if's in one function.
Can anyone PLEASE hint me which steps I should take?
Thanks in advance!! :)

Algebraic_​loop_Solut​ion_SIMULI​NK

I want to implement the following pseudo-code in SIMULINK:
q^0 = q_init, i = 0
IF q^i ! = q_final
q^(i+1) = q^i + alpha * F(q^i)
i = i + 1
ELSE return <q^0,q^1 ... q^i>
The main problem is, that F(q^i) is a function of the current q and is calculated in every iteration. When trying to impement this in SIMULINK, I run into an algebraic loop that cannot be solved.
What is the proper way of solving the problem (in SIMULINK) ?
Thank you !
Miklos
Understand what to partition inside of a Simulink simulation and what should be the output.
You'd usually cache the outputs q^0 to q^i as outputs from the model, rather than trying to get the whole model to output that.
That means the Simulink model would just be dealing with calculating q^(i+1) from q^(i) (which you store with a unit-delay block).
Regarding the if condition: It is best not to run a simulation forever unless you know it will definitely tend towards q_final. If you're not using integers that might get very hard for the == to exactly evaluate. In that case you should use (abs(q^i - final) > threshold) then, and check it will end.
Ending a simulation exactly at that point might be possible with a breakpoint, but a simpler option would to allowing the simulation to run past it and then trim your output (q^0 to q^i, then some more values) in Matlab.

Is there a way to go back after you go forward with an 'IF' statement?

So I'm making this text based game for my 'C' Programming class.
I want to continue it even after I'm done with the class so it's not just a homework assignment I want to actually keep it for later use.
My question is in this part of the code is there a way to send the user back to the previous question asked when using an 'IF' statement so they can make multiple choices before ultimately going the direction of the story?
if (door2 == 1)
{
// what happens when you touch the orb.
printf("The orb transports you to an unknown location.\n");
printf("You look around to get the lay of your area,\n");
printf("off in the distance you see a church like building.");
door2 = door2 - 1;
printf("\n");
printf("Do you go to the building? ");
scanf_s("%d", &door1);
printf("\n");
if (door1 == 1)
{
// Going up to the church.
printf("You walk up to the building, it gives you a strange feeling\n");
printf("in the pit of your stomach. You look around and see two windows\n");
printf("low enough for you to see into along with the main door.\n");
printf("Do you go to the left window? right window? or try to open the front door?\n");
scanf_s("%d", &movement);
printf("\n");
if (movement = 1)
{
// left window.
printf("You creep up to the window and peak inside...\n");
printf("You see a large figure pacing back and forth in the room\n");
printf("what ever it is spots you and darts further into the church.");
movement = movement - 1;
// i subtract the L,S,R numbers to insure there is not an infinite loop.
}
else if (movement = 2)
{
// front door.
printf("You walk up to the front door, and try to open it.\n");
printf("The door does not budge, it must be locked.");
movement = movement - 2;
}
else if (movement = 3)
{
// right window.
printf("You creep up to the window and find an empty room.\n");
movement = movement - 3;
printf("The window is cracked open somewhat... Do you try to enter the\n");
printf("church through the window? ");
scanf_s("%d", &door2);
printf("\n");
}
Actually yes, if you would just put a loop around that, but i'd advise splitting your ifs in functions. Your code will look much better.
void main() {
enterTheCurch();
}
void enterTheCurch() {
printf("You've entered the Curch. There are 2 Doors. Do you want to go left or right?");
String direction;
scanf_s("%s", &direction);
if(direction == "left") {
goLeftCurchDoor();
}
else {
goRightCurchDoor();
}
}
goLeftCurchDoor() {
...
}
goRightCurchDoor() {
...
}
Try using this structure. Like this you also can give parameters to the function like bool alreadyVisited and change the prints depending on these parameters.
This is probably not the correct approach at all. A game generally is split into several components: a main loop (that runs infinitely), an update loop (that simulates the game world) and a process input function (which takes input from the user.)
The way your code is structured also leaves much to be desired. For one thing, your prompts to the user are inconsistent. Sometimes you seem to be asking a yes or no question, other times it seems you want a movement command with no indication to the user which is expected. This is a UX nightmare. Instead, you can treat each movement as an action. For example, going forward to a locked door means the user wants to try to open the door. Going forward with an open window means the user wants to travel through the window. With that in mind, it becomes clear that you only actually need to keep track of one variable.
Making a game is not an easy task and you cannot brute force your way into making one - it requires thoughtful planning ahead of time. Try drawing a dialogue tree on a piece of paper. You'll quickly see it spiral out of control as you run out of room on the paper - designing a game is a complex task. It's important to have a blueprint before you begin coding.
First, let's tackle what your game loop can look like:
#include <stdio.h>
#include <stdbool.h> // for true and false
typedef enum { NONE = 0, LEFT, RIGHT, UP, DOWN } movement_t;
int main()
{
movement_t movement = NONE;
movement_t last_movement = NONE;
while (true)
{
int movement_input = 0;
scanf("%d", &movement_input);
movement = (movement_t) movement_input;
// ...
last_movement = movement;
}
}
Now you want to know what kind of data structure should represent your game. Unfortunately this is a complex topic and I'm not a game developer, so I'll try to present a naive approach. The simplest way that takes less work is to have a static message for each room as you enter it. If something changes, then you could reflect that change once a variable has been updated.
void church()
{
printf("Generic church description.");
if (some_player_did_something)
{
printf("You now spot a shiny object on the floor.");
}
}
Keeping track of the player's last movement (which I have demonstrated above) is useful for determining where they came from.
if (last_movement == LEFT)
{
printf("You come in from the left and noticed something you haven't before...");
}
I would take the suggestions from the others and split your code into functions (as I'm sure your instructor has drilled into you by now.) A monolithic approach is not the way to go.
There is one: goto.
label:
if (someCondition) {
goto label;
}
This code will loop until someCondition becomes false.
goto is a inconditional jump, and allow you to jump excecution forward or backward to a label, provided you stay in the same scope.
Lots of people hates goto, and you should make sure not to use it if you have other better alternatives.
Story telling sounds like a nice use case for goto.
Loops or recursion are other options to produce this result, such as while do ... while for.
each location in the game needs an entry in a table,
along with certain environment details such as:
which direction is the player facing
visible items at each location
current game state,
current inventory,
'next' table entry to use, etc.
This table grows huge very quickly and can have many parameters per line in the table. It is the actual game. All the rest is just user manipulation of the table, current conditions, etc.
Every possible user input has a unique function to handle that input (there are not that many possible inputs).
Each of these functions gets a parameter that is a pointer to an entry in the location table, that lets that function process the user input.
The main loop of the program handles getting input from the user and dispatching the appropriate inputFunction handler.
There will be sub functions to handle inventory changes, display inventory, enable/disable certain types of actions, etc

How to search three or more arrays row by row for an optimum value in matlab

I have a few variables and here they are, three variables "R1, R2 and R3" each have a size of [40 x 1].
I have a fourth variable U of the same dimension. For every U(i) I need to search for an optimum value within R1(i), R2(i) and R3(i) which would return a single value solution. I intend to plot the optimum value against U9i).I have been trying to wrap my head around the knnsearch function but no luck.
Any one out there who could please help??
Thanks
Well when I can't wrap my head around something, I don't come here first.
A lot of people forget this one because we are online, but read a book on the topic. Have your code open so when you see something in the book, test it out.
Draw out any type of diagram. I call these "Napkin Diagrams", because I write it on anything, even a napkin.
I play with code until my keyboard has no letters left on it, then I keep plugging away until the keys fall off
Explore the language API's
Check for public repositories that you can play with
Google, is okay for a quick reference, but google will not teach you anything other than how to google
I talk my code over with myself all the time, people think I'm nuts, but so do I . . It actually works sometimes.
Then if I still can't get it, I come here with a list of things that I have tried, sample code that has not worked, etc.
I used to hate when people told me this, but that was the best thing anyone could have done for me so I tend to do the same now" Thinking about coding is a big part, but u have to get done wht u can. Then we all know what level u are at. Plus it being the end of semester a lot of these types of questions are homework...
Thinking is good, now turn those thoughts into a conceptual design . It's okay to be wrong in this stage, its all just conceptual
If I understood correctly, this might be what you need:
RR = [R1(:) R2(:) R3(:)];
d = bsxfun(#minus,RR, U(:));
[m mi] = min(abs(d),[],2);
answer = RR(:,mi);
first - put the three vectors into a single matrix:
RR = [R1(:) R2(:) R3(:)];
next, take the difference with U: bsxfun is ideal for this kind of thing
d = bsxfun(#minus,RR, U(:));
Now find the minimum absolute difference for each row:
[m mi] = min(abs(d),[],2);
The corresponding indices should allow you to find the "best fit"
answer = RR(:,mi);
I had to do some mind reading to get to this 'answer', so feel free to correct my misunderstanding of your problem!
update if you just need the highest of the three values, then
val = max([R1(:) R2(:) R3(:)]');
plot(U, val);
should be all you need...

Understanding this C function

I'm trying to understand how this function works, I have studied several algorithms to generate sudoku puzzles and found out this one.
Tested the function and it does generates a valid 9x9 Latin Square (Sudoku) Grid.
My problem is that I can't understand how the function works, i do know the struct is formed by to ints, p and b , p will hold the number for the cell in the table, But after that I don't understand why it creates more arrays (tab 1 and tab2) and how it checks for a latin square =/ etc , summarizing , I'm completely lost.
I'm not asking for a line by line explanation, the general concept behind this function.
would help me a lot !
Thanks again <3
int sudoku(struct sudoku tabla[9][9],int x,int y)
{
int tab[9] = {1,1,1,1,1,1,1,1,1};
int i,j;
for(i=0;i<y;++i)
{
tab[tabla[x][i].p-1]=0;
for(i=0;i<x;++i)
{
tab[tabla[i][y].p-1]=0;
}
for(i=(3*(x/3));i<(3*(x/3)+3);++i)
{
for(j=(3*(y/3));j<y;++j)
{
tab[tabla[i][j].p-1]=0;
}
}
int n=0;
for(i=0;i<9;++i)
{
n=n+tab[i];
}
int *tab2;
tab2=(int*)malloc(sizeof(int)*n);
j=0;
for(i=0;i<9;++i)
{ if(tab[i]==1)
{
tab2[j]=i+1;
j++;
}
}
int ny, nx;
if(x==8)
{
ny=y+1;
nx=0;
}
else
{
ny=y;
nx=x+1;
}
while(n>0)
{
int los=rand()%n;
tabla[x][y].p=tab2[los];
tab2[los]=tab2[n-1];
n--;
if(x==8 && y==8)
{
return 1;
}
if (sudoku(tabla,nx,ny)==1)
{
return 1;
}
}
return 0;
}
EDIT
Great, I now understand the structure, thanks lijie's answer. What I still don't understand is the part that tries out the values in random order). I don't understand how it checks if the random value placement is valid without calling the part of the code that checks if the movement is legal, also, after placing the random numbers is it necessary to check if the grid is valid again? –
Basically, the an invocation of the function fills in the positions at and "after" (x, y) in the table tabla, and the function assumes that the positions "prior" to (x, y) are filled, and returns whether a legal "filling in" of the values is possible.
The board is linearized via increasing x, then y.
The first part of the function finds out the values that are legal at (x, y), and the second part tries out the values in a random order, and attempts fills out the rest of the board via a recursive call.
There isn't actually a point in having tab2 because tab can be reused for that purpose, and the function leaks memory (since it is never freed, but aside from these, it works).
Does this make sense to you?
EDIT
The only tricky area in the part that checks for legal number is the third loop (checking the 3x3 box). The condition for j is j < y because those values where j == y are already checked by the second loop.
EDIT2
I nitpick, but the part that counts n and fills tab2 with the legal values should really be
int n = 0;
for (i = 0; i < 9; ++i) if (tab[i]) tab[n++] = i+1;
hence omitting the need for tab2 (the later code can just use tab and n instead of tab2). The memory leak is thusly eliminated.
EDIT
Note that the randomness is only applied to valid values (the order of trying the values is randomized, not the values themselves).
The code follows a standard exhaustive search pattern: try each possible candidate value, immediately returning if the search succeeds, and backtracking with failure if all the candidate values fail.
Try to solve sudoku yourself, and you'll see that there is inherent recursion in finding a solution to it. So, you have function that calls itself until whole board is solved.
As for code, it can be significantly simplified, but it will be for the best if you try to write one yourself.
EDIT:
Here is one from java, maybe it will be similar to what you are trying to do.
A quick description of the principles - ignoring the example you posted. Hopefully with the idea, you can tie it to the example yourself.
The basic approach is something that was the basis of a lot of "Artificial Intelligence", at least as it was seen until about the end of the 80s. The most general solution to many puzzles is basically to try all possible solutions.
So, first you try all possible solutions with a 1 in the top-left corner, then all possible solutions with a 2 in the top-left corner and so on. You recurse to try the options for the second position, third position and so on. This is called exhaustive search - or "brute force".
Trouble is it takes pretty much forever - but you can short-cut a lot of pointless searching.
For example, having placed a 1 in the top-left corner, you recurse. You place a 1 in the next position and recurse again - but now you detect that you've violated two rules (two ones in a row, two ones in a 3x3 block) even without filling in the rest of the board. So you "backtrack" - ie exit the recursion to the previous level and advance to putting a 2 in that second position.
This avoids a lot of searching, and makes things practical. There are further optimisations, as well, if you keep track of the digits still unused in each row, column and block - think about the intersection of those sets.
What I described is actually a solution algorithm (if you allow for some cells already being filled in). Generating a random solved sudoku is the same thing but, for each digit position, you have to try the digits in random order. This also leaves the problem of deciding which cells to leave blank while ensuring the puzzle can still be solved and (much harder) designing puzzles with a level-of-difficulty setting. But in a way, the basic approach to those problems is already here - you can test whether a particular set of left-blank spaces is valid by running the solution algorithm and finding if (and how many) solutions you get, for example, so you can design a search for a valid set of cells left blank.
The level-of-difficulty thing is difficult because it depends on a human perception of difficulty. Hmmm - can I fit "difficult" in there again somewhere...
One approach - design a more sophisticated search algorithm which uses typical human rules-of-thumb in preference to recursive searching, and which judges difficulty as the deepest level of recursion needed. Some rules of thumb might also be judged more advanced than others, so that using them more counts towards difficulty. Obviously difficulty is subjective, so there's no one right answer to how precisely the scoring should be done.
That gives you a measure of difficulty for a particular puzzle. Designing a puzzle directly for a level of difficulty will be hard - but when trying different selections of cells to leave blank, you can try multiple options, keep track of all the difficulty scores, and at the end select the one that was nearest to your target difficulty level.

Resources