Arsalan's Musings on Software

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

Archive for the ‘Code’ Category

Count prime numbers in a range (C# Solution)

with 2 comments

Problem: Given a range of integers, count the number of primes. Also list the prime numbers in the range.

using System;

namespace SolvingSmallProblems
{
public class Program
{
static void Main(string[] args)
{
int defaultLowNum = 1;
int defaultHighNum = 50;
int lowNum, highNum;
PrimeNumberPuzzles prime = new PrimeNumberPuzzles();

Console.WriteLine(“PRIME NUMBER COUNT PROGRAM”);
Console.WriteLine();
Console.WriteLine(“Please enter start number”);
try
{
lowNum =
Convert.ToInt32(Console.ReadLine());
}
catch (Exception)
{
lowNum = defaultLowNum;
}

Console.WriteLine(“Please enter end number”);
try
{
highNum = Convert.ToInt32(Console.ReadLine());
}
catch (Exception)
{
highNum = defaultHighNum;
}

if (lowNum < 1) { lowNum = defaultLowNum; } if (highNum < lowNum) { highNum = defaultHighNum; } int totalPrimes = prime.CountPrimes(lowNum, highNum); Console.WriteLine(); Console.WriteLine("Total number of prime numers between " + lowNum.ToString() + " and " + highNum.ToString() + " is " + totalPrimes + "."); Console.ReadKey(); } } public class PrimeNumberPuzzles { public int CountPrimes(int low, int high) { int count = 0; for (int num = low; num <= high; num++) { if (IsPrime(num)) { Console.Write(num + " "); count++; } } return count; } bool IsPrime(int num) { bool isNumPrime = true; if ( num == 2) { return true; } else if (num == 1) { return false; } else if (num < 1) { throw new Exception("Invalid number!"); } else { int remainder; for (int test = 2; test < num - 1; test++) { remainder = num % test; if (remainder == 0) { isNumPrime = false; } } return isNumPrime; } } } }[/sourcecode]

Written by Arsalan A.

January 21, 2008 at 6:10 pm

Posted in Code

Simple zig-zag numeric spiral

leave a comment »

I propose the following problem. Take the number of columns and a series of numbers between 10 and 99 as input and create a zig-zag pattern on console output. The output should be centered so that it fills an 80 char wide screen. For example,

prompt>ZigZag 3 12 45 78 48 34 67 90 23 72 67 34 56 17 32 88

will give the following output:

12
                                                             45
                                                                                                                               78
                                                            48
34
                                                            67
                                                                                                                               90
                                                            23
72 
                                                             67 
                                                                                                                               34
                                                             56
17
                                                             32
                                                                                                                               88

———————————————————————————

I will try to write C# code to solve this problem below within a day or two.

Written by Arsalan A.

January 8, 2008 at 2:49 pm

Posted in Code

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