Sudoku validator

If you’re looking for a coding job and haven’t started practicing for interview coding challenges, I’d highly recommend checking out codefights.  It’s also a good place just to have fun and keep your mind sharp.  It really is addicting.  Until now I’ve been using a site called codechef.  Codechef is great but I like the content and organization of codefights a bit better.  I don’t think I’ll share all of my solutions for codefights on here but I’d like to share a few that I really had fun with.  Here’s my solution for a sudoku validator:

bool sudoku2(char[][] grid) 
{
    string[] subgrids = new string[9];
    for(int i = 0; i < 9; i++)
    {
        string row = "";
        string column = "";
        for(int j = 0; j < 9; j++)
        {
            //Check rows
            if(grid[i][j] != '.' && row.Contains(grid[i][j]))return false;
            row = row + grid[i][j];
            //Check columns
            if(grid[j][i] != '.' && column.Contains(grid[j][i]))return false;
            column = column + grid[j][i];
            //Check subgrids
            if(i < 3 && j < 3)
            {
                if(!String.IsNullOrEmpty(subgrids[0]))
                {
                    if(grid[i][j] != '.' && subgrids[0].Contains(grid[i][j]))return false;
                }
                subgrids[0] = subgrids[0] + grid[i][j];
            }
            else if(i < 3 && 2 < j && j < 6)
            {
                if(!String.IsNullOrEmpty(subgrids[1]))
                {
                    if(grid[i][j] != '.' && subgrids[1].Contains(grid[i][j]))return false;
                }
                subgrids[1] = subgrids[1] + grid[i][j];
            }
            else if(i < 3 && j > 5)
            {
                if(!String.IsNullOrEmpty(subgrids[2]))
                {
                    if(grid[i][j] != '.' && subgrids[2].Contains(grid[i][j]))return false;
                }
                subgrids[2] = subgrids[2] + grid[i][j];
            }
            else if(2 < i && i < 6 && j < 3)
            {
                if(!String.IsNullOrEmpty(subgrids[3]))
                {                    
                    if(grid[i][j] != '.' && subgrids[3].Contains(grid[i][j]))return false;
                }
                subgrids[3] = subgrids[3] + grid[i][j];
            }
            else if(2 < i  && i< 6 && 2 < j  && j < 3)
            {
                if(!String.IsNullOrEmpty(subgrids[4]))
                {      
                    if(grid[i][j] != '.' && subgrids[4].Contains(grid[i][j]))return false;
                }
                subgrids[4] = subgrids[4] + grid[i][j];
            }
            else if(2 < i && i < 6 && j > 5)
            {
                if(!String.IsNullOrEmpty(subgrids[5]))
                {    
                    if(grid[i][j] != '.' && subgrids[5].Contains(grid[i][j]))return false;
                }
                subgrids[5] = subgrids[5] + grid[i][j];
            }
            else if(i > 5 && j < 3)
            {
                if(!String.IsNullOrEmpty(subgrids[6]))
                {    
                    if(grid[i][j] != '.' && subgrids[6].Contains(grid[i][j]))return false;
                }
                subgrids[6] = subgrids[6] + grid[i][j];
            }
            else if(i > 5 && 2 < j  && j < 6)
            {
                if(!String.IsNullOrEmpty(subgrids[7]))
                {    
                    if(grid[i][j] != '.' && subgrids[7].Contains(grid[i][j]))return false;
                }
                subgrids[7] = subgrids[7] + grid[i][j];
            }
            else if(i > 5 && j > 5)
            {
                if(!String.IsNullOrEmpty(subgrids[8]))
                {    
                    if(grid[i][j] != '.' && subgrids[8].Contains(grid[i][j]))return false;
                }
                subgrids[8] = subgrids[8] + grid[i][j];
            }
        }
    }
    
    return true;
}

If you haven’t done this on codefights you might notice that this validator allows for blank spaces.  The blank spaces are identified with periods.

In an actual game of sudoku you probably would not want to validate a puzzle until the end but something like this might be useful as a sudoku trainer.  For example you could run this function every time a player makes a move to let them know if it is a valid move or not.  The only problem with that though is that it would allow a player to make an incorrect move early on which wouldn’t be very helpful.  If I were to design a sudoku trainer, I would just check the player’s input with the completed table.  That would also be far fewer lines of code.  But I guess the purpose of these challenges are just to see if you can solve the problem, not to actually write useful code for an application.¯\_(ツ)_/¯

