Same Number Rows Pattern
Problem
Read n and print a triangle where row i contains the number i repeated i times, separated by one space.
Constraints
- 1 <= n <= 20
Examples
Input
3
Output
1 2 2 3 3 3
Solutions
The value written in the row is the row number. The inner loop only decides how many times we write it.
Java 8 has no String.repeat, so we use a small helper method. In Java 11 and newer you can write " ".repeat(count).
/*
* Problem : Rows of repeated numbers.
* Input : One integer n (rows).
* Output : n lines of numbers.
* Approach: Repeat the row number.
* 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: Write the row number "row" times. Example: row 3 -> 3 3 3.
for (int count = 1; count <= row; count++) {
if (count > 1) {
line.append(" ");
}
line.append(row);
}
// Step 3: Print the finished line.
System.out.println(line);
}
}
}
Hints (2)
- Use an outer loop for the rows and an inner loop for the numbers in a row.
- Write the output for n = 3 and look for the rule.