Language c slowing down loop [closed] - c

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I have for loop which makes falling effect in matrix. I am generating numbers in the first row of matrix and the fall.
#include <stdio.h>
#include <stdbool.h>
#include <Windows.h>
void hra(){
.....
do {
for(int i = V; i > 0; i--) {
for(int j = 0; j < S; j++) {
mat1[i][j] = mat1[i - 1][j];
}
}....}
}
But now its too quick. When i use Sleep() it will slow down everything (user input etc..)
Is there a way to slow down only this loop (and gradually make it quicker)?
//
I am sorry I should have mentioned that the user sees the falling numbers and have to interact with them (the numbers fall at the bottom of the matrix where they get stored or they get erased by user). So I want them to "fall" slowly so the user can see them and decide which ones he want or dont. And V is 10 and S 4.

The solution you are looking for is multi-threading. Have the main thread do the calculations, have another thread do the graphics and a third thread handle to user input.

usleep() takes a time in microseconds as parameter, you could put a variable as value and then decrement it. Per example if you want to slow down this for:
for(int i = V; i > 0; i--)
you could add:
usleep(x * i);
in it. (Where x is whatever you want.) Feel free to use any equation you want to choose the way it will slow down.

Related

Fibonacci sequence C problems [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I was solving the problem... But I don't know why it does when a number greater than 200 is entered, it becomes an infinite loop. I used the recursive function. And I also only can use this function. What should I do?
#include <stdio.h>
int f(int n){
if (n<=0) return 0;
else if(n==1 || n==2) return 1;
else {
return f(n-1)+f(n-2);
}
}
int main()
{
int n;
scanf("%d", &n);
printf("%d", f(n));
return 0;
}
… it becomes an infinite loop.
If you are judging whether the program is in an infinite loop by waiting for it to finish, you cannot distinguish between it being in a very long loop and it being in an infinite loop unless you wait forever, which I doubt you have done.
When you ask for f(200), the call to f evaluates f(199) and f(198). Then the first of those calls to f evaluates f(198) and f(197), and the second evaluates f(197) and f(196). When you follow this tree of calls, there are very roughly 1041 calls involved. So your program never terminates while you are waiting because evaluating that many calls would take eons.
(The number of calls for a given input n is going to be very similar to the Fibonacci sequence for n, and the ratios between numbers approaches (1+sqrt(5))/2, so the number of calls will be around (1+sqrt(5)/2)n times some constant depending on the initial terms.)

Display the progress of completion while the program is being executed [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I want to display the progress of my C program in percentages while it is running. The actual work in the program whose progress should be measured is confined in a loop. Here is what I tried:
int i;
int to = 100000000;
while (i++ < to) {
printf("\rPercent done: %d", (100 * i)/to);
}
Might be a dumb question, but how does one display a progress while
the program is running?
Not like this.
You have multiple issues:
Your i is uninitialized, so the program will print garbage. (Fix: -> int i = 0; instead)
Your "progress counter" will only count the progress while in the loop. As soon as Percent done: 100 will be printed, only the loop will be over.
You're printing 100 million lines to the console. Maybe think that through again.
With (i*100)/to you're hitting integer overflow about half way through, so use i / (to / 100) instead. Notice depending on the compiler the compiler could optimize that out by itself.
A little less obnoxious way would be:
#include <stdio.h>
int main (void) {
int i = 0;
int to = 100000000;
while (i++ < to) {
if (i % 1000000 == 0) {
printf("\rPercent done: %d", i / (to / 100));
}
dostuff();
}
printf("\rLoop finished");
return 0;
}
Note that this will only accurately reflect how far the program has come executing the loop. Any work before/after the loop will not be measured by this.
This only prints a console message for every full percent. Still obnoxious that you're getting 100 console messages, but nowhere near as bad as 100.000.000 (!) calls to printf. Still though, that's still a performance impact.

Variable Number of for loops with code in between [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
So the problem I have is that I want to implement N for loops in the following way (where N is a variable):
for i0=0:MAX
cOR[0] = initial + move[i0];
for i1=0:MAX
cOR[1] = cOR[0] + move[i1];
....
some other stuff inside the final loop
(cOR is a vector of length equal to the number of for loops)
So I found this solution that works when you just have the nested loops (https://stackoverflow.com/a/20577981/3932908) but have been struggling to modify it for my particular case which requires code in between the for loops. Is there a simple way to implement this or is a different approach needed?
The general approach is to
Write a recursive function.
If recursion is not for some reason appropriate for your code (e.g. very long recursion depth, or the ability to suspend the execution is required), then convert the recursive version to an iterative one by explicitly modeling the stack.
Doing №1 is easy:
void f(int depth, int initial, int *cOR)
{
if(your termination condition)
{
// some other stuff inside the final loop, and...
return;
}
for(int i = 0; i < MAX; ++i)
{
cOR[depth] = initial + move[i];
f(depth+1, cOR[depth]);
}
}
And call it like so:
f(0, initial, cOR);
Now we head to №2, i.e. converting to a non-recursive version. The extra state we need is what was stored on the stack before: the values of the i variables. So here we go:
int i[max_depth];
int depth = 0;
for(;;)
{
if(your termination condition)
{
// some other stuff inside the final loop, and...
do {
if(--depth < 0)
return;
} while(++i[depth] >= MAX);
}
else
i[depth] = 0;
cOR[depth] = (depth > 0 ? cOR[depth-1] : initial) + move[i[depth]];
++depth;
}
If you can't estimate max_depth a priori then you can switch to a dynamically allocated array that grows as you need.

Chessboard game...but a different one [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
https://www.hackerrank.com/challenges/chessboard-game-again-1
I have tried the above question in the following manner but the answers are evaluated as wrong.(I am not asking for a solution, but I am asking for the defects in the approach);
my code (please ignore the c99 errors)
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
int numofmov = 0;
int issafe(int a,int b){
if(a>=0 && a<15 && b>=0 && b<15)
return 1;
return 0;
}
void move(int board[][15]){
for(int i=0;i<15;i++){
for(int j=0;j<15;j++){
if(board[i][j]>0){
board[i][j]--;
if(issafe(board,i-2,j+1)==1) {
numofmov++;
board[i-2][j+1]++;
}
if(issafe(board,i-2,j-1)==1) {
numofmov++;
board[i-2][j-1]++;
}
if(issafe(board,i+1,j-2)==1) {
numofmov++;
board[i+1][j-2]++;
}
if(issafe(board,i-1,j-2)==1) {
numofmov++;
board[i-1][j-2]++;
}
}
}
}
}
int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
int t;
scanf("%d",&t);
while(t--){
int k;
scanf("%d",&k);
int board[15][15];
for(int j=0;j<15;j++){
for(int h=0;h<15;h++){
board[j][h]=0;
}
}
for(int i=0;i<k;i++){
int x,y;
scanf("%d %d",&x,&y);
board[x-1][y-1]++;
}
int bro=0,mov=numofmov;
while(bro==0){
move(board);
if(numofmov==mov){
bro++;
printf("Second\n");
break;
}
mov = numofmov;
move(board);
if(numofmov==mov){
bro++;
printf("First\n");
break;
}
mov = numofmov;
}
}
return 0;
}
My approach is to go on making all the moves possible for all the coins until we come to a point when no moves are possible. But this is giving wrong answers in some test cases.
You are asking what is wrong with this approach ?
"My approach is to go on making all the moves possible for all the
coins until we come to a point when no moves are possible. But this is
giving wrong answers in some test cases."
I didn't read your code, but I can say that the main issue is your approach itself. You are thinking of this problem as a brute-force (make all possible move paths, and see who is winning). The number of possible moves can be arbitrarily large, checking is moves lead to a win is infinitely slow. In reality it is either dynamic-programming, or even more relevant game-theory problem.
Think about it this way. Does the starting positions uniquely identifies the winner of this game? What if I change the initial position of a single coin, will the winner change too?
Best way to approach this kind of problems is to simplify it. Assume that there is only a single board with a single coin, positioned at (x,y). Now notice, that after each move of a coin from position (x,y) to position (a,b), the following is true a+b<x+y. So if (x,y) is one of (1,1),(1,2),(2,1),(2,2), player making the move already lost. So my goal is to make sure my opponent will be making a move from already lost position, and if I can do it, I am in winning position. If u follow the same logic, you will realise that this approach will uniquely identify if position is winning or losing. So for any position we can answer if it is winning or losing simply building the grid of answers by going backwards from (1,1) to (15,15).
Now what would u do if the number of boards is more than one? You need to dig into the game theory, in particular Grundy numbers and how they relate to Nim games. I would suggest you to check the following links for further information:
https://en.wikipedia.org/wiki/Nim
https://en.wikipedia.org/wiki/Nimber
https://www.topcoder.com/community/data-science/data-science-tutorials/algorithm-games/

What is the complexity of the following simple program? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I am having trouble finding understanding complexity. Could someone help me understand what the complexity of the code below is and why.
for (int i = 1; i < n; i++) { // (n is a number chosen by the user)
for (int j = i - 1; j >= 0; j--) {
printf("i=%d, j=%d", i, j);
}
}
An explanation would be great.
Assuming i starts at 0, the complexity would be constant. The complexity is always expressed relative to a variable defining the number of executions, which is not the case here.
If one term should be used to describe this behavior, it is "constant". There will be a number of executions, but this number will never change
Original Question: Because i's initial value is undefined, the behavior of the code is unpredictable. There is no way to usefully answer the question other than that the complexity is undefined. There is no way to know how many operations the code will perform.
Updated Question: It's O(1). The code will always do precisely the same amount of work.
You can compute the time complexity of this code fragment by evaluating the number of operations, namely the number of calls to printf() which for simplicity's sake we shall assume to be equivalent:
Assuming i starts at 1 (you initially forgot to initialize it), the outer loop runs 99 times, for each iteration, the inner loop runs i times. Gauss was supposedly 9 years old when he computed the resulting number of iterations to be 99 * (99 + 1) / 2.
The complexity of the original piece of code was O(1) since it did not depend on any variable, but since instead you updated the code as:
void fun(int n) {
for (int i = 1; i < n; i++) {
for (int j = i - 1; j >= 0; j--) {
printf("i=%d, j=%d", i, j);
}
}
}
The time complexity would come out as O(n2).

Resources