Esta serie mantiene la mente fresca resolviendo, uno a uno, los ejercicios de HackerRank. Cada entrada toma un tema concreto y lo agota; todas las consultas están en MySQL salvo donde se indique.
Te invito a intentar cada ejercicio antes de leer la solución.
Aquí SQL deja de parecer SQL. Estos ejercicios usan variables y bucles, y los de triángulos están resueltos en SQL Server.
Triangle
Draw The Triangle 1
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).
Solución
En este caso usaremos Sql Server para poder resolver esto de forma mas cómoda, aparte que también me toco aprender sobre esto. En este caso es solamente verlo como si lo hubiéramos solucionado en algún lenguaje de programación como python, por ejemplo, para declarar una variable podemos usar DECLARE @i INT y ahora sabemos que @i es una variable de tipo INT la cual vale 20, nosotros queremos que imprimía inicialmente los 20 asteriscos y se reduzca -1 (n-1) asterisco cada vez que hace un recorrido hasta llegar a 0 donde acaba el bucle.
SET NOCOUNT ON;
DECLARE @i INT = 20;
WHILE @i > 0
BEGIN
PRINT REPLICATE('* ', @i);
SET @i = @i - 1;
END
goDraw The Triangle 2
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).
Solución
Esto seria lo mismo pero de forma invertida.
SET NOCOUNT ON;
DECLARE @i INT = 1;
WHILE @i <= 20
BEGIN
PRINT REPLICATE('* ', @i);
SET @i = @i + 1;
END
goPrint Prime Numbers
Write a query to print all prime numbers less than or equal to 1000. Print your result on a single line, and use the ampersand (&) character as your separator (instead of a space).
For example, the output for all prime numbers ≤ 10 would be:
2&3&5&7
Solución
SET NOCOUNT ON;
DECLARE @i INT = 1000;
WHILE @i <= 1000
BEGIN
IF(@i % 2 = 0)
BEGIN
SET @Prime = @Prime + CAST(@i AS VARCHAR) + '&';
END
SET @i = @i + 1;
END
PRINT @Prime
go