Alice and Borys are playing tennis and it is unknown who served the first game. After each game, the serve changes to other player. If the server wins the game, then it is said that s/he holds the serve and if the receiver wins the game then it is said that s/he breaks the serve.
If Alice won a times and Borys won b times in (a+b) no of games then find all possible values of k such that exactly k breaks of serve occurred in the entire match.
I have written this code but I think I have missed some edge cases.
package com.company;
public class KBreaksInTennis {
static int[] displayKBreaks(int a, int b) {
int t = a + b;
//it was given k ranges upto a+b+1
int[] arrayOfK = new int[t + 1];
int lastIndex = -1;
boolean isEven = false;
if (t % 2 == 0) {
isEven = true;
}
for (int k = 0; k <= t; k++) {
System.out.println("For k = " + k);
for (int i = 0; i <= k / 2; i++){
// checks if the 'no_of_breaks' is more than the 'no of chances to break'
if (!(k - i > (t / 2) + 1)) {
int j = k - i;
if (isEven) {
int c1 = (t / 2 - i) + j;
if (c1 == a || c1 == b) {
arrayOfK[++lastIndex] = k;
}
} else {
// all the possibilities of breaking the serve
//like who breaks the serve how many times
//is it the player occuring t/2 times or t/2 +1 times
//and who is it alice or borys( a or b respectively)
int c1 = ((t / 2) - i) + j;
int c2 = ((t / 2) + 1 - j) + i;
int c3 = ((t / 2) + 1 - i) + j;
int c4 = -1;
// since j can be more than t/2
if (j <= (t / 2)) {
c4 = ((t / 2) - j) + i;
}
if ((c1 == a && c2 == b) || (c1 == b && c2 == a) ) {
arrayOfK[++lastIndex] = k;
}
if (c4 != -1) {
if ((c3 == a && c4 == b) || (c3 == b && c4 == a)) {
arrayOfK[++lastIndex] = k;
}
}
}
}
}
}
return arrayOfK;
}
public static void main(String[] args) {
int[] arrOfK = displayKBreaks(0, 5);
System.out.println(arrOfK.length);
for (int i : arrOfK) {
System.out.print(i + " ");
}
}
}
a=2, b=1
and the expected output is4
and0 1 2 3
, but your program throws anArrayIndexOutOfBoundsException
. \$\endgroup\$