Zero One Triangle Pattern

easy Pattern Printing

Problem

Read n and print a triangle of 1 and 0. Every row ends with 1 and the digits change between 1 and 0 as you move left. Digits are separated by one space. Rule: a digit is 1 when row + column is even.

Constraints

  • 1 <= n <= 20

Examples

Input

3

Output

1
0 1
1 0 1

Solutions

Best approachTime O(n^2)Space O(1)

The digit depends only on the parity (even or odd) of row + column. The last digit of each row is at column = row, so row + column = 2 * row, which is always even, so every row ends with 1.

Same code works in Java810172125Basic features only, so nothing changes between versions.

Java 8 has no String.repeat, so we use a small helper method. In Java 11 and newer you can write " ".repeat(count).

/*
 * Problem : Triangle of 1 and 0.
 * Input   : One integer n (rows).
 * Output  : n lines of digits.
 * Approach: Use the sum of row and column to choose 1 or 0.
 * Time    : O(n^2)
 * Space   : O(1)
 * Java    : 8 or newer.
 */
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        int rows = new Scanner(System.in).nextInt();

        // Step 1: Repeat once for each row. Row numbers go from 1 to rows.
        for (int row = 1; row <= rows; row++) {
            StringBuilder line = new StringBuilder();

            // Step 2: Visit each column of the row. Column numbers go from 1 to row.
            for (int column = 1; column <= row; column++) {
                // Step 3: If row + column is even, write 1. If it is odd, write 0.
                int digit = (row + column) % 2 == 0 ? 1 : 0;

                if (column > 1) {
                    line.append(" ");
                }
                line.append(digit);
            }

            // Step 4: Print the finished line.
            System.out.println(line);
        }
    }
}
Hints (2)
  1. Look for a rule that uses row and column.
  2. What is the parity of row + column on the last column?