Subscribe to danzar's Blog

## My attempt at Martyr2's Mega Project ideal list. ("Numbers" section)

This is my attempt to do all of Martyr2's project list Martyr2's Mega Project ideals. My goal is to create working code for each item in the list. I will be posting a section at a time. Starting with the "Numbers" section first and continuing downwards till the end. (however long that might take)

What I am hoping is to learn a lot in the process and also receive feedback from forum members on my code. Such as improvements to the code, better coding techniques, and just an over all better understanding of programming. So if you read this blog and see something that you think could help me in some way, PLEASE say it.

On to the "Text" section now.

(Update to this first blog. I think I am not going to wait to post each section. Instead post for each ideal. This way I feel I can explain what I am thinking in the code better.)

Dan

P.S. This is my very first blog anywhere and the very first time I have posted any of the code for the public to see.

"Find PI to the Nth Digit"
``` private void Cal_PI(object sender, RoutedEventArgs e)
{
try
{
//  if (Convert.ToInt32(nth_place_tx.Text) != 0)
MessageBox.Show("The Pi value is " + Process(Convert.ToInt32(nth_place_tx.Text)));
}
catch
{
}
}

public static string Process(int digits)
{
StringBuilder result = new StringBuilder();

result.Append("3.");

DateTime StartTime = DateTime.Now;

if (digits > 0)
{

for (int i = 0; i < digits; i += 9)
{
String ds = CalculatePiDigits(i + 1);
int digitCount = Math.Min(digits - i, 9);

if (ds.Length < 9)
ds = string.Format("{0:D9}", int.Parse(ds));

result.Append(ds.Substring(0, digitCount));
}
}

return result.ToString();
}

```

"Fibonacci Sequence"

```  private void genfib_bt_Click(object sender, RoutedEventArgs e)
{
try
{
MessageBox.Show("The sequence to that point is " + gen_Fib(Convert.ToInt32(fibinput_tx.Text)));
}
catch
{

}

}
private static string gen_Fib(int length)
{
int a = 0;
int b = 1;
int fib = 0;
for (int i = 0; i < length; i++)
{
fib = a + b;
b = a;
a = fib;
}
return Convert.ToString(fib);
}

```

"Prime Factorization"
```   private void genPrime_bt_Click(object sender, RoutedEventArgs e)
{

try
{
MessageBox.Show("These are all the Prime numbers " + FindPrime(Convert.ToInt32(prim_tx.Text)));
}
catch
{
}
}
private static string FindPrime(int length)
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < length; i++)
{
if (IsPrime(i))
{ sb.Append(i + ", "); }
}
return sb.ToString();
}
public static bool IsPrime(int candidate)
{
// Test whether the parameter is a prime number.
if ((candidate & 1) == 0)
{
if (candidate == 2)
{
return true;
}
else
{
return false;
}

}
for (int i = 3; (i * i) <= candidate; i += 2)
{
if ((candidate % i) == 0)
{
return false;
}
}
return candidate != 1;
}

```

"Next Prime Number"

```  private void listprime_bt_Click(object sender, RoutedEventArgs e)
{
int primNumber = 2;
try
{
while (MessageBox.Show("Keep going with the Prime numbers? " + Convert.ToString(primNumber), "Prime listing", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
{
primNumber = nextPrime(primNumber);

}
}
catch
{
}
}
private static int nextPrime(int lastprime)
{
for (int i = lastprime + 1; i < Int32.MaxValue; i++)
{
if (IsPrime(i))
{
return i;
}
}
return 0;

}

```

"Find Cost of Tile to Cover W x H Floor"

```  private void calTileCost_bt_Click(object sender, RoutedEventArgs e)
{
try
{
tileTotalCost_lb.Content = "= " + Convert.ToString(Convert.ToInt32(tileWidth_tx.Text) * Convert.ToInt32(tileHeight_tx.Text) * Convert.ToDecimal(tilePer_tx.Text));
}
catch
{
}
}

```

"Mortgage Calculator"

```private void cal_Morgtage_Click(object sender, RoutedEventArgs e)
{
try
{
double rate = Convert.ToDouble(morgFixedRate_tx.Text);
int years = Convert.ToInt32(morgYears_tx.Text);
double i = (rate / 100) / 12;
double n = -years * 12;
double L = loanamount;
decimal results = Convert.ToDecimal(L * (i / (1 - Math.Pow((1 + i), n))));
morgMonthlyPayment_tx.Text = Convert.ToString(results);
}
catch
{
}

}

```

