zer0-day
zer0-day

Reputation: 7

Building a simple Chess board with recursion in java

I'm trying to build a simple chess board layout in java via recursion but my problem is, that in each recursive call the amount of fields are reduced by one which is wrong. Black fields are represented by a "#" and white fields by space. I've done this with Iteration which was no problem but the recursive approach gives me headaches.

import java.util.Scanner;

public class Chess {

public static int chess(int boardlength) {

    if (boardlength == 0) {
        return boardlength;
    } else {
        pattern(boardlength);
        System.out.println("\n");
    }
    return chess(boardlength - 1);
}

    public static int pattern(int runs) {

        if (runs == 0) {
            return runs;
        } else {
            if (runs % 2 != 0) {
                System.out.print("#");
            } else {
                System.out.print(" ");
            }
        }
        return pattern(runs - 1);
    }

public static void main(String[] args) {

    Scanner input = new Scanner(System.in);
    System.out.print("Length of the board: ");
    int boardlength = input.nextInt();
    chess(boardlength);
}

}

Upvotes: 0

Views: 423

Answers (1)

theBittor
theBittor

Reputation: 834

I know this is not the prettiest code in the world, but it does the trick

I use a second variable calls to calculate the number of recursions needed. With this, I could use the boardlength variable to print each row.

import java.util.Scanner;

public class Chess {

  public static int chess(int boardlength, int calls) {

    if (calls == boardlength ) {
      return boardlength;
    } else {
      pattern(boardlength, calls % 2 != 0);
      System.out.println("\n");
    }
    return chess(boardlength, calls + 1);
  }

  public static int pattern(int runs, boolean pat) {

    if (runs == 0) {
      return runs;
    } else {
      if (pat) {
        System.out.print("#");
      } else {
        System.out.print("@");
      }
    }
    return pattern(runs - 1, !pat);
  }

  public static void main(String[] args) {

    Scanner input = new Scanner(System.in);
    System.out.print("Length of the board: ");
    int boardlength = input.nextInt();
    chess(boardlength, 0);
  }

}

Output with boardlenth=8 (I change the space for a @)

@#@#@#@#

#@#@#@#@

@#@#@#@#

#@#@#@#@

@#@#@#@#

#@#@#@#@

@#@#@#@#

#@#@#@#@

Upvotes: 1

Related Questions