When the coef is 0, I used continue to not print, but only printTerm(a) comes out and the printTerm(b) part does not come out.
When I delete the (if & continue) statement, both printTerm(a) and printTerm(b) appear, so it seems that there is a problem here (if & continue) statement.
How can I solve this?
int main() {
a[0].coef = 2;
a[0].expon = 1000; // 2x^1000
a[1].coef = 1;
a[1].expon = 2; // x^2
a[2].coef = 1;
a[2].expon = 0; // 1
b[0].coef = 1;
b[0].expon = 4; // x^4
b[1].coef = 10;
b[1].expon = 3; // 10x^3
b[2].coef = 3;
b[2].expon = 2; // 3x^2
b[2].coef = 1;
b[2].expon = 0; // 1
printTerm(a);
printTerm(b);
return 0;
}
void printTerm(polynomial *p) {
int i=0;
printf("polynomial : ");
while(p[i].expon != -1) {
if(p[i].coef == 0) continue;
printf("%dx^%d", p[i].coef, p[i].expon);
i++;
if(p[i].expon != -1 && p[i].coef > 0) printf(" + ");
}
printf("\n");
}
Because you only increment i if p[i].coef is not equal to 0.
If p[i].coef == 0 it skips the increment part and function is stuck in infinite loop, always checking the same array item.
EDIT:
Way to fix this:
Instead of if(p[i].coef == 0) continue; use:
if (p[i].coef == 0)
{
i++;
continue;
}
This way while loop evaluetes next array item instead of being stuck on the same.
Related
Hello I have the following code in C and when the code clause:
if (idx - 1 == 0) {
return opening_address;
}
executes it returns to the While loop's predicate rather than actually returning and ending the function. The code does get hit and likewise for the other return statement in the loop and both have the same behavior and basically do a continue action.
int find_smallest_free_block(int block_size) {
int opening_address = 0;
int idx = 0;
while (idx + lowestPower <= highestPower) {
if (powers[idx].hasHoles) {
if (powers[idx].size > block_size) {
opening_address = powers[idx].head_p->start_address;
// Add 2 holes to the next power down
int try = 0;
try = addHole(idx - 1, powers[idx].head_p->start_address, powers[idx].head_p->end_address / 2);
try = addHole(idx - 1, powers[idx].head_p->end_address / 2, powers[idx].head_p->end_address);
// Remove hole at power
try = removeHole(idx, powers[idx].head_p->start_address);
if (idx - 1 == 0) {
return opening_address; // cant make holes at lowest level
}
idx -= 1;
continue;
} else {
return opening_address;
}
}
idx += 1;
}
return opening_address;
}
I'm trying to implement the Join Five game. It is a game where, given a grid and a starting configuration of dots, you have to add dots in free crossings, so that each dot that you add forms a 5-dot line with those already in the grid. Two lines may only have 1 dot in common (they may cross or touch end to end)
My game grid is an int array that contains 0 or 1. 1 if there is a dot, 0 if there isn't.
I'm doing kinda well in the implementation, but I'd like to display all the possibles moves.
I made a very long and ugly function that is available here : https://pastebin.com/tw9RdNgi (it was way too long for my post i'm sorry)
here is a code snippet :
if(jeu->plat[i][j] == 0) // if we're on a empty spot
{
for(k = 0; k < lineSize; k++) // for each direction
{
//NORTH
if(jeu->plat[i-1-k][j] == 1) // if there is a dot north
{
n++; // we count it
}
else
{
break; //we change direction
}
} //
This code repeats itself 7 other times changing directions and if n or any other variable reaches 4 we count the x and y as a possible move.
And it's not even treating all the cases, if the available spot is between 2 and 2 dots it will not count it. same for 3 and 1 and 1 and 3.
But I don't think the way I started doing it is the best one. I'm pretty sure there is an easier and more optimized way but i can't figure it out.
So my question is: could somebody help me figure out how to find all the possible 5-dot alignments, or tell me if there is a better way of doing it?
Ok, the problem is more difficult than it appears, and a lot of code is required. Everything would have been simpler if you posted all of the necessary code to run it, that is a Minimal, Complete, and Verifiable Example. Anyway, I resorted to putting together a structure for the problem which allows to test it.
The piece which answers your question is the following one:
typedef struct board {
int side_;
char **dots_;
} board;
void board_set_possible_moves(board *b)
{
/* Directions
012
7 3
654 */
static int dr[8] = { -1,-1,-1, 0, 1, 1, 1, 0 };
static int dc[8] = { -1, 0, 1, 1, 1, 0,-1,-1 };
int side_ = b->side_;
char **dots_ = b->dots_;
for (int r = 0; r < side_; ++r) {
for (int c = 0; c < side_; ++c) {
// The place already has a dot
if (dots_[r][c] == 1)
continue;
// Count up to 4 dots in the 8 directions from current position
int ndots[8] = { 0 };
for (int d = 0; d < 8; ++d) {
for (int i = 1; i <= 4; ++i) {
int nr = r + dr[d] * i;
int nc = c + dc[d] * i;
if (nr < 0 || nc < 0 || nr >= side_ || nc >= side_ || dots_[nr][nc] != 1)
break;
++ndots[d];
}
}
// Decide if the position is a valid one
for (int d = 0; d < 4; ++d) {
if (ndots[d] + ndots[d + 4] >= 4)
dots_[r][c] = 2;
}
}
}
}
Note that I defined a square board with a pointer to pointers to chars, one per place. If there is a 0 in one of the places, then there is no dot and the place is not a valid move; if there is a 1, then there is a dot; if there is a 2, then the place has no dot, but it is a valid move. Valid here means that there are at least 4 dots aligned with the current one.
You can model the directions with a number from 0 to 7 (start from NW, move clockwise). Each direction has an associated movement expressed as dr and dc. Moving in every direction I count how many dots are there (up to 4, and stopping as soon as I find a non dot), and later I can sum opposite directions to obtain the total number of aligned points.
Of course these move are not necessarily valid, because we are missing the definition of lines already drawn and so we cannot check for them.
Here you can find a test for the function.
#include <stdio.h>
#include <stdlib.h>
board *board_init(board *b, int side) {
b->side_ = side;
b->dots_ = malloc(side * sizeof(char*));
b->dots_[0] = calloc(side*side, 1);
for (int r = 1; r < side; ++r) {
b->dots_[r] = b->dots_[r - 1] + side;
}
return b;
}
board *board_free(board *b) {
free(b->dots_[0]);
free(b->dots_);
return b;
}
void board_cross(board *b) {
board_init(b, 18);
for (int i = 0; i < 4; ++i) {
b->dots_[4][7 + i] = 1;
b->dots_[7][4 + i] = 1;
b->dots_[7][10 + i] = 1;
b->dots_[10][4 + i] = 1;
b->dots_[10][10 + i] = 1;
b->dots_[13][7 + i] = 1;
b->dots_[4 + i][7] = 1;
b->dots_[4 + i][10] = 1;
b->dots_[7 + i][4] = 1;
b->dots_[7 + i][13] = 1;
b->dots_[10 + i][7] = 1;
b->dots_[10 + i][10] = 1;
}
}
void board_print(const board *b, FILE *f)
{
int side_ = b->side_;
char **dots_ = b->dots_;
for (int r = 0; r < side_; ++r) {
for (int c = 0; c < side_; ++c) {
static char map[] = " oX";
fprintf(f, "%c%s", map[dots_[r][c]], c == side_ - 1 ? "" : " - ");
}
fprintf(f, "\n");
if (r < side_ - 1) {
for (int c = 0; c < side_; ++c) {
fprintf(f, "|%s", c == side_ - 1 ? "" : " ");
}
fprintf(f, "\n");
}
}
}
int main(void)
{
board b;
board_cross(&b);
board_set_possible_moves(&b);
board_print(&b, stdout);
board_free(&b);
return 0;
}
I am fighting some simple question.
I want to get prime numbers
I will use this algorithm
and... I finished code writing like this.
int k = 0, x = 1, n, prim, lim = 1;
int p[100000];
int xCount=0, limCount=0, kCount=0;
p[0] = 2;
scanf("%d", &n);
start = clock();
do
{
x += 2; xCount++;
if (sqrt(p[lim]) <= x)
{
lim++; limCount++;
}
k = 2; prim = true;
while (prim && k<lim)
{
if (x % p[k] == 0)
prim = false;
k++; kCount++;
}
if (prim == true)
{
p[lim] = x;
printf("prime number : %d\n", p[lim]);
}
} while (k<n);
I want to check how much repeat this code (x+=2; lim++; k++;)
so I used xCount, limCount, kCount variables.
when input(n) is 10, the results are x : 14, lim : 9, k : 43. wrong answer.
answer is (14,3,13).
Did I write code not well?
tell me correct point plz...
If you want to adapt an algorithm to your needs, it's always a good idea to implement it verbatim first, especially if you have pseudocode that is detailed enough to allow for such a verbatim translation into C-code (even more so with Fortran but I digress)
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
int main (void){
// type index 1..n
int index;
// var
// x: integer
int x;
//i, k, lim: integer
int i, k, lim;
// prim: boolean
bool prim;
// p: array[index] of integer {p[i] = i'th prime number}
/*
We cannot do that directly, we need to know the value of "index" first
*/
int res;
res = scanf("%d", &index);
if(res != 1 || index < 1){
fprintf(stderr,"Only integral values >= 1, please. Thank you.\n");
return EXIT_FAILURE;
}
/*
The array from the pseudocode is a one-based array, take care
*/
int p[index + 1];
// initialize the whole array with distinguishable values in case of debugging
for(i = 0;i<index;i++){
p[i] = -i;
}
/*
Your variables
*/
int lim_count = 0, k_count = 0;
// begin
// p[1] = 2
p[1] = 2;
// write(2)
puts("2");
// x = 1
x = 1;
// lim = 1
lim = 1;
// for i:=2 to n do
for(i = 2;i < index; i++){
// repeat (until prim)
do {
// x = x + 2
x += 2;
// if(sqr(p[lim]) <= x) then
if(p[lim] * p[lim] <= x){
// lim = lim +1
lim++;
lim_count++;
}
// k = 2
k = 2;
// prim = true
prim = true;
// while (prim and (k < lim)) do
while (prim && (k < lim)){
// prim = "x is not divisible by p[k]"
if((x % p[k]) == 0){
prim = false;
}
// k = k + 1
k++;
k_count++;
}
// (repeat) until prim
} while(!prim);
// p[i] := x
p[i] = x;
// write(x)
printf("%d\n",x);
}
// end
printf("x = %d, lim_count = %d, k_count = %d \n",x,lim_count,k_count);
for(i = 0;i<index;i++){
printf("%d, ",p[i]);
}
putchar('\n');
return EXIT_SUCCESS;
}
It will print an index - 1 number of primes starting at 2.
You can easily change it now--for example: print only the primes up to index instead of index - 1 primes.
In your case the numbers for all six primes up to 13 gives
x = 13, lim_count = 2, k_count = 3
which is distinctly different from the result you want.
Your translation looks very sloppy.
for i:= 2 to n do begin
must translate to:
for (i=2; i<=n; i++)
repeat
....
until prim
must translate to:
do {
...
} while (!prim);
The while prim... loop is inside the repeat...until prim loop.
I leave it to you to apply this to your code and to check that all constructs have been properly translated. it doesn't look too difficult to do that correctly.
Note: it looks like the algorithm uses 1-based arrays whereas C uses 0-based arrays.
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 8 years ago.
Improve this question
I have a project yet my teacher hasn't taught us about arrays. We need to output =<> signs corresponding to the comparison of one number to another. IE the main number is 1234 and I put in 2315, the output would be <<<> where the signs do not go in the order of the numbers but by this order =, <, >.
I have an idea and that to use an array then to use some code that would read out the whole array and apply rules to it, however I do not know how to implement this. I have been googling for awhile now and nothing I found really helps.
Just to let you know the program has way more steps than just this, all of which I have already completed, I just can't figure out this part. I do not want just the answer, I just want someone to point me in the right direction.
Thanks
EDIT:: The example 1234 and 2315 are bad examples. To give a more definitive idea without giving away too much of the problem so I have work to do is listing num1 and num2 (corresponding to 1234 and 2315) from least to greatest or greatest to least and compare that way. So another example would be 4751 is the main number and I put in 1294. The output would be ==<>. Thanks for the help guys so far. I am learning a lot.
EDIT2:: Thanks guys for the help. I learned a lot. I don't want any more submissions at least until I can upload my code.
Taking you at your word that you've already successfully completed most of your assignment, and by giving you code that you'll have to work through and understand to figure it out and adapt it to your needs, this will do what you want. The fact that you don't have to output the signs in the same order as the numbers themselves is what makes this easier.
#include <stdio.h>
int main(void) {
int num1 = 1234;
int num2 = 2315;
int lt = 0, gt = 0, eq = 0;
while ( num1 > 0 && num2 > 0 ) {
int op1 = num1 % 10;
int op2 = num2 % 10;
if ( op1 < op2 ) {
++lt;
} else if ( op1 > op2 ) {
++gt;
} else {
++eq;
}
num1 /= 10;
num2 /= 10;
}
for ( int i = 0; i < eq; ++i ) {
putchar('=');
}
for ( int i = 0; i < lt; ++i ) {
putchar('<');
}
for ( int i = 0; i < gt; ++i ) {
putchar('>');
}
putchar('\n');
return 0;
}
and outputs:
paul#MacBook:~/Documents/src/scratch$ ./eq
<<<>
paul#MacBook:~/Documents/src/scratch$
This code lets you get the nth digits you can compare and make a count of each symbol you need to return
char nthdigit(int x, int n)
{
while (n--) {
x /= 10;
}
return (x % 10) + '0';
}
And this is how you get the length of a number, check this post
As promised here is the rest of my code. It fixes the issue pointed out in the question but I have another issue. It is probably pretty noticeable but I wanted to post my code so I don't forget again.
#include<stdio.h>//standard inputs and outputs
#include<stdlib.h>//for compare, qsort, srand, and rand function
#include<time.h>//for random numbers at different times
#include<unistd.h>//for fun at the end
int main(void){
int guess, gdig1, gdig2, gdig3, gdig4, random, rdig1, rdig2, rdig3, rdig4;//variables for main
int lt, gt, eq, i, q, temp, holder;//this is for the hints
int g[3],r[3];
printf("Give the computer a few seconds to come up with a super secret passcode.\n");
do{//figuring out a random code
unsigned int iseed = (unsigned int)time(NULL);
srand (iseed);//using an unassigned integer
random = rand()%9000+1000;//generating a random number but limiting it
rdig4 = random%10;
rdig3 = (random/10)%10;
rdig2 = (random/100)%10;
rdig1 = (random/1000)%10;//figuring out the individual digits of the code
} while ((rdig1 == rdig2)||(rdig1 == rdig3)||(rdig1 == rdig4)||(rdig2 == rdig3)||(rdig2 == rdig4)||(rdig3 == rdig4)||(rdig1 == 0)||(rdig2 == 0)||(rdig3 == 0)||(rdig4 == 0));
//^^ some crazy boolean expression making sure the random integer doesnt have any of the same digits.
printf("\nThe actual passcode is:%d.\n",random);//testing in beginning comment out ********
do{
do{
printf("\nEnter in your guess for the passcode: ");
scanf("%d",&guess);//inputting and reading the guessed code
// printf("You entered:%d\n",guess);//just to check comment out at end**
gdig4 = guess%10;
gdig3 = (guess/10)%10;
gdig2 = (guess/100)%10;
gdig1 = (guess/1000)%10;//figuring out the individual digits of the guess code using modulus operator
if (guess > 9999){//the starting loop statement to make sure number is valid. this one is if it is greater than 4 digits
printf("\nPlease use a four digit number for the passcode.\n");
}
else if (guess < 1000){//this one is if it is less than 4 digits
printf("\nPlease use a four digit number for the passcode.\n");
gdig1 = 1;
gdig2 = 1;//used so the computer still loops
gdig3 = 1;
gdig4 = 1;
}
if ((gdig1 == 0) || (gdig2 == 0) || (gdig3 == 0) || (gdig4 == 0)){
break;
}
if ((rdig1 == gdig1) && (rdig2 == gdig2) && (rdig3 == gdig3) && (rdig4 == gdig4)){//to skip this codeblock and move onto next
break;
}
if (guess > 9999){
break;
}
if (guess < 1000){
break;
}
printf("\n%d %d %d %d\n",rdig1,rdig2,rdig3,rdig4); //used to testing comment out at end
printf("\n%d %d %d %d\n",gdig1,gdig2,gdig3,gdig4);
while (guess > 0){
g[i++] = guess % 10;
guess /=10;
}
do{//took a long long LONG time to get
for(i = 0; i<3;i++){
if(g[i] > g[i+1]){
holder = g[i+1];
g[i]=g[i+1];
g[i+1] = holder;
}
}
}while (i == 1);
for(i = 0;i<4;i++){
printf("%d",g[i]);
}
while (random > 0){
r[i++] = random % 10;
random /=10;
}
do{//took a long long LONG time to get
for(i = 0; i<3;i++){
if(r[i] > r[i+1]){
temp = r[i+1];
r[i]=r[i+1];
r[i+1] = temp;
}
}
}while (i == 1);
for(i = 0;i<4;i++){
printf("%d",r[i]);
}
/* for(digit=0;digit<4;digit++){
for(tmp=guess;tmp>0;tmp/=10){
if(tmp%10==digit){
printf("%d",digit);
g[i++]=digit;
}
}
}
printf("\n");
for(i=0;i<4;i++){
printf("%d",g[i]);
}//just to check
//this is for sorting the random
for(digit=0;digit<4;digit++){
for(tmp=random;tmp>0;tmp/=10){
if(tmp%10==digit){
printf("%d",digit);
r[i++]=digit;
}
}
}
for(i=0;i<4;i++){
printf("%d",r[i]);
}//just to check
*/
//this is for hints
rdig1=r[0];//redefining the random and guess digits so it is easier later
rdig2=r[1];
rdig3=r[2];
rdig4=r[3];
gdig1=g[0];
gdig2=g[1];
gdig3=g[2];
gdig4=g[3];
q = 0;
eq = 0;
lt = 0;
gt = 0;
if (random > 0){//loop that always holds true
if (gdig1 == rdig1){
eq++;
}else if (gdig1 < rdig1){
lt++;
}else if (gdig1 > rdig1){
gt++;
}
if (gdig2 == rdig2){
eq++;
}else if (gdig2 < rdig2){
lt++;
}else if (gdig2 > rdig2){
gt++;
}
if (gdig3 == rdig3){
eq++;
}else if (gdig3 < rdig3){
lt++;
}else if (gdig3 > rdig3){
gt++;
}
if (gdig4 == rdig4){
eq++;
}else if (gdig4 < rdig4){
lt++;
}else if (gdig4 > rdig4){
gt++;
}
}
for (q = 0; q < eq; q++){//counting step for the = <> no problems here^^
putchar('=');
}
for (q = 0; q < lt; q++){
putchar('<');
}
for (q = 0; q < gt; q++){
putchar('>');
}
//everything below is correct do not mess with *******************************************************************************************
} while (gdig1 > 0);//to loop inputs until they input correctly
if ((gdig1 == 0) || (gdig2 == 0) || (gdig3 == 0) || (gdig4 == 0)){//a nested if statement to check each digit if it is a 0
printf("\nYou have entered the Super Secret Code!!!!!\nThe actual passcode is:%d.\n",random);
break;
}
if ((rdig1 == gdig1) && (rdig2 == gdig2) && (rdig3 == gdig3) && (rdig4 == gdig4)){//to skip this codeblock and move onto next
break;
}
} while (((rdig1 != gdig1) && (rdig2 != gdig2) && (rdig3 != gdig3) && (rdig4 != gdig4)));//to loop inputs until they got it
//everything below is correct do not mess with *******************************************************************************************
if ((rdig1 == gdig1) && (rdig2 == gdig2) && (rdig3 == gdig3) && (rdig4 == gdig4)){
printf("\nCorrect Code inputted.");
sleep(1);
printf("\nImplementing unlocking procedures...\n");
for (i=0;i<=4;i++){//for fun cause why not. if you spend hours on code might as well have some fun :)
int p =25*i ;
printf("%d%% complete................\n",p);
sleep(1);
}
printf("Stand back!!! The vault is now opening.\n");
}
return 0;
}
This is a trivial algorithmic question, I believe, but I don't seem to be able to find an efficient and elegant solution.
We have 3 arrays of int (Aa, Ab, Ac) and 3 cursors (Ca, Cb, Cc) that indicate an index in the corresponding array. I want to identify and increment the cursor pointing to the smallest value. If this cursor is already at the end of the array, I will exclude it and increment the cursor pointing to the second smallest value. If there is only 1 cursor that is not at the end of the array, we increment this one.
The only solutions I can come up are complicated and/or not optimal. For example, I always end up with a huge if...else...
Does anyone see a neat solution to this problem ?
I am programming in C++ but feel free to discuss it in pseudo-code or any language you like.
Thank you
Pseudo-java code:
int[] values = new int[3];
values[0] = aa[ca];
values[1] = ab[cb];
values[2] = ac[cc];
Arrays.sort(values);
boolean done = false;
for (int i = 0; i < 3 && !done; i++) {
if (values[i] == aa[ca] && ca + 1 < aa.length) {
ca++;
done = true;
}
else if (values[i] == ab[cb] && cb + 1 < ab.length) {
cb++;
done = true;
}
else if (cc + 1 < ac.length) {
cc++;
done = true;
}
}
if (!done) {
System.out.println("cannot increment any index");
stop = true;
}
Essentially, it does the following:
initialize an array values with aa[ca], ab[cb] and ac[cc]
sort values
scan values and increment if possible (i.e. not already at the end of the array) the index of the corresponding value
I know, sorting is at best O(n lg n), but I'm only sorting an array of 3 elements.
what about this solution:
if (Ca != arraySize - 1) AND
((Aa[Ca] == min(Aa[Ca], Ab[Cb], Ac[Cc]) OR
(Aa[Ca] == min(Aa[Ca], Ab[Cb]) And Cc == arraySize - 1) OR
(Aa[Ca] == min(Aa[Ca], Ac[Cc]) And Cb == arraySize - 1) OR
(Cc == arraySize - 1 And Cb == arraySize - 1))
{
Ca++;
}
else if (Cb != arraySize - 1) AND
((Ab[Cb] == min(Ab[Cb], Ac[Cc]) OR (Cc == arraySize - 1))
{
Cb++;
}
else if (Cc != arraySize - 1)
{
Cc++;
}
Pseudo code: EDIT : tidied it up a bit
class CursoredArray
{
int index;
std::vector<int> array;
int val()
{
return array[index];
}
bool moveNext()
{
bool ret = true;
if( array.size() > index )
++index;
else
ret = false;
return ret;
}
}
std::vector<CursoredArray> arrays;
std::vector<int> order = { 0, 1, 2 };//have a default order to start with
if( arrays[0].val() > arrays[1].val() )
std::swap( order[0], order [1] );
if( arrays[2].val() < arrays[order[1]].val() )//if the third is less than the largest of the others
{
std::swap( order[1], order [2] );
if( arrays[2].val() < arrays[order[0]].val() )//if the third is less than the smallest of the others
std::swap( order[0], order [1] );
}
//else third pos of order is already correct
bool end = true;
for( i = 0; i < 3; ++i )
{
if( arrays[order[i]].MoveNext() )
{
end = false;
break;
}
}
if( end )//have gone through all the arrays