Task:
A lock has n buttons in it, numbered from 1 to n. To open the lock, you have to press all buttons in some order, i.e. a key to the lock is a permutation of the first n integers. If you push the right button in the right order, it will be pressed into the lock. Otherwise all pressed buttons will pop out. When all buttons are pressed into the lock, it opens.
Your task is to calculate the number of times you've got to push buttons in order to open the lock in the worst-case scenario.
My decision:
public class Main {
public static long pressCounter = 0;
public static long step = 2;
public static long PressButton(long n)
{
if (n == 0) return 0;
if (n == 1) return 1;
if (n == 2) return 2;
long temp = (n - step) * step + 1;
pressCounter += temp;
if ((n - step) != 0) {
step++;
PressButton(n);
}
long result = n + pressCounter;
return result;
}
public static void main(String[] args) {
System.out.println(PressButton(3));
System.out.println(PressButton(4));
}
}
Two or more runs of this method give an unexpected solution. I think it's the pressCounter and step variables. How can I fix it?
System.out.println(PressButton(3));
expecting - 7
System.out.println(PressButton(4));
expecting - 14