MYSQL-Solution-procedure-with-two-variables

Hackerrank – Draw the Triangle 2 – SQL – Solution

Publish Date - November 26th, 2022

|

Last Modified - March 7th, 2023

A slightly more difficult solution, Hackerrank draws on it’s previous question in of Draw the Triangle 1, with Draw the Triangle 2. Let’s jump into it.

The problem

P(R) represents a pattern drawn by Julia in R rows. The following pattern represents P(5):

* 
* * 
* * * 
* * * * 
* * * * *

Write a query to print the pattern P(20).

The solution

Firstly I tried to draw on my code from the previous problem since it’s a similar layout question (just a reversed order). However, that didn’t work. That being said you can take the same approach that I did in Draw the Triangle solution 1 and create a procedure.

Remember, this is what you’re trying to achieve:

* 
* * 
* * * 
* * * * 
* * * * * 
* * * * * * 
* * * * * * * 
* * * * * * * * 
* * * * * * * * * 
* * * * * * * * * * 
* * * * * * * * * * * 
* * * * * * * * * * * * 
* * * * * * * * * * * * * 
* * * * * * * * * * * * * * 
* * * * * * * * * * * * * * * 
* * * * * * * * * * * * * * * * 
* * * * * * * * * * * * * * * * * 
* * * * * * * * * * * * * * * * * * 
* * * * * * * * * * * * * * * * * * * 
* * * * * * * * * * * * * * * * * * * * 

Basically a 90 degree triangle with 20 rows of stars (ascending). Where the code deviates from the first triangle challenge is the way that you approach looping through the stars and printing out the strings. There are two subtle differences this challenge and the previous challenge (with the code I used to solve it).

  1. You’ll need to use two sets of variables (one input for the rows and another to count all of the rows), in my answer I used “r int” and “counter int”.
  2. Make sure that your logic is “Counted <= r” as you want WHILE loop to only last as long as the value of r (which is your procedure input).
-- For an N amount of rows (with an input) 
-- print the ascending amount of stars. 


DELIMITER $$

CREATE PROCEDURE stars(r INT) -- procedure stars() with r as an int
BEGIN
    DECLARE counted INT DEFAULT 1; -- counted as a variable
    WHILE counted <= r DO -- loop as long as counted is <= r
        SELECT REPEAT('* ', counted); -- print out * per amount counted
        SET counted = counted + 1; -- increment +1 for each counted row        
    END WHILE;
END $$
    
CALL stars(20); -- call procedure with the value 20

Conclusion

This question was pretty easy and straightforward to complete, since I had already completed the previous question. Ultimately, it was a very similar question – with only minor modifications needed.

Feel free to check out my articles on related technologies:

Leave a Comment

Your email address will not be published. Required fields are marked *