Back from Hiatus

I don’t normally write about what I’ve been personally doing but I thought I might take a moment to do so to explain this 3-month gap in posts.  In April I moved back from Osaka, Japan where I lived for 3 years.  Between moving internationally, getting settled, looking for jobs, and getting reacquainted with people, writing these posts has fallen by the wayside.  I’ve actually been doing a lot of coding in preparation for potential interviews so I have lots of material I’d like to share.  So stay tuned!

Also, I’ve made a few updates to Galactic Scholar!  I just need to update the app on the app store and play store.  Enjoy!

Levitating Orb

using System.Collections;
using UnityEngine;

public class Levitate : MonoBehaviour 
{
   public float amplitude;      
   public float speed;                
   private float startHeight;
   private Vector3 tempPos;
     
   void Start () 
   {
       startHeight = transform.position.y;
   }
 
   void Update () 
   {       
      tempPos = transform.position;
      tempPos.y = startHeight  + amplitude * Mathf.Sin(speed * Time.time);
      transform.position = tempPos;
   }
}

I’ve been working on a new 2.5D platformer in which I have a little witch that creates a levitating orb to light her path. This script creates the levitating effect. It is attached to the orb which is a child of the witch in the hierarchy. ‘amplitude’ controls the amplitude of the sine curve. ‘speed’ controls the speed at which the orb oscillates. ‘startHeight’ sets the Y position of the bottom of the sine curve. ‘tempPos’ holds the temporary position of the orb. For a gentle effect, in the inspector I have the amplitude set at 0.3 and the speed set at 1.5.

Binary Serialization: Creating a File

 

using UnityEngine;
using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Collections.Generic;

class PlayingCards : MonoBehaviour
{
   void Awake()
   {
      #if UNITY_IPHONE
         Environment.SetEnvironmentVariable("MONO_REFLECTION_SERIALIZER", "yes");
      #endif
   }
   void Start ()
   {
      print(Application.persistentDataPath + "/Example.dat");
      CreateFile();
   }

   void CreateFile()
   {
      BinaryFormatter bf = new BinaryFormatter ();
      FileStream file = File.Create(Application.persistentDataPath + "/Example.dat");
      Cards card = new Cards();
      bf.Serialize (file, card);
      file.Close ();
   }
}

[Serializable]
class Cards
{
   public List<string> questions = new List<string>();
   public List<string> answers = new List<string> ();
   public List<int> questionSizes = new List<int> ();
   public List<int> answerSizes = new List<int> ();
}

Probably the best two things about Unity are that it’s free and that there’s a fantastic asset store with tons of useful assets including serialization assets. There are some more economical options as well as some really beefy packages that will probably handle everything you’ll ever need to do. However, serialization is quite simple. In order to create a file, you just need 5 lines of code and a basic understanding of how it works. Here are some points to consider when implementing binary serialization:

  • As always make sure you’re using the necessary namespaces.
  • If you’re developing for iPhone, you may experience some AOT/JIT compilation issues.  If you do, include a preprocessor directive indicated on lines 11 and 13 and use Environment.SetEnvironmentVariable() with the necessary arguments.
  • If you’d like to see where the file is and if it was successfully created or not, simply print Application.PersistenDataPath to see the exact location on your computer.
  • At the moment I can’t think of a reason you’d ever want to hardcode a file name but I did so here for the sake of simplicity.
  • Whatever you are going to serialize, make sure it’s serializable as indicated on line 31.

CodeChef – Small Factorials

using System;
using System.Collections.Generic;
using System.Numerics;

public class Program
{
	public static void Main()
	{
		int dataSize = int.Parse(Console.ReadLine());
		List<BigInteger> data = new List<BigInteger>();
		
		for(int i = 0; i < dataSize; i++)
		{
			data.Add(BigInteger.Parse(Console.ReadLine()));
		}
		
		foreach(BigInteger n in data)
		{
			Console.WriteLine(CalculateFactorial(n));
		}
	}