"Change Return Program"

``` private void cal_Change_bt_Click(object sender, RoutedEventArgs e)
{
int cost = Convert.ToInt32(100 * decimal.Parse(returnchangeCost_tx.Text));
int recieved = Convert.ToInt32(100 * decimal.Parse(returnchangeRecieved_tx.Text));
int change = recieved - cost;
int remander;
StringBuilder sb = new StringBuilder();
sb.Append("Your Change is " + Convert.ToString((Convert.ToDecimal(change) / 100)) + " : ");
if (change > 100)
{
int dollars = Math.DivRem(change, 100, out remander); change = remander;
sb.Append(" Dollars = " + dollars);
}
if (change > 25)
{
int quarters = Math.DivRem(change, 25, out remander); change = remander;
sb.Append(" Quarter = " + quarters);
}
if (change > 10)
{
int dimes = Math.DivRem(change, 10, out remander); change = remander;
sb.Append(" Dimes = " + dimes);
}
if (change > 5)
{
int nickels = Math.DivRem(change, 5, out remander); change = remander;
sb.Append(" Nickels = " + nickels);
}
if (change > 0)
{
int pennys = change;
sb.Append(" Pennys = " + pennys);
}
MessageBox.Show(" " + sb.ToString());

}

```

"Binary to Decimal and Back Converter "

```  private void bd_Convert_bt_Click(object sender, RoutedEventArgs e)
{
try
{
int number;
if (int.TryParse(bd_decimal_tx.Text, out number))
{
bd_Binary_tx.Text = convertToBinary(number).ToString();
}
else
{
bd_decimal_tx.Text = convertToDecimal(bd_Binary_tx.Text).ToString();
}

}
catch
{

}

}
private static string convertToDecimal(string binary)
{
return Convert.ToInt64(binary, 2).ToString();
}
private static string convertToBinary(int number)
{
int rem = 0;
string results = string.Empty;
while (number > 0)
{
rem = number % 2;
number = number / 2;
results = rem.ToString() + results;
}
return results;
}

```

"Calculator"

``` int cal_sum = 0;
string trigger_call = null;
private void cal_Add_bt_Click(object sender, RoutedEventArgs e)
{
{
}

}

private void cal_Sub_bt_Click(object sender, RoutedEventArgs e)
{
int sub = 0;
if (int.TryParse(cal_results_tx.Text, out sub))
{
trigger(trigger_call, sub);
trigger_call = "Sub";
}

}

private void cal_Mul_bt_Click(object sender, RoutedEventArgs e)
{
int mul = 0;
if (int.TryParse(cal_results_tx.Text, out mul))
{
trigger(trigger_call, mul);
trigger_call = "Mul";
}

}

private void cal_Div_bt_Click(object sender, RoutedEventArgs e)
{
int div = 0;
if (int.TryParse(cal_results_tx.Text, out div))
{
trigger(trigger_call, div);
trigger_call = "Div";
}

}

private void cal_Clear_bt_Click(object sender, RoutedEventArgs e)
{
cal_results_tx.Text = "";
cal_sum = 0;
trigger_call = "";

}

private void cal_Equals_bt_Click(object sender, RoutedEventArgs e)
{
int equ = 0;
if (int.TryParse(cal_results_tx.Text, out equ))
{
trigger(trigger_call, equ);
trigger_call = "";
}
cal_results_tx.Text = cal_sum.ToString();
}
private void trigger(string trig, int input)
{
switch (trig)
{
cal_sum = cal_sum + input;
cal_results_tx.Text = cal_sum.ToString();
break;
case "Sub":
cal_sum = cal_sum - input;
cal_results_tx.Text = cal_sum.ToString();
break;
case "Mul":
cal_sum = cal_sum * input;
cal_results_tx.Text = cal_sum.ToString();
break;
case "Div":
cal_sum = cal_sum * input;
cal_results_tx.Text = cal_sum.ToString();
break;
default:
cal_sum = input;
break;
}
}

```

"Unit Converter" (only did the Temp & Currency)

