Rendez-vous with cassidoo #200, interview question of the week

cassidoo sql puzzle

I've recently discovered Cassidy's newsletter, more precisely this one and really liked it:

  • it's short
  • it's fun
  • and there is a fun interview question

I admit I haven't read the linked articles :-)

This week’s question:

Given a direction and a number of columns, write a function that outputs an arrow of asterisks (see the pattern in the examples below)!

Example:

$ printArrow('right', 3)
Output:
*
 *
  *
 *
*

$ printArrow('left', 5)
Output:
    *
   *
  *
 *
*
 *
  *
   *
    *

My solution

I've decided to do it in SQL (PostgreSQL flavour) because these times it's the language I have the most fun with for these little puzzles.

My solution is based on 2 main ideas:

  • generate_series to generate the lines (it's kind of obvious if you're used to do these puzzles in SQL)
  • it looks like an abs function plot
CREATE OR REPLACE FUNCTION public.print_arrow(
        direction text, 
        columnnumber integer)
 RETURNS text
 LANGUAGE sql
 IMMUTABLE
AS $function$
  select 
    -- we repeat a space s times, add a * at the end 
    -- and separate lines with \n
    -- nothing surprising...
    string_agg(repeat(' ', s) || '*', E'\n')
  from (
    -- here is the number of space computation
    select
      case
        when direction = 'right' then 
            columnnumber - abs(line  - columnnumber) - 1
        when direction = 'left' then 
            abs(line - columnnumber)
        else /*uh oh!*/ 0
      end as s
    from 
      -- generate numbers from 1 to 2n-1
      generate_series(1, 2 * columnnumber - 1) line
  ) spaces;
$function$

Not very complicated, but fun to see that SQL gives us everything we need in this case.

(Photo by Dale Brooks from Pexels.)

Previous Post Next Post