Speed Coding 2016 – Q1 Solution


13 July 2016, by

This post explains the solutions to Question 1 of our speed coding 2016 competition. If you haven’t yet read the question, head back and have a go now.

The quickest answer that came through to this question was from Matthew Richards. He solved the problem in 13:27 and used C#. Here’s his solution:

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Challenge1
{
  class Program
  {
    static void Main(string[] args)
    {
      Stars(5);
      Stars(6);
      Stars(7);
      Stars(8);
      Stars(50);
      Stars(77);
    }

    static void Stars(int size)
    {
      bool[,] grid = new bool[size,size];
      FillGrid(grid, 0, size);

      using (var output = new StreamWriter(new FileStream(@"c:\test\stars" + size + ".txt", FileMode.Create)))
      {
        PrintGrid(grid, output);
      }
    }

    static void FillGrid(bool[,] grid, int start, int size)
    {
      for (int i = start; i < start + size; i++)
      {
        grid[i,start] = true;
        grid[i,start + size - 1] = true;
        grid[start,i] = true;
        grid[start + size - 1,i] = true;
      }

      size = size - 4;

      if (size > 0)
      {
        FillGrid(grid, start + 2, size);
      }
    }

    static void PrintGrid(bool[,] grid, TextWriter output)
    {
      for (int x = 0; x < grid.GetLength(0); x++)
      {
        for (int y = 0; y < grid.GetLength(1); y++)
        {
          output.Write(grid[x,y] ? "*" : " ");
        }

        output.WriteLine();
      }
    }
  }
}

As you can see, his solution was to fill in squares in a recursive manner working inwards.

There were three types of solution to this problem:

  • Matthews recursive solution.
  • A recursive outwards solution (start in the center and wrap it in larger and larger squares).
  • Use the symmetry of the square to work out each coordinate in turn.

If you managed to complete this problem in under 17:39, then you would have placed in our top 5!

Tags: , , ,

Categories: Social, Softwire, Technical

«
»

Leave a Reply

* Mandatory fields


3 × = twenty one

Submit Comment