	public static BigInteger CalculateFactorial(BigInteger n)
	{
		if(n > 1)
		{
			n = n * CalculateFactorial(n-1);
			return n;
		}
		else
		{
			return n;
		}
	}
}

So here’s a proper factorial calculator as opposed to the previous post entitled ‘Factorials.’ This code actually calculates the factorial of a number. I have to admit though that this code was not accepted by CodeChef because there is a compiling error due to the fact that CodeChef uses an older version of .Net in which the namespace Numerics does not exist. You can do this with doubles fine but the judge on CodeChef doesn’t accept scientific notation. And if you convert the scientific notation with format specifiers, the number still gets rounded up too much. Apparently there is a way to do this problem without Numerics and the BigInteger data type but I’m pretty satisfied with my solution regardless.

Here’s a link to the problem.

CodeChef – Factorial

using System;
					
public class Program
{
	public static void Main()
	{
		int dataSize = int.Parse(Console.ReadLine());
		double[] data = new double[dataSize];
		
		for(int i = 0; i < dataSize; i++)
		{
			data[i] = double.Parse(Console.ReadLine());
		}
		
		for(int i = 0; i < dataSize; i++)
		{
			Console.WriteLine(FindTrailingZeros(data[i]));
		}
	}
	
	public static double FindTrailingZeros(double n)
	{
		double quotient = 1;
		double sumOfQuotients = 0;
		int power = 1;
		
		while(true)
		{
			quotient = n / Math.Pow(5, power);
			quotient = Math.Truncate(quotient);
			power++;
			
			if(quotient > 0)
			{
				sumOfQuotients += quotient;
			}
			else
			{
				return sumOfQuotients;
			}
		}
	}
}

Here’s my code for the Factorial problem on CodeChef, though I think the title doesn’t really describe the problem well. You are not supposed to find the factorial of a number but rather the number of trailing zeros of the factorial. My first instinct was to find the factorial, put the numbers in a string, and iterate through the string to check for zeros. The problem with that algorithm though is that factorials are huge! And moreover, an input could be as large as 1 billion which would produce an astronomically large number. So I read the editorial for the problem and they had a little trick for finding trailing zeros of a factorial which was way more efficient.

Here’s a link to the problem.

CodeChef-Bytelandian Gold Coin

using System;
using System.Collections.Generic;

public class Program
{
   public static void Main()
   {
      uint input;
      bool b = true;

      while(b)
      {
         b = uint.TryParse(Console.ReadLine(), out input);
         if(b)
         {
            Console.WriteLine(FindBestDeal(input));
         }
      }
   }

   static Dictionary<uint, uint> cache = new Dictionary<uint, uint>();

   public static uint FindBestDeal(uint n)
   {
      if(cache.ContainsKey(n))
      {
         return cache[n];
      }

      if(n/2 + n/3 + n/4 > n)
      {
         uint sum = FindBestDeal(n/2) + FindBestDeal(n/3) + FindBestDeal(n/4);
         cache[n] = sum;
         return sum;
      }
      else
      {
         return n;
      }
   }
}

This is my final solution to the Bytelandian Gold Coin problem on CodeChef. This was my first shot at a problem of a medium level of difficulty on this site. And honestly I thought it was surprisingly simple at first but that was only because I didn’t give the problem proper considerations. I busted out some code, submitted it feeling confident and then found out my solution was incorrect. I went through a number of iterations and finally came up with this.

Here’s a description of the problem here.

I won’t go through every iteration I went through but here are a couple of key concepts required for a problem like this.

Recursion

Recursion is a concept in which an algorithm calls itself.  In the problem, we need to take a coin, divide it by two, three, and four, and add up the quotients.  If the sum of quotients is greater, than we have to return the highest possible sum.  And in order to do that, we have to divide all of the previous quotients by two, three, and four, and up up those quotients.  For example, 24 becomes 12 +  8 + 6 which is a total of 26.  26 however is not the right answer because one of our new quotients is 12.  And 12 becomes 6 + 4 + 3 which is 13.  So the correct answer for 24 is 27.  So basically you just have use the same logic on all of the cascading quotients as you do the initial input.  Have a look at line 32 to see where the recursion begins.

Memoization

It’s weawy hawd for me to even think about this technique without giggling.  It weawy takes me back to my pwe-speech class days when I had twouble with my ‘r’ sounds.  Anyways, memoization is a technique used to optimize repeated methods.  It works by caching data and then checking that cache to determine whether or not certain data has already been computed. It seems like a good practice for recursive algorithms as it saves tons of CPU cycles.  And in this problem on CodeChef, you need to implement memoization in order to stay under the time limit.  You can look at the memoization parts of this program on lines 21, 25-28, and 33.

The uint Data Type

There really isn’t much to this but because the problem potentially requires integers larger than a regular int can store, you need something with a larger boundary like a uint.  Though if you test this program with 1000000000 you still get very close to the maximum integer a uint can store.

CodeChef-Ciel and A-B

using System;

public class Program
{
  public static void Main()
  {
    string line = Console.ReadLine();
    string[] splitLines = line.Split(' ');
    string answerText;

    int a = int.Parse(splitLines[0]);
    int b = int.Parse(splitLines[1]);
    int answerNumber = a - b;

    answerText = answerNumber.ToString();

    char[] answerChar = answerText.ToCharArray();

    int[] answerArr = new int[answerChar.Length];
    int length = answerArr.Length;

    for(int i = 0; i < length; i++) 
    { 
      answerArr[i] = (int)Char.GetNumericValue(answerChar[i]); 
    } 

    if(answerArr[length - 1] >= 5)
    {
      answerArr[length -1] -= 1;
    }
    else
    {
      answerArr[length - 1] += 1;
    }

    foreach(int num in answerArr)
    {
      Console.Write(num);
    }
  }
}

So here’s another solution to a CodeChef problem. The problem is to take two user-generated integers on the same line(‘A’ and ‘B’), find the difference, and then make the answer incorrect but changing one of it’s integers. And finally write the incorrect answer to the console. The OCD part of my brain was not a huge fan of writing an algorithm to produce an incorrect answer to a simple math problem but I think it was overall a good exercise for the basics.

Here’s a link to the problem.

CodeChef-Enormous Input Test

using System;

public class Program
{
   public static void Main()
   {
      string lines = Console.ReadLine();
      string[] splitLines = lines.Split(' ');

      int n = int.Parse(splitLines[0]);
      int k = int.Parse(splitLines[1]);
      int[] t = new int[n];
      int output = 0;

      for(int i = 0; i < n; i++)
      {
         t[i] = int.Parse(Console.ReadLine());
      }

      foreach(int i in t)
      {
         if(i % k == 0)
         {
            output++;
         }
      }

      Console.WriteLine(output);
   }
}

I’m now officially addicted to CodeChef. These problems are so much fun. This is my solution to another beginner problem. In this one, the user inputs two integers separated by a space(hints the split with a ‘ ‘ on line 8). The first integer is ‘n’ and it indicates how many numbers are going to be tested. The second integer is ‘k’ and this is going to be used to find out if each subsequent integer is a multiple of ‘k’.

Here’s a link to the problem.

CodeChef-ATM

using System;

public class Test
{
   public static void Main()
   {
      string line = Console.ReadLine();
      string[] splitLines = line.Split(' ');

      double withdrawal = double.Parse(splitLines[0]);
      double balance = double.Parse(splitLines[1]);

      if(withdrawal % 5 == 0 && balance >= withdrawal + 0.5)
      {
         double updatedBalance = balance - withdrawal - 0.5;
         Console.WriteLine(updatedBalance.ToString("F"));
      }
      else
      {
         Console.WriteLine(balance.ToString("F"));
      }
   }
}

Here’s my solution to the ATM problem on CodeChef.  The user has to input a withdrawal amount and a balance amount on the same line(Why? IDK).  There is an ATM usage fee of $0.50 that must be added to the withdrawal.  The withdrawal of course cannot exceed the balance and must be a multiple of 5.  Simple may this problem be, I actually felt like I learned few things from doing it.

  1. Split() is a really nifty method for when you need to split strings.
  2. Format specifiers, in this case “F”, are really nifty for when you need to specify precision.
  3. Try not to get big-headed even when doing simple tasks.  Next thing you know, you’ll have a logical brain fart, get frustrated, and slip into an existential crisis.

Here’s the link to the problem.