BLOG
ARTICLE
If you've been coding for a while you defintely would had encountered the familar staircase problem somewhere early in your career, probably during study or work interviews 😁.
The problem dictates you to create a solution to print a shape resembling a 'staircase' to console.
1 2 3 4 5 6
# ## ### #### ##### ######
While this is a very easy problem, once you go far and accumulate years of programming experience it's easy to forget the small stuffs.
I will try to solve this problem in various programming languages that I know. I will not try to optimize the solution for now so if you have better ideas feel free to share to me!
Problem statement
- Single integer as input to function 'staircase'.
- Use spaces and # symbols as the staircase.
- The last line must have zero spaces in it.
1. JavaScript
I really like how concise the solution in modern JavaScript compared to other languages. By using repeat we could make this into one-liner.
1 2 3 4 5
function staircase(n) { for (var x = 0; x < n; x++) { console.log(' '.repeat(n-x-1) + '#'.repeat(x+1)); } }
Note: In general one-liners are harder to understand and maintain, so write them wisely.
Run the code on JSBin: LINK
2. Go
1 2 3 4 5 6 7 8 9 10 11
func staircase(n int) { for x := 0; x < n; x++ { for y := 0; y < n-x-1; y++ { fmt.Print(" ") } for y := 0; y <= x; y++ { fmt.Print("#") } fmt.Println() } }
Run the code on Go Playground: LINK
Go also has simpler solution similar to JavaScript by using a method in package 'strings': Repeat.
1 2 3 4 5
func staircase(n int) { for x := 0; x < n; x++ { fmt.Printf("%s%s\n", strings.Repeat(" ", n-x-1), strings.Repeat("#", x+1)) } }
Run the code on Go Playground: LINK
3. PHP
1 2 3 4 5 6 7 8 9 10 11
function staircase($n) { for ($x = 0; $x < $n; $x++) { for ($y = 0; $y < $n-$x-1; $y++) { print " "; } for ($y = 0; $y <= $x; $y++) { print "#"; } print "\n"; } }
Run the code on PHP Playground: LINK
4. Java
1 2 3 4 5 6 7 8 9 10 11
public static void staircase(int n) { for (int x = 0; x < n; x++) { for (int y = 0; y < n-x-1; y++) { System.out.print(" "); } for (int y = 0; y <= x; y++) { System.out.print("#"); } System.out.println(); } }
Run the code on Code Labstack: LINK
5. Python
I might add Python once I get better at it 🐍.
Hi, I'm Jerfareza
Daviano 👋🏼
Hi, I'm Jerfareza Daviano 👋🏼
I'm a Full Stack Developer from Indonesia currently based in Japan.
Passionate in software development, I write my thoughts and experiments into this personal blog.