From fd1fd718f2832b7e0caae2b435a93cf5645b64d9 Mon Sep 17 00:00:00 2001 From: Rob Hallam <0504004h@student.gla.ac.uk> Date: Tue, 19 Sep 2023 16:58:07 +0100 Subject: [PATCH] Implement Lab 6 Exercise 6 (number triangle) I spotted a neat way of doing this before I had to head off so couldn't resist --- week1.java | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/week1.java b/week1.java index 30d55e0..5fa1b63 100644 --- a/week1.java +++ b/week1.java @@ -250,6 +250,7 @@ class Lab6 extends Lab { System.out.println(String.format("%n")); new six3(); new six5(); + new six6(); } /** @@ -286,6 +287,39 @@ class Lab6 extends Lab { System.out.println(String.format("TODO / NOT IMPLEMENTED until we get stdin working")); } } + /** + * Produce a number triangle + * + * eg: + * 1 + * 2 2 + * 3 3 3 + * 4 4 4 4 + */ + class six6 extends Section { + public six6() { + super(6); + numberTriangle(8); + } + } + + /** + * @param num Size of triangle + */ + public void numberTriangle(int num) { + /* Observations: + - for even-sized triangles, preceding number of spaces starts at n=rows and decrements + - for even-sized triangles even numbers have odd spaces and vice versa + */ + int spaces = num; + for (int i = 1; i <= num; i++) { + System.out.println(" ".repeat(spaces) + + String.format("%s ", i).repeat(i) + + " ".repeat(spaces-1) + ); + spaces--; + } + } public void writeTimesTable(int num, int limit) { for (int i = 0; i < (limit + 1); i++) {