Arsalan's Musings on Software

Software design and development techniques, ideas, and source code snippets…

Adding rows and columns in a square matrix (C# Solution)

leave a comment »

This is a variation to the problem/solution posted on Ali Abbas Rizvi’s blog. I wanted to allow the user to enter matrix size for each run and to get a view of a randomly generated matrix in addition to all the sums for rows and columns. I also wanted to create a design that would lend itself favorably to adding new functionality. As an example, two methods (AddAllRows and AddAllColumns) have been added to the SquareMatrix class.

// Problem: Given a matrix, add rows and columns
// Author: Ahmed Arsalan
// (c) 2008. Please cite source if used in your presentation.

using System;
using System.Linq;
using System.Text;

namespace SolvingSmallProblems
{
  class Program
  {
  static void Main(string[] args)
  {
  SquareMatrix aMatrix;
  int matrixSize;

Console.Out.WriteLine(“Please enter matrix size (e.g. 10):”);
  try
  {
  matrixSize = Int32.Parse(Console.In.ReadLine().Trim());
  }
  catch (Exception)
  {
  Console.Out.WriteLine(“Please entger a valid integer.”);
  throw new Exception(“Invalid size entered!”);
  }
  Console.Out.WriteLine(“The randomly generated matrix looks like this:”);

aMatrix = new SquareMatrix(matrixSize);

for (int underline = 0; underline < matrixSize; underline++)   {   Console.Out.Write("____");   }   aMatrix.Show(); Console.Out.WriteLine("Press ENTER to generate sums...");   Console.In.ReadLine(); // display sums   long [] rowSums = new long [matrixSize];   long [] columnSums = new long [matrixSize];   for (int rowOrColumn = 0; rowOrColumn < matrixSize; rowOrColumn++)   {   rowSums[rowOrColumn] = aMatrix.AddRow(rowOrColumn);   columnSums[rowOrColumn] = aMatrix.AddColumn(rowOrColumn); Console.Out.WriteLine (String.Format ("The sum of row {0} is {1}, " +   "and the sum of column {2} is {3}. ", rowOrColumn,   rowSums[rowOrColumn], rowOrColumn, columnSums[rowOrColumn]));   } Console.Out.WriteLine (String.Format ("The MAX of all rows is {0}, " +   "and the MAX of all columns is {1}", rowSums.Max(), columnSums.Max()));   Console.In.ReadLine();   }   } class SquareMatrix   {   # region ------------------------ Instance Variables ------------------------   private const int DEFAULT_MATRIX_SIZE = 10;   int[,] matrix;   Random randomNumber;   int selectedMatrixSize;   #endregion #region ------------------------ Constructors ------------------------   public SquareMatrix() :this(DEFAULT_MATRIX_SIZE)   {   // use default size   } public SquareMatrix(int matrixSize)   {   randomNumber = new Random(99);   selectedMatrixSize = matrixSize; matrix = new int[matrixSize, matrixSize];   for (int row = 0; row < matrixSize; row++)   {   for (int column = 0; column < matrixSize; column++)   {   try   {   matrix[row, column] = RandomNumber; // random # between 1 and 99   }   catch (Exception)   {   Console.out.WriteLine ("Error generating random number!");   throw new Exception ("Error generating random number.");   }   }   }   }   #endregion # region ------------------------ Public Properties ------------------------   public int RandomNumber   {   get   {   return randomNumber.Next(1, 99);   }   }   #endregion #region ------------------------ Public Methods ------------------------   public void Show()   {   for (int row = 0; row < selectedMatrixSize; row++); for (int column = 0; column < selectedMatrixSize; column++)   {   Console.Out.Write(matrix[row, column]);   Console.Out.Write(" ");   } Console.Out.WriteLine();   }   } public long AddRow(int rowNumber)   {   long addedRow = 0;   for (int column = 0; column < selectedMatrixSize; column++)   {   addedRow += matrix[rowNumber, column];   } return addedRow; } public long AddColumn(int columnNumber)   {   long addedColumn = 0;   for (int row = 0; row < selectedMatrixSize; row++)   {   addedColumn += matrix[row, columnNumber];   } return addedColumn; } public long AddAllRows()   {   long addedAllRows = 0;   for (int row = 0; row < selectedMatrixSize; row++)   {   addedAllRows += AddRow(row);   }   return addedAllRows;   } public long AddAllColumns()   {   long addedAllColumns = 0;   for (int column = 0; column < selectedMatrixSize; column++)   {   addedAllColumns += AddColumn(column);   }   return addedAllColumns;   }   #endregion } } [/sourcecode]

Written by Arsalan A.

January 8, 2008 at 1:36 am

Posted in 1

WordPress makes posting source code to your blog easy

with one comment

When I decided to start a blog to post source code for small projects, I needed a blogging platform that would make posting source code with keyword highlights, line numbers, and proper indentation a snap. After a bit of search and general disappointment with blogging systems, I came across the wonderful feature in WordPress that let’s you post beautifully styled source code simply by enclosing the code inside the SourceCode tag! And that was all I had to do! Brilliant!

The only caveat I found so far is that the view seems fixed in width. So you have to choose a theme that gives you more space in the main text area. If a line in your code is longer than what the template allows, you will get a horizontal scroll bar. However, if you scroll right to see the overflowing code, you will notice that the alternating background color scheme does not apply there. Clearly a bug and a big disappointment. I hope some body at WordPress sees this post and removes that defect. This is still the best and easiest way to date to showcase your source code in a blog.

Here is the FAQ for WordPress.

Happy coding!

Written by Arsalan A.

January 6, 2008 at 3:31 pm

Posted in 1

Time Math Interview Problem (C# Solution)

with 4 comments

This is a solution for the problem posted by Ali Abbas Rizvi here. Command line arguments are method name (e.g. AddMinutes), start time (e.g. 9:24AM), and minutes to add (e.g. 18). The result will be the new time after addminutes in the same time format.

using System;
using System.Text.RegularExpressions;
using System.Collections.Specialized;

namespace SolvingSmallProblems
{
class Program
{
static void Main(string[] args)
{
TimeConversions timeConv = new TimeConversions();

string commandName;
string baseTime;
string incrementalTime;
string output;
if (args.GetLength(0) == 3)
{
commandName = args[0];
baseTime = args[1];
incrementalTime = args[2];

switch (commandName.ToUpper())
{

case (“ADDMINUTES”):
output = timeConv.AddMinutes(baseTime, Int32.Parse(incrementalTime));
Console.Out.WriteLine(output);
Console.Out.Flush();
break;
}
}
else
{
throw new Exception(“Incorrect number of arguments: 2 expected…”);
}

}

}

class TimeConversions
{
private StringCollection meridiemValidValues;
public StringCollection methodsAvailable;

public TimeConversions()
{
meridiemValidValues = new StringCollection();
meridiemValidValues.Add(“AM”);
meridiemValidValues.Add(“PM”);

methodsAvailable = new StringCollection();
methodsAvailable.Add(“AddMinutes”);
}

public string AddMinutes(string time, int minutesToAdd)
{
long convertedTime = ConvertTimeToMinutes(time);
string finalTime = ConvertMinutesToTime(convertedTime + minutesToAdd);
return finalTime;
}

private string ConvertMinutesToTime(long minutes)
{
long calculatingHours;
long calculatingMinutes;
string calculatingMeridiem;

calculatingMinutes = minutes % 60;
// Rolling over hours for a 24-hour clock
calculatingHours = (minutes / 60) % 24;

if (calculatingHours < 12) { calculatingMeridiem = "AM"; // 0 am should be written as 12 am if (calculatingHours == 0) { calculatingHours = 12; } } else { calculatingMeridiem = "PM"; calculatingHours -= 12; } return calculatingHours.ToString() + ":" + calculatingMinutes.ToString().PadLeft(2, '0') + " " + calculatingMeridiem; } private long ConvertTimeToMinutes(string time) { long normalizedTime; string regexStringForTimeConversion = @"^(?[\d]{1,2}):(?\d\d)[\s]?(?[AP]M)$”;
Regex regexForTimeConversion = new Regex(regexStringForTimeConversion);

Match matchedTime = regexForTimeConversion.Match(time);
int hours, minutes;
string meridiem;
try
{
hours = Int32.Parse(matchedTime.Groups[“Hours”].Value);
}
catch (Exception)
{
throw new Exception(“Invalid characters in Hours!”);
}
try
{
minutes = Int32.Parse(matchedTime.Groups[“Minutes”].Value);
}
catch (Exception)
{
throw new Exception(“Invalid characters in Minutes!”);
}
if (meridiemValidValues.Contains( matchedTime.Groups[“Meridiem”].Value))
{
meridiem = matchedTime.Groups[“Meridiem”].Value;
}
else
{
throw new Exception(“Invalid characters in Meridiem!”);
}

// Rule: 12 PM will be 12 in a 24-hour clock, 12 AM will be 0
if ((hours == 12) && (meridiem == “AM”))
{
hours = 0;
}
else if ((hours < 12) && (meridiem == "PM")) { hours += 12; } normalizedTime = (hours * 60) + minutes; return normalizedTime; } } } [/sourcecode]

Written by Arsalan A.

January 2, 2008 at 4:20 am

Posted in Code