Build Tower solution

This commit is contained in:
Leonid
2025-04-08 10:30:41 +03:00
parent 17eb02553a
commit f40b140249

View File

@@ -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;
}
}