My code for the jug puzzle is not working

Asked

Viewed 84 times

0

First of all, I want to thank everyone who reads my call for help. I’m pretty new to the C language, and I’m pretty sure I made a mistake, and I’m pretty sure I didn’t miss that code. I spent all day trying to write it but I can’t find the mistake. I think it’s some inappropriate use of pointers in the swap() function or some other silly thing I did. Anyway, there it is. Please forgive the noobagens, I did everything with my best. The program even accepts some moves, but most do not. I am using Ubuntu in its latest version.

Edit1: The problem with jugs is the following: You have three jars on a table in front of you. The first holds three litres, the second five litres and the last eight litres, and is the only one that is full. Your goal is to separate four liters in the b and c jugs, and the only move you can make is to exchange the liquid from one jug to the other until it reaches the limit of the jug you receive, or until the liquid in the vase you pour runs out.

Edit2: I made some small modifications and the program hits some answers precisely, for example:

State:
a = 0, b = 0, c = 8
>3 1
State:
a = 3, b = 0, c = 5

But transferring from c to b does not return the expected:

State:
a = 3, b = 0, c = 5
>3 2
State:
a = 3, b = 3, c = 2

Thanks in advance.

Edit3: Commented code for better understanding.

#include <stdio.h>
#include <math.h>
#include <stdbool.h>
#define MAXA 3 //Defino o maximo da variável a, e etc;
#define MAXB 5
#define MAXC 8

int a = 0, b = 0, c = 8; //Defino que só a terceira está cheia.
void swap(int *po, int *pd) //Função de troca, aceita dois ponteiros para inteiros,
{                           // Mas não sei se estou a usar corretamente;
  int maxor, maxdes; //Defino duas variáveis que comportarão o máximo da origem e destino.
  if(po != &a && po != &b && po != &c || pd != &a && pd != &b && pd != &c || po == pd) //Caso for inválido,
    return; //quebre.
  if(po == &a) //Se o ponteiro recebido apontar para a, máximo da origem é MAXA, etc...
    maxor = MAXA;
  if(po == &b)
    maxor = MAXB;
  if(po == &c)
    maxor == MAXC;
  if(pd == &a)
    maxdes = MAXA;
  if(pd == &b)
    maxdes == MAXB;
  if(pd == &c)
    maxdes == MAXC;
  int d = maxdes - *pd; //Variável que define o quanto o destino comporta, e o quanto a origem fornecerá.
  *pd += d;
  *po -= d;

}
int main()
{
  int *pa = &a; //Defino os ponteiros para as respectivas variáveis.
  int *pb = &b;
  int *pc = &c;
  while(b != 4 && c != 4) //Enquanto não houver quatro litros em b e c;
  {
    int (*alfa), (*beta); //Ponteiros que eventualmente apontarão pra escolha do usuário.
    int cho, chos; //Inteiros de escolha de origem e destino.
    printf("State:\na = %i, b = %i, c = %i\n>", a, b, c); //Imprime o estado atual.
    scanf("%i %i", &cho, &chos);
    if(cho == 1) //Caso cho seja 1, o ponteiro alfa aponta para a, e etc.
      alfa = &a;
    if(cho == 2)
      alfa = &b;
    if(cho == 3)
      alfa = &c;
    if(chos == 1)
      beta = &a;
    if(chos == 2)
      beta = &b;
    if(chos == 3)
      beta = &c;
    swap(alfa, beta); //Realize a troca entre alfa e beta;
  }
}
  • In your swap function, first if, do you really want to compare the address of the variables? I see no sense in it, I think I should compare the contents of these variables.

1 answer

0


I believe that your program could have many of its features re-thought, such as the need to have global variables and the need to make use of so many pointers, since there are only three pots. However, I will not address this in the reply, since you asked for it. The main problem can be fixed just by looking at the warnings that the compiler returns (preferably compiling with the option -Wall). Though there have been more than one, I will omit the like, leaving the following:

testeC.c:19:11: warning: equality comparison result unused [-Wunused-comparison]
    maxor == MAXC;
    ~~~~~~^~~~~~~
testeC.c:12:27: warning: '&&' within '||' [-Wlogical-op-parentheses]
  if(po != &a && po != &b && po != &c || pd != &a && pd != &b && pd != &c || po == pd) //Caso for inválido,
     ~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~ ~

The first Warning shows that you have confused the assignment operator =, with the comparison operator ==. On some lines you have used maxor==MAX_ when you should have used maxor=MAX_. This is the case for lines 19, 23 and 25.

Also, the other warns you about something that should always be done in the case of logical if’s like yours. You should always use parentheses to explain to the compiler the order you want it to perform operations. In the doubt about the precedence of the operators, my suggestion is to err on the exaggeration and the easy reading of the code. With these modifications the code seems to work:

State:
a = 0, b = 0, c = 8
>3 1
State:
a = 3, b = 0, c = 5
>3 2
State:
a = 3, b = 5, c = 0

Finally, I believe you forgot to check at the end of the swap function if the source jug has enough content to make the transition. You check only the capacity at the destination. This generates the following mistake:

State:
a = 0, b = 0, c = 8
>3 1
State:
a = 3, b = 0, c = 5
>3 2
State:
a = 3, b = 5, c = 0
>1 3
State:
a = -5, b = 5, c = 8

As there were few modifications, I believe it is not necessary to re-put the full code here, but if you need or have any additional questions just ask.

  • Thank you very much, now it’s working perfectly.

  • You are welcome! Do not forget to mark the answer as accepted, so the question is resolved, and help any site searches.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.