Problem Statement
A description of the problem can be found on Hackerrank.
Solution
Create n
times a line consting of spaces (' '
) and hashes ('#'
). Each line contains incremented count of hashes and decremented count of spaces form 1
to n
, respectively n
downto 1
.
I created solution in 4 languages:
All solutions are also available on my GitHub.
Scala
1 2 3 4 5 6 7 8 9 |
object Staircase extends App { val n = io.Source.stdin.bufferedReader().readLine().toInt Range(1, n + 1).foreach { i => println(stair(i, n)) } def stair(i: Int, n: Int) = " " * (n - i) + "#" * i } |
Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
import java.util.*; public class Staircase { public static void main(String[] args) { Scanner stdin = new Scanner(System.in); int height = Integer.parseInt(stdin.nextLine()); for(int i = 0; i < height; i++) { for(int j = 0; j < height; j++) { if(height - i - 2 < j) { System.out.print("#"); } else { System.out.print(" "); } } System.out.println(); } stdin.close(); } } |
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
function processData(input) { var n = parseInt(input); for(var i = 0; i < n; i++) { var s = ""; for(var j = 0; j < n; j++) { if(n - i - 2 < j) { s += "#"; } else { s += " "; } } console.log(s); } } process.stdin.resume(); process.stdin.setEncoding("ascii"); _input = ""; process.stdin.on("data", function (input) { _input += input; }); process.stdin.on("end", function () { processData(_input); }); |
Ruby
1 2 3 4 5 6 7 8 9 |
def stair(spaces, hashes) " " * spaces + "#" * hashes end n = gets.to_i for i in 1..n do puts stair(n - i, i) end |