简体   繁体   中英

Need help shifting latin square in Java

I'm currently making a latin square that starts with a user-set number but for simplicity's sake I'll exclude Scanner code.

  public static void main(String[] args){
  
  int first = 2; // starting integer on square
  int order = 4; //max integer
  String space = new String(" "); 

  for (int row = 0; row < order; row++)
     {
      for (int column = 0; column < order; column++)
      {    
        for (int shift = 0; shift < order; shift++)
          {
            int square = ((column+(first-1)) % order + 1); //this makes a basic square with no shifting
            int latin = square+shift; //this is where my code becomes a mess
            System.out.print(latin + space);
          }
     System.out.println();
       }  
     }
  }
}

Which prints out:

2 3 4 5 
3 4 5 6 
4 5 6 7 
1 2 3 4 
2 3 4 5 
3 4 5 6 
4 5 6 7 
1 2 3 4 

It's so close, considering the fact that it does start with my pre-determined first digit and it's printing only 4 integers. The problem I'm running into is the fact that it's going further than my order integer and that it's printing double the rows. Any idea what I can do to fix this?

For reference, this is what I want it to print:

2 3 4 1
3 4 1 2
4 1 2 3
1 2 3 4

It seems that the innermost loop for (int shift...) is redundant and it causes duplication of the output, the latin value should be calculated using row parameter:

public static void main(String args[]) {
    int first = 2; // starting integer on square
    int order = 4; //max integer
    String space = " "; 

    for (int row = 0; row < order; row++) {
        for (int column = 0; column < order; column++) {    
            int latin = (row + column + first - 1) % order + 1;
            System.out.print(latin + space);
        }
        System.out.println();

    }
}

Output:

2 3 4 1 
3 4 1 2 
4 1 2 3 
1 2 3 4 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM