DEV Community

tommy-3
tommy-3

Posted on

Learning Algorithms with JS, Python and Java 9: Printing Steps

This series of articles follows Stephen Grider's Udemy course in three different languages. JavaScript solutions are by Stephen. I try to "translate" them into Python and Java.

Today's question is meant to be an introduction to recursions.

--- Directions
Write a function that accepts a positive number N.
The function should console log a step shape
with N levels using the # character. Make sure the
step has spaces on the right hand side!
--- Examples
steps(2)
'# '
'##'
steps(3)
'#  '
'## '
'###'
steps(4)
'#   '
'##  '
'### '
'####'

1: Iterative Solution

JavaScript:

function steps(n) {
    for (let row = 0; row < n; row++) {
        let stair = '';
        for (let column = 0; column < n; column++) {
            if (column <= row) {
                stair += '#';
            } else {
                stair += ' ';
            }
        }
        console.log(stair);
    }
}

Python:

def steps(n):
    for row in range(n):
        stair = ''
        for column in range(n):
            if column <= row:
                stair += '#'
            else:
                stair += ' '
        print(stair)

Java:

static void steps(int n) {
    for (int row = 0; row < n; row++) {
        StringBuilder stair = new StringBuilder();
        for (int column = 0; column < n; column++) {
            if (column <= row) {
                stair.append("#");
            } else {
                stair.append(" ");
            }
        }
        System.out.println(stair);
    }
}

2: Recursive Solution

JavaScript:

function steps(n, row = 0, stair = '') {
    if (n === row) {
        return;
    }

    if (n === stair.length) {
        console.log(stair);
        return steps(n, row + 1);
    }

    stair += stair.length <= row ? '#' : ' ';
    steps(n, row, stair);
}

Python:

def steps(n, row=0, stair=''):
    if n == row:
        return

    if n == len(stair):
        print(stair)
        return steps(n, row+1)

    stair += '#' if len(stair) <= row else ' '
    steps(n, row, stair)

Java:

static void steps(int n) {
    steps(n, 0, new StringBuilder());
}

static void steps(int n, int row, StringBuilder stair) {
    if (n == row) {
        return;
    }

    if (n == stair.length()) {
        System.out.println(stair);
        steps(n, row + 1, new StringBuilder());
        return;
    }

    stair.append(stair.length() <= row ? "#" : " ");
    steps(n, row, stair);
}

Top comments (9)

Collapse
 
jastbytes profile image
Jan Steffen • Edited

This is what I came up with in C#. Sure there are many possible soultions. :)

Iterative Solution

static void Steps(int n)
{
    var step = new char[n];
    Array.Fill(step, ' ');

    for (var i = 0; i < n; i++)
    {
        step[i] = '#';
        Console.WriteLine(step);
    }
}

Recursive Solution

static void Steps(int n, int i = 0, char[] step = null)
{
    if (i == n) return;
    if (step == null)
    {
        step = new char[n];
        Array.Fill(step, ' ');
    }

    step[i] = '#';
    Console.WriteLine(step);

    Steps(n, ++i, step);
}
Collapse
 
tommy3 profile image
tommy-3

Thank you for your comment. I've never learned any C-family language and I thought they were much different from the languages I know, but the code actually looks quite familiar to me.

Collapse
 
jastbytes profile image
Jan Steffen

I think C# is more similar to modern languages than C++. The syntax of C++ gives me creep's every time. ;-)

Collapse
 
tetri profile image
Tetri Mesquita

I really appreciate the Python code. It's fantastic.
I practice coding in CodeWars and over there the ninja coders quickly post a code for this problem in 2 lines or just over 30 characters.

Collapse
 
tommy3 profile image
tommy-3 • Edited

I, too, like Python the best, though I'm sure I'm yet to learn to write in a more Pythonic way!

Collapse
 
arminaskatilius profile image
Arminas Katilius • Edited

Actually for these kind of tasks, you could mostly used same code as for Java as in Javascript :) Not complaining, but there are a lot of outdated examples on the internet.
For example, there is no need to use String builder, string concetanation works fine. Also Java has ternary operator. And if you would use Java 10, it has var keyword that allows almost copy Javascript sample you were using.

Collapse
 
tommy3 profile image
tommy-3

Thanks for the comment.

I know I can do without StringBuilders, but I make it a rule to use them for performance.

Using the iterative Java code above, it took 14 seconds when the parameter is 10000.

With this code:

static void stepsWithoutStringBuilder(int n) {
    for (int row = 0; row < n; row++) {
        String stair = "";
        for (int column = 0; column < n; column++) {
            if (column <= row) {
                stair += "#";
            } else {
                stair += " ";
            }
        }
        System.out.println(stair);
    }
}

it took 243 seconds for 10,000 steps!

I've always used Java 8 and I like Java for its strong typing, so I'm surprised to learn about the "var" in Java 10. I'm not sure if I'll like it or not, but anyway thank you for the information!

Collapse
 
vdedodev profile image
Vincent Dedo • Edited

Or better python

def steps(n):
for x in range(1, n+1):
print "{}{}".format('#' * x, ' ' * (n-x))

Edit: how do you format code on here?

Collapse
 
tommy3 profile image
tommy-3 • Edited

Ah, this is nice indeed. Thanks for your comment!

how do you format code on here?

I'm using different editors/IDEs for each language and I let them format the code.
I'm using VS Code for JS, PyCharm for Python and Eclipse for Java. I don't really have a strong reason for it.