Is this logic incorrect? It seems to work for everything I try but apparently it is not right

StackOverflow https://stackoverflow.com/questions/22572703

  •  19-06-2023
  •  | 
  •  

Question

So I have this program about a robber who walks into a bank. He finds N gold bars. He can carry M bars at a time and he takes T seconds to go between his car and the bank.

Input
3
3 2 10
35 68 42
25 70 1

First line is how many times the program will run/how many robberies. First line of the first run (3 2 10), the 3 represents N, the number of gold bars. 2 represents M, number of bars the robber can carry at a time and 10 represents T, the time it takes for the robber to travel between his car and the bank.

Output
30
42
1

This was my logic to it but according to the graders of this program, it failed their test data (they have a different input). I tried many combinations of numbers and the answers still came out right. Does anyone see what could be wrong with this?

/* NOTE:   
1 <= First line of input <= 10    
1 <= N <= 100    
1 <= M <= 100    
1 <= T <= 100  */

public class Stealing
{
    public static void main(String[] args) throws IOException
    {
        Scanner scan = new Scanner (new File ("stealing.dat"));
        int numRuns = scan.nextInt();
        int time = 0;
        for (int i = 0; i < numRuns; i++)
        {
            int N = scan.nextInt();
            int M = scan.nextInt();
            int T = scan.nextInt();
            if (M >= N)
                time = T;
            else
            {
                while (N > 0)
                {
                    if (M <= N)
                        time += (2*T);
                    else
                        time += T;
                    N -= M;
                }
            }
            out.println(time);
            time = 0;
        }
    }
}
Was it helpful?

Solution

The error in your logic shows up when N is a multiple of M, for example the input

6 3 1

produces 4, but it should produce 3.

The problem is with this condition:

if (M <= N)

it should be:

if (M < N)

By testing for equality too, the bank robber makes one more trip back to the bank, but there's nothing to collect, so the loop ends (with her at the bank, rather than at the car - another logic problem).

If I were doing this I would not use a loop - I would use purely numerical methods (an exercise for the reader, but hover over the following to see my solution):

int time = (N / M) * 2 * T + (N % M == 0 ? -T : T);

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top