M
M
mk_qwerty2019-10-17 21:14:08
Java
mk_qwerty, 2019-10-17 21:14:08

How to find an efficient solution to a problem (Java)?

Good day, I solved the problem, but the solution is not effective. How can you make it more efficient and shorter?
Problem Statement: Write a program that takes an integer in n as a command-line argument and uses nested loops to output a chessboard of n*n elements.

public class checkerBoard{
  public static void main(String[] args){
    int n = Integer.parseInt(args[0]);

    for (int i = 1; i <= n; i++){
        for (int j = 1; j <= n; j++){
          if (i % 2 == 0){
            if(j % n != 0){
              if (j % 2 == 0){
                System.out.print("*");
              }
              else System.out.print("-");
            }
            else{
              if (j % 2 == 0){
                System.out.println("*");
              }
              else System.out.println("-");
            }
          }
          else{
            if(j % n != 0){
              if (j % 2 == 0){
                System.out.print("-");
              }
              else System.out.print("*");
            }
            else{
              if (j % 2 == 0){
                System.out.println("-");
              }
              else System.out.println("*");
            }
          }

        }
    }
  }
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry Alexandrov, 2019-10-17
@mk_qwerty

Viktor Malkov ,
still in the piggy bank, not shorter, but will cause an attack among haters of lambdas and streams

IntStream.rangeClosed(1, n).forEach(i -> {
            IntStream.rangeClosed(1, n).forEach(j -> 
                System.out.print((i + j) % 2 == 0 ? '*' : '-'));
        System.out.println();});

Another perversion, the truth will only work with odd numbers, but in one cycle! =).
IntStream.rangeClosed(1, n*n).forEach(i -> System.out.print(i % n != 0 ? (i % 2==0 ?'*':'-') : '\n'));

K
krka92, 2019-10-17
@krka92

Java, alas, I do not know

procedure WriteCheckLine(Len: Integer; Offset: Byte);
var i: Integer;
begin
  for i := Offset to Len - 1 + Offset do
  begin
    if i and 1 > 0 then Write('*')
    else Write('-');
  end;
  WriteLn;
end;

procedure WriteCheckBoard(N: Integer);
var i: Integer;
begin
  for i := 0 to N - 1 do WriteCheckLine(N, i and 1);
end;

or no call
procedure WriteCheckBoard(N: Integer);
var i, j, Offset: Integer;
begin
  for i := 0 to N - 1 do
  begin
    Offset := i and 1;
    for j := Offset to N - 1 + Offset do
    begin
      if j and 1 > 0 then Write('*')
      else Write('-');
    end;
    WriteLn;
  end;
end;

How will it be more convenient

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question