From f40b140249dfce6957781b3304a55a58a049a487 Mon Sep 17 00:00:00 2001 From: Leonid Date: Tue, 8 Apr 2025 10:30:41 +0300 Subject: [PATCH] Build Tower solution --- .../java/com/algos/codewars/BuildTower.java | 56 +++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 src/main/java/com/algos/codewars/BuildTower.java diff --git a/src/main/java/com/algos/codewars/BuildTower.java b/src/main/java/com/algos/codewars/BuildTower.java new file mode 100644 index 0000000..f804a04 --- /dev/null +++ b/src/main/java/com/algos/codewars/BuildTower.java @@ -0,0 +1,56 @@ +package com.algos.codewars; + +//Build Tower +// +// Build a pyramid-shaped tower, as an array/list of strings, given a positive integer number of floors. A tower block is represented with "*" character. +// +// For example, a tower with 3 floors looks like this: +// +// [ +// " * ", +// " *** ", +// "*****" +// ] +// +// And a tower with 6 floors looks like this: +// +// [ +// " * ", +// " *** ", +// " ***** ", +// " ******* ", +// " ********* ", +// "***********" +// ] + + +import java.util.Arrays; + +public class BuildTower { + + public static void main(String[] args) { + + System.out.println(Arrays.toString(towerBuilder(3))); + } + + public static String[] towerBuilder(int nFloors) { + + String[] result = new String[nFloors]; + int stars = (nFloors - 1) * 2 + 1; + int spaces = 0; + + for (int i = nFloors - 1; i >= 0; i--) { + result[i] = buildFloor(stars, spaces); + stars = stars - 2; + spaces++; + } + + return result; + } + + private static String buildFloor(int stars, int spaces) { + + String spacesStr = " ".repeat(spaces); + return spacesStr + "*".repeat(stars) + spacesStr; + } +}