```   #region Temp convertion
private void temp_convert_bt_Click(object sender, RoutedEventArgs e)
{
int input = 0;
if (int.TryParse(temp_Fah_tx.Text, out input))
{
temp_Cel_tx.Text = Convert.ToString((5 * (input - 32)) / 9);
temp_Fah_tx.Text = "";
}
else if (int.TryParse(temp_Cel_tx.Text, out input))
{
temp_Fah_tx.Text = Convert.ToString(((input * 9) / 5) + 32);
temp_Cel_tx.Text = "";
}
else
{
}
}
#endregion
#region Currency
private void currConvert_bt_Click(object sender, RoutedEventArgs e)
{
decimal input = 0;
if (decimal.TryParse(currConvertDollar_tx.Text, out input))
{
decimal euroRate = Convert.ToDecimal(.77);
currConvertEuro_tx.Text = Convert.ToString(input * euroRate);
currConvertDollar_tx.Text = "";
}
else if (decimal.TryParse(currConvertEuro_tx.Text, out input))
{
decimal usRate = Convert.ToDecimal(1.28);
currConvertDollar_tx.Text = Convert.ToString(input * usRate);
currConvertEuro_tx.Text = "";
}
else
{
}
}
#endregion

```

"Alarm Clock "

``` DispatcherTimer dispatcherTimer = new DispatcherTimer();

private void alarmtimerStart_bt_Click(object sender, RoutedEventArgs e)
{
int hour = 0;
int minute = 0;
DateTime nowTime = new DateTime();
string format = "HH";

if (alarmtimerAlarm_rb.IsChecked == true)
{
// start alarm

dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Alarm_Tick);
dispatcherTimer.Interval = TimeSpan.FromSeconds(60);
dispatcherTimer.Start();

}
if (alarmtimerTimer_rb.IsChecked == true)
{
//start timer
hour = int.Parse(alarmtimerHourTimer_cb.SelectedItem.ToString());
minute = int.Parse(alarmtimerMinuteTimer_cb.SelectedItem.ToString());
int _timer = (hour * 60) + minute;
dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);
dispatcherTimer.Interval = TimeSpan.FromMinutes(_timer);
dispatcherTimer.Start();

}

}

private void dispatcherTimer_Alarm_Tick(object sender, EventArgs e)
{
int hour = int.Parse(alarmtimerHourAlarm_cb.SelectedItem.ToString());
int minute = int.Parse(alarmtimerMinuteAlarm_cb.SelectedItem.ToString());
DateTime nowTime = DateTime.Now;
int nowhour = int.Parse(nowTime.ToString("hh"));
int nowminute = int.Parse(nowTime.ToString("mm"));
if (hour == nowhour && minute == nowminute)
{
Console.Beep();//play sound
MessageBox.Show("Beep");
}

}
private void dispatcherTimer_Tick(object sender, EventArgs e)
{
MessageBox.Show("Beep");
Console.Beep();//play sound.
}

private void alarmtimerStop_bt_Click(object sender, RoutedEventArgs e)
{
dispatcherTimer.Stop();
}

```

"Distance Between Two Cities"

``` private double distance(double lat_a, double lon_a, double lat_b, double lon_b)
{
double theta = lon_a - lon_b;

dist = Math.Acos(dist);
dist = toDeg(dist);
dist = dist * 60 * 1.1515;
return dist;
}
{ return deg * (Math.PI / 180); }
{ return rad * 180 / Math.PI; }
{ return (toDeg(rad) + 360) % 360; }

private static Dictionary<string, cityCords> getCityList()
{
Dictionary<string, cityCords> cityDictionay = new Dictionary<string, cityCords>();
cityDictionay.Add("Little Rock,Arkansas", new cityCords { lat = "34.736009", longu = " -92.331122" });
cityDictionay.Add("Sacramento,California", new cityCords { lat = "38.555605", longu = "-121.468926" });
cityDictionay.Add("Connecticut,Hartford", new cityCords { lat = " 41.767", longu = "-72.677" });
cityDictionay.Add("Dover,Delaware", new cityCords { lat = "39.161921", longu = "-75.526755" });
cityDictionay.Add("Concord,New Hampshire", new cityCords { lat = "43.220093", longu = " -71.549127" });
cityDictionay.Add("Albary,New York", new cityCords { lat = "42.659829", longu = "-73.781339" });

return cityDictionay;
}

private void distancecity_B_cb_Selectionchanged(object sender, SelectionchangedEventArgs e)
{
if (distancecity_A_cb.SelectedItem != null && distancecity_B_cb.SelectedItem != null && distancecity_B_cb.SelectedItem != distancecity_A_cb.SelectedItem)
{
cityCords city_a = new cityCords();
cityCords city_b = new cityCords();
city_a.lat = ((cityCords)distancecity_A_cb.SelectedValue).lat;
city_a.longu = ((cityCords)distancecity_A_cb.SelectedValue).longu;
city_b.lat = ((cityCords)distancecity_B_cb.SelectedValue).lat;
city_b.longu = ((cityCords)distancecity_B_cb.SelectedValue).longu;
double dist_to = distance(Convert.ToDouble(city_a.lat),
Convert.ToDouble(city_a.longu),
Convert.ToDouble(city_b.lat),
Convert.ToDouble(city_b.longu));
if ((string)((ComboBoxItem)distancecity_MK_cb.SelectedValue).Content == "Miles")
{ distancecityOutput_lb.Content =(1.15 * dist_to).ToString();
}
else
{ distancecityOutput_lb.Content = (dist_to * 1.85).ToString(); }
}
}
public class cityCords
{
public String lat { get; set; }
public String longu { get; set; }
}

```

"Credit Card Validator"

``` private void ccvalidatorNumberInput_tb_TextChanged(object sender, TextChangedEventArgs e)
{
if (ccValidator(ccvalidatorNumberInput_tb.Text))
{
ccvalidatorCheckOuput_lb.Content = "Valid";
}
else
{
ccvalidatorCheckOuput_lb.Content = "INVALID";
}
}
private static bool ccValidator(string in_number)
{
long number = 0;
int counter = 0;
int sum = 0;
if (Int64.TryParse(in_number, out number))
{
byte[] digits = Digits(number);
for (int i = digits.Length - 1; i >= 0; i--)
{
if (counter % 2 != 0)
{
if ((digits[i] *= 2) > 9)
{ digits[i] -= 9; }
}
counter++;
sum += digits[i];
}
return (sum % 10 == 0);
}
else
return false;
}
public static byte[] Digits(long num)
{
int nDigits = num.ToString().Length;
byte[] digits = new byte[nDigits];
int index = nDigits - 1;
while (num > 0)
{
byte digit = (byte)(num % 10);
digits[index] = digit;
num = num / 10;
index = index - 1;
}
return digits;
}

```

"Tax Calculator"

```   private void taxcost_bt_Click(object sender, RoutedEventArgs e)
{
int cost = 0;
double tax = 0;
if (int.TryParse(taxcostCost_tb.Text, out cost) && double.TryParse(taxcostTax_tb.Text, out tax))
{
taxcostTotal_lb.Content = (cost + (cost * (tax * 0.01))).ToString();
}
}

```

"Dijkstra’s Algorithm" (used someone's example for this)

```   private IDictionary<int, int>[] childNodes;

public void Graph(IDictionary<int, int>[] childNodes)
{
this.childNodes = childNodes;
}

public int NodesCount
{
get { return childNodes.Length; }
}

public void FindShortestPaths(int startNode)
{
int[] distances = new int[childNodes.Length];
int[] previous = new int[childNodes.Length];
HashSet<int> nodes = new HashSet<int>();

for (int i = 0; i < childNodes.Length; i++)
{
previous[i] = int.MinValue;
if (i != startNode)
{
distances[i] = int.MaxValue;
}
else
{
distances[i] = 0;
}
}

distances = CalculatePaths(nodes, distances, previous);

for (int i = 0; i < distances.Length; i++)
{
Console.WriteLine("{0} - {1}", i, distances[i]);
}
}

private int[] CalculatePaths(HashSet<int> nodes, int[] distances, int[] previous)
{
while (nodes.Count > 0)
{
int node = GetNextNode(distances, nodes);
if (node == int.MaxValue)
{
break;
}

nodes.Remove(node);

foreach (var child in childNodes[node])
{
if (nodes.Contains(child.Key))
{
int newDistance = distances[node] + child.Value;
if (newDistance < distances[child.Key])
{
distances[child.Key] = newDistance;
previous[child.Key] = node;
}
}
}
}

return distances;
}

private int GetNextNode(int[] distances, HashSet<int> nodes)
{
int min = int.MaxValue;
int next = int.MaxValue;

foreach (var node in nodes)
{
if (distances[node] < min)
{
min = distances[node];
next = node;
}
}

return next;
}

```

### 0 Comments On This Entry

There are no Trackbacks for this entry

S M T W T F S
123
45678910
11121314151617
181920212223 24
25262728293031

### 0 user(s) viewing

0 Guests
0 member(s)
0 anonymous member(s)