<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Bryan Simonson &#187; Programming</title>
	<atom:link href="http://www.bryansimonson.com/tags/programming/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.bryansimonson.com</link>
	<description>Trust Door AI</description>
	<lastBuildDate>Wed, 01 Sep 2010 07:26:48 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.1</generator>
		<item>
		<title>Making a Fractal in Java&#8217;s Console</title>
		<link>http://www.bryansimonson.com/2010/02/21/making-a-fractal-in-javas-console/</link>
		<comments>http://www.bryansimonson.com/2010/02/21/making-a-fractal-in-javas-console/#comments</comments>
		<pubDate>Mon, 22 Feb 2010 00:32:31 +0000</pubDate>
		<dc:creator>bryan</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[fractal]]></category>

		<guid isPermaLink="false">http://www.bryansimonson.com/?p=305</guid>
		<description><![CDATA[From, Data Structures and Other Objects Using Java, Chapter 8, Project #9, page 440: Examine this pattern of asterisks and blanks and write a recursive method that can generate exactly this pattern: * * * * * * * * * * * * * * * * * * * * * * * [...]]]></description>
			<content:encoded><![CDATA[<p>From, <a rel="nofollow" href="http://www.amazon.com/Data-Structures-Other-Objects-Using/dp/0321375254/ref=sr_1_2?ie=UTF8&#038;s=books&#038;qid=1266797057&#038;sr=1-2manticorcom-20" >Data Structures and Other Objects Using Java</a>, Chapter 8, Project #9, page 440:</p>
<p>
<blockquote>
Examine this pattern of asterisks and blanks and write a recursive method that can generate exactly this pattern:</p>
<pre>
*
* *
  *
* * * *
    *
    * *
      *
* * * * * * * *
        *
        * *
          *
        * * * *
            *
            * *
              *
</pre>
<p>With recursive thinking, the method needs only seven or eight lines of ode (including two recursive calls). How is this pattern a fractal? Your method should also be capable of producing larger or smaller patterns of the same variety. Hint: Have two parameters. One parameter indicates the indentation of the leftmost line in the pattern; the other parameter indicates the number of stars in the longest line.
</p></blockquote>
<p>WARNING: Cheating is bad, mmmmkay children? Don’t cheat.</p>
<pre class="brush: java; ">

 /*
|	Bryan Simonson
 \	CS211 - Craig Niiyama
  | 2/21/2010
*/

package bryansimonson;

public class Fractal {
	public static void main(String args[]){
		drawFractal(32,0);
	}

	public static void drawFractal(int length, int space){
		if (length==1){ // the stopping case
			for (int n=0; n&lt;space; n++) System.out.print(&quot;  &quot;);
			System.out.println(&quot;* &quot;);
		} else {		// length is a power of two
			drawFractal(length/2,space);
			for (int n=0; n&lt;space; n++) System.out.print(&quot;  &quot;);
			for (int n=0; n&lt;length; n++) System.out.print(&quot;* &quot;);
			System.out.println();
			drawFractal(length/2,length/2+space);
		}
	}
}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.bryansimonson.com/2010/02/21/making-a-fractal-in-javas-console/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Simulating a Car Wash in Java</title>
		<link>http://www.bryansimonson.com/2010/02/21/simulating-a-car-wash-in-java/</link>
		<comments>http://www.bryansimonson.com/2010/02/21/simulating-a-car-wash-in-java/#comments</comments>
		<pubDate>Mon, 22 Feb 2010 00:23:44 +0000</pubDate>
		<dc:creator>bryan</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[car wash]]></category>
		<category><![CDATA[simulation]]></category>

		<guid isPermaLink="false">http://www.bryansimonson.com/?p=303</guid>
		<description><![CDATA[From, Data Structures and Other Objects Using Java, Chapter 7, Project #8, page 396: Make improvements to the car was simulation program from Section 7.2. Note: Portions of code taken from Michael Main&#8217;s version. WARNING: Cheating is bad, mmmmkay children? Don’t cheat. /* &#124; Bryan Simonson \ CS211 - Craig Niiyama &#124; 2/21/2010 */ // [...]]]></description>
			<content:encoded><![CDATA[<p>From, <a rel="nofollow" href="http://www.amazon.com/Data-Structures-Other-Objects-Using/dp/0321375254/ref=sr_1_2?ie=UTF8&#038;s=books&#038;qid=1266797057&#038;sr=1-2manticorcom-20" >Data Structures and Other Objects Using Java</a>, Chapter 7, Project #8, page 396:</p>
<p>
<blockquote>
Make improvements to the <a href="http://www.cs.colorado.edu/~main/applications/CarWash.java">car was simulation program</p>
<p> from Section 7.2.
</p></blockquote>
<p>Note: Portions of code taken from <a href="http://www.cs.colorado.edu/~main/applications/CarWash.java">Michael Main&#8217;s</a> version.</p>
<p>WARNING: Cheating is bad, mmmmkay children? Don’t cheat.</p>
<pre class="brush: java; ">

 /*
|	Bryan Simonson
 \	CS211 - Craig Niiyama
  | 2/21/2010
*/

// FILE: Carwash.java
// This program illustrates the use of the carWashSimulate method which uses
// a simple queue to simulate cars waiting at a car wash.
package bryansimonson;
import java.io.*;
import java.util.LinkedList;
import java.util.Queue;
import edu.colorado.simulations.BooleanSource;
import edu.colorado.simulations.Washer;
import edu.colorado.simulations.Averager;

/******************************************************************************
* The &lt;CODE&gt;CarWash&lt;/CODE&gt; Java application illustrates the use of
* the &lt;CODE&gt;carWashSimulate&lt;/CODE&gt; method.
* The illustration uses the following values:
*   &lt;CODE&gt;
*   &lt;br&gt;washTime = 240
*   &lt;br&gt;arrivalTime = 0.0025
*   &lt;br&gt;totalTime = 6000
*   &lt;/CODE&gt;
*
* &lt;p&gt;&lt;dt&gt;&lt;b&gt;Java Source Code for this class:&lt;/b&gt;&lt;dd&gt;
*   &lt;A HREF=&quot;../applications/CarWash.java&quot;&gt;
*   http://www.cs.colorado.edu/~main/applications/CarWash.java
*   &lt;/A&gt;
*
* @author Michael Main
*   &lt;A HREF=&quot;mailto:main@colorado.edu&quot;&gt; (main@colorado.edu) &lt;/A&gt;
*
* @version
*   Jun 12, 1998
******************************************************************************/
public class CarWash
{
   /**
   * The main method activates &lt;CODE&gt;carWashSimulate&lt;/CODE&gt; with the values:
   *   &lt;CODE&gt;
   *   &lt;br&gt;washTime = 240
   *   &lt;br&gt;arrivalTime = 0.0025
   *   &lt;br&gt;totalTime = 6000
   *   &lt;/CODE&gt;
   * &lt;BR&gt;The &lt;CODE&gt;String&lt;/CODE&gt; argument (&lt;CODE&gt;args&lt;/CODE&gt;) is not used in
   * this implementation.
   **/
   public static void main(String[ ] args) throws IOException
   {
	  BufferedReader stdin = new BufferedReader (new InputStreamReader(System.in));

	  // get total length of simulation from the user
      System.out.println(&quot;How many seconds would you like to simulate?&quot;);
      System.out.println(&quot;(Default is 6000)&quot;);
      int simtime = Integer.parseInt(stdin.readLine());

      // get the probability of a new customer from the user
      System.out.println(&quot;What is the probably of a new customer arriving in any given second?&quot;);
      System.out.println(&quot;(Default is 0.0025)&quot;);
      double probability = Double.parseDouble(stdin.readLine());

      // get the number of seconds it takes to wash the car from the user
      System.out.println(&quot;How many seconds does it take to wash one car?&quot;);
      System.out.println(&quot;(Default is 240)&quot;);
      int washtime = Integer.parseInt(stdin.readLine());

      carWashSimulate(washtime, probability, simtime);
   }

   /**
   * Simulate the running of a car washer for a specified amount of time.
   * @param &lt;CODE&gt;washTime&lt;/CODE&gt;
   *   the number of seconds required to wash one car
   * @param &lt;CODE&gt;arrivalProb&lt;/CODE&gt;
   *   the probability of a customer arriving in any second, for example
   *   0.1 is 10%
   * @param &lt;CODE&gt;totalTime&lt;/CODE&gt;
   *   the total number of seconds for the simulation
   * &lt;dt&gt;&lt;b&gt;Precondition:&lt;/b&gt;&lt;dd&gt;
   *   &lt;CODE&gt;washTime&lt;/CODE&gt; and &lt;CODE&gt;totalTime&lt;/CODE&gt; are positive;
   *   &lt;CODE&gt;arrivalProb&lt;/CODE&gt; lies in the range 0 to 1.
   * &lt;dt&gt;&lt;b&gt;Postcondition:&lt;/b&gt;&lt;dd&gt;
   *   The method has simulated a car wash where &lt;CODE&gt;washTime&lt;/CODE&gt; is the
   *   number of seconds needed to wash one car, &lt;CODE&gt;arrivalProb&lt;/CODE&gt; is
   *   the probability of a customer arriving in any second, and
   *   &lt;CODE&gt;totalTime&lt;/CODE&gt; is the total number of seconds for the
   *   simulation. Before the simulation, the method has written its three
   *   parameters to &lt;CODE&gt;System.out&lt;/CODE&gt;. After the simulation, the method
   *   has written two pieces of information to &lt;CODE&gt;System.out&lt;/CODE&gt;:
   *   (1) The number of cars washed, and (2) The average waiting time for
   *   customers that had their cars washed. (Customers that are still in the
   *   queue ARE included in this average).
   * @exception java.lang.IllegalArgumentException
   *   Indicates that one of the arguments violates the precondition.
   **/
   public static void carWashSimulate
   (int washTime, double arrivalProb, int totalTime)
   {
      Queue&lt;Integer&gt; arrivalTimes = new LinkedList&lt;Integer&gt;( );
      int next;
      BooleanSource arrival = new BooleanSource(arrivalProb);
      Washer machine = new Washer(washTime);
      Averager waitTimes = new Averager( );
      int currentSecond;

      // Write the parameters to System.out.
      System.out.println(&quot;Seconds to wash one car: &quot; + washTime);
      System.out.print(&quot;Probability of customer arrival during a second: &quot;);
      System.out.println(arrivalProb);
      System.out.println(&quot;Total simulation seconds (open \&quot;hours\&quot;): &quot; + totalTime);

      // Check the precondition:
      if (washTime &lt;= 0 || arrivalProb &lt; 0 || arrivalProb &gt; 1 || totalTime &lt; 0)
         throw new IllegalArgumentException(&quot;Values out of range&quot;); 

      for (currentSecond = 0; currentSecond &lt; totalTime || !arrivalTimes.isEmpty(); currentSecond++)
      {  // Simulate the passage of one second of time.

         // Check whether a new customer has arrived.
         if (arrival.query( ) &amp;&amp; currentSecond &lt;= totalTime)
            arrivalTimes.add(currentSecond);

         // Check whether we can start washing another car.
         if ((!machine.isBusy( ))  &amp;&amp;  (!arrivalTimes.isEmpty( )))
         {
            next = arrivalTimes.remove( );
            waitTimes.addNumber(currentSecond - next);
            machine.startWashing( );
         }

         // Subtract one second from the remaining time in the current wash cycle.
         machine.reduceRemainingTime( );
      }

      // Write the summary information about the simulation.
      System.out.println(&quot;Customers served: &quot; + waitTimes.howManyNumbers( ));
      if (waitTimes.howManyNumbers( ) &gt; 0)
         System.out.println(&quot;Average wait: &quot; + waitTimes.average( ) + &quot; sec&quot;);

      // Print ending second to compare to expected &quot;closing time&quot;
      System.out.println(&quot;Ending second (or last customer served): &quot; + currentSecond);
   }

}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.bryansimonson.com/2010/02/21/simulating-a-car-wash-in-java/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Solving the nQueens Problem in Java</title>
		<link>http://www.bryansimonson.com/2010/02/21/solving-the-nqueens-problem-in-java/</link>
		<comments>http://www.bryansimonson.com/2010/02/21/solving-the-nqueens-problem-in-java/#comments</comments>
		<pubDate>Mon, 22 Feb 2010 00:15:34 +0000</pubDate>
		<dc:creator>bryan</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[nqueens]]></category>

		<guid isPermaLink="false">http://www.bryansimonson.com/?p=291</guid>
		<description><![CDATA[From Data Structures and Other Objects Using Java, Chapter 6, Project #10, Page #347: Suppose that you have n queens from a chess game, and that you also have an n-by-n chess board. Is it possible to place all n queens on the board so that no two queens are in the same row, no [...]]]></description>
			<content:encoded><![CDATA[<p>From <a rel="nofollow" href="http://www.amazon.com/Data-Structures-Other-Objects-Using/dp/0321375254/ref=sr_1_2?ie=UTF8&#038;s=books&#038;qid=1266797057&#038;sr=1-2manticorcom-20" >Data Structures and Other Objects Using Java</a>, Chapter 6, Project #10, Page #347:</p>
<blockquote><p>
Suppose that you have <i>n</i> queens from a chess game, and that you also have an <i>n</i>-by-<i>n</i> chess board. Is it possible to place all <i>n</i> queens on the board so that no two queens are in the same row, no two queens are in the same column, and no two queens are on the same diagonal?
</p></blockquote>
<p></p>
<p>WARNING: Cheating is bad, mmmmkay children? Don&#8217;t cheat.</p>
<p>n Queens source code:</p>
<pre class="brush: java; ">

 /*
|	Bryan Simonson
 \	CS211 - Craig Niiyama
  | 2/21/2010
*/

package bryansimonson;
import edu.colorado.collections.*;

public class nQueens {
	public static void main(String[] args) {
		final int QUEENS = 40;
		queens(QUEENS);
	}

	public static void queens(int n){
		boolean success = false;

		// row = the row within the stack, column = the row&#039;s integer value
		ArrayStack&lt;Integer&gt; s = new ArrayStack&lt;Integer&gt;(n);
		s.push(1);

		while (!success &amp;&amp; !s.isEmpty()){
			int x=0;	// placeholder for when we pop values
			boolean conflict = false;

			// check for conflicts
			for (int i=1; i&lt;s.size(); i++){
				int deltarows = s.size()-i;
				if (	// no need to check row, stack preempts row conflict
						s.peek()==s.itemAt(i) ||			// same column
						s.peek()==s.itemAt(i)+deltarows ||	// same diagonal
						s.peek()==s.itemAt(i)-deltarows		// same diagonal
					) conflict = true;
			}

			if (conflict){
				while (s.peek()==n)
					x=s.pop();
				if (!s.isEmpty())
					s.push(s.pop()+1);
				else
					s.push(x+1);
			} else if (!conflict &amp;&amp; s.size()==n){
				success = true;
			} else {
				// new row, so try column 1
				s.push(1);
			}
		}

		// print out the board with the queens
		for (int x=1; x&lt;=s.size(); x++){
			for (int y=1; y&lt;=n; y++){
				if (s.itemAt(x)==y)
					System.out.print(&quot;X &quot;);
				else
					System.out.print(&quot;O &quot;);
			}
			System.out.println();
		}

	}
}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.bryansimonson.com/2010/02/21/solving-the-nqueens-problem-in-java/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>PseudoRandom Number Generation in Java</title>
		<link>http://www.bryansimonson.com/2010/01/20/pseudorandom-number-generation-in-java/</link>
		<comments>http://www.bryansimonson.com/2010/01/20/pseudorandom-number-generation-in-java/#comments</comments>
		<pubDate>Thu, 21 Jan 2010 02:51:42 +0000</pubDate>
		<dc:creator>bryan</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[School]]></category>

		<guid isPermaLink="false">http://www.bryansimonson.com/?p=286</guid>
		<description><![CDATA[Assignment number 1 in CS211 (Java) programming class. (No stealing! I want full point on my grade!) PseudoRandomDemo.java /* &#124; Bryan Simonson \ CS211 - Craig Niiyama &#124; 1/19/2010 */ package bryansimonson; import bryansimonson.PseudoRandom; /** * @author Bryan Simonson (manticor@gmail.com) */ public class PseudoRandomDemo { /** * The main function generates a table that counts [...]]]></description>
			<content:encoded><![CDATA[<p>Assignment number 1 in CS211 (Java) programming class. (No stealing! I want full point on my grade!)</p>
<p>PseudoRandomDemo.java</p>
<pre class="brush: java; ">

 /*
|	Bryan Simonson
 \	CS211 - Craig Niiyama
  | 1/19/2010
*/

package bryansimonson;
import bryansimonson.PseudoRandom;

/**
 * @author Bryan Simonson (manticor@gmail.com)
 */
public class PseudoRandomDemo {

	/**
	 * The main function generates a table that counts how many
	 * instances of a pseudorandom number fall within a certain range.
	 */
	public static void main(String[] args) {
		final int INTRVL = 10;				// interval of distribution table
		final int LOOPS = 1000000;			// number of times to run loop
		final int SEED = 1;					// initial seed value
		final int INCR = 3641;				// increment
		final int MOD = 729;				// modulus
		final int MULT = 40;				// multiplier
		int[] dist = new int[INTRVL];		// distribution table

		PseudoRandom x = new PseudoRandom(SEED, MULT, INCR, MOD);

		System.out.println(&quot;Output of PseudoRandomDemo&quot;);
		System.out.println();

		// Show initial values
		System.out.println(&quot;Initial values&quot;);
		System.out.println(&quot;Interval:\t&quot;+INTRVL);
		System.out.println(&quot;Seed:\t\t&quot;+SEED);
		System.out.println(&quot;Multiplier:\t&quot;+MULT);
		System.out.println(&quot;Increment:\t&quot;+INCR);
		System.out.println(&quot;Modulus:\t&quot;+MOD);
		System.out.println();

		// Demonstrate current() function
		System.out.println(&quot;Demonstrate current() function&quot;);
		System.out.println(x.current());
		System.out.println();

		// Demonstrate next() function
		System.out.println(&quot;Demonstrate next() function&quot;);
		System.out.println(x.next());
		System.out.println(x.next());
		System.out.println(x.next());
		System.out.println();

		// Demonstrate nextMod() function
		System.out.println(&quot;Demonstrate nextMod() function&quot;);
		System.out.print(&quot;nextMod() value: &quot;);
		System.out.printf(&quot;%6.2f&quot;,x.nextMod());
		System.out.println();
		System.out.println(&quot;new seed value:&quot;+x.current());

		// Demonstrate changeSeed() function
		x.changeSeed(SEED);
		System.out.println(&quot;\nSeed has been reset using changeSeed(&quot;+SEED+&quot;)\n&quot;);

		// Populate array with count of instances between each interval
		for (int i = 0; i&lt;LOOPS; i++){
			dist[(int)(x.nextMod()*INTRVL)]++;
		}

		// Print out a table with instance counts per interval
		System.out.println(&quot;Count of instances&quot;);
		System.out.println(&quot;Range\t\tNumber of Occurrences&quot;);
		for (int i=0; i&lt;INTRVL; i++){
			System.out.println(
					&quot;[&quot;+
					((double)(i)/INTRVL)+
					&quot;..&quot;+
					((double)(i+1)/INTRVL)+
					&quot;)\t&quot;+
					dist[i]
			);
		}
	}
}
</pre>
<p>PseudoRandom.java (Class)</p>
<pre class="brush: java; ">

package bryansimonson;

 /*
|	Bryan Simonson
 \	CS211 - Craig Niiyama
  | 1/19/2010
*/

/**
 * @author Bryan Simonson (manticor@gmail.com)
 *
 */
public class PseudoRandom {
	private int seed;
	private int multiplier;
	private int increment;
	private int modulus;

	/**
	 * Constructor for PseudoRandom object.
	 * @param firstseed - The original seed value
	 * @param mult - Multiplier
	 * @param incr - Increment
	 * @param mod - Modulus value
	 */
	public PseudoRandom (int firstseed, int mult, int incr, int mod){
		multiplier = mult;
		increment = incr;
		modulus = mod;
		seed = (mult * firstseed + incr) % mod;
	}

	/**
	 * Access the current seed value
	 * @return
	 * 	The current seed value
	 */
	public int current(){
		return seed;
	}

	/**
	 * Generates the next pseudorandom number iteration
	 * @return
	 * 	The next pseudorandom number iteration
	 * @postcondition
	 * 	The current seed value set to the same value that is returned
	 */
	public int next(){
		seed = (multiplier * seed + increment) % modulus;
		return seed;
	}

	/**
	 * Change the current seed value
	 * @param newseed
	 * @postcondition
	 * 	The current seed value is replaced by &lt;code&gt;newseed&lt;/code&gt;
	 */
	public void changeSeed(int newseed){
		seed = newseed;
	}

	/**
	 * Generates the next pseudorandom number divided by the modulus value
	 * @return
	 * 	a double in the range [0..1)
	 * @postcondition
	 * 	the current seed value is set to whatever the next pseudorandom integer
	 */
	public double nextMod(){
		return (next()/(double)modulus);
	}
}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.bryansimonson.com/2010/01/20/pseudorandom-number-generation-in-java/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>C++ Date Class &#8211; Manipulate Dates in C++</title>
		<link>http://www.bryansimonson.com/2009/11/15/c-date-class-manipulate-dates-in-c/</link>
		<comments>http://www.bryansimonson.com/2009/11/15/c-date-class-manipulate-dates-in-c/#comments</comments>
		<pubDate>Mon, 16 Nov 2009 05:35:54 +0000</pubDate>
		<dc:creator>bryan</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[School]]></category>
		<category><![CDATA[c++]]></category>

		<guid isPermaLink="false">http://www.bryansimonson.com/?p=270</guid>
		<description><![CDATA[Finally! I did it! Assignment #4 is complete, and I can manipulate dates pretty effing easily now. No doubt there is already some vastly superior date manipulation library already out there&#8230; stupid school. Just kidding. I learned a LOT with this assignment. #include &#60;iostream&#62; using namespace std; class Date { private: /* &#124; \ PRIVATE [...]]]></description>
			<content:encoded><![CDATA[<p>Finally! I did it! Assignment #4 is complete, and I can manipulate dates pretty effing easily now.</p>
<p>No doubt there is already some vastly superior date manipulation library already out there&#8230; stupid school.</p>
<p> <img src='http://www.bryansimonson.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  Just kidding. I learned a LOT with this assignment.</p>
<pre class="brush: cpp; ">

#include &lt;iostream&gt;
using namespace std;

class Date {

private:
	 /*
	|
	 \	PRIVATE DATA
	  |
	*/
	static const int EpochYear = 1752;
	static const int EpochMonth = 9;
	static const int EpochDay = 14;
	static const int EpochDoW = 5;		// must define day of week of epoch (5 = Thursday)
	int epochdays;						// this is the number of days since September 14, 1752
	int month,day,year;					// the current value of month/day/year
	bool validdate;

	 /*
	|
	 \	PRIVATE MEMBER FUNCTIONS
	  |
	*/
	bool isLeapYear(int year){
		// check if this year is a leap year, return false if not
		bool leapyear;

		if ((year % 4) == 0){
			if (year % 100 == 0){
				leapyear = false;
				if (year % 400 == 0){
					leapyear = true;
				}
			} else {
				leapyear = true;
			}
		} else {
			leapyear = false;
		}
		return leapyear;
	}

	int daysInMonth(int m, int y){
		// returns the number of days in a given month (1 =  January, etc)
		// invalid month/year combinations return -1
		int days = -1;
		int febdays = 28;

		if (isLeapYear(y))
			febdays = 29;

		switch (m){
			case 1: case 3: case 5: case 7: case 8: case 10: case 12: days = 31; break;
			case 2: days = febdays; break;
			case 4: case 6: case 9: case 11: days = 30; break;
			default: days = -1; break;
		}
		return days;
	}

	int dayOfYear(int m, int d, int y){
		// return the day of year (eg, Jan 1 = 1, Dec 1 = 365 (or 366 on leap years))
		int daycount = 0;		// holds number of days elapsed this year

		// leap through every fully elapsed month
		for (int i=1; i&lt;m; i++){
			daycount += daysInMonth(i,y);
		}

		// don&#039;t forget to add the elapsed days of this month
		daycount += d;

		return daycount;
	}

	int getEpochDays(int m, int d, int y){
		// for a given m/d/y, return the number of days since the epoch, 9/14/1752
		int daycount;	// this will be count of epochdays
		int thisDOY = dayOfYear(m,d,y);
		int epochDOY = dayOfYear(EpochMonth,EpochDay,EpochYear);

		// subtract day of year from epoch
		daycount = thisDOY - epochDOY;

		// add days for each fully elapsed year
		while (y &gt; EpochYear){
			y--;	// decrement year now to avoid overcounting leap year
			if (isLeapYear(y)){
				daycount += 366;
			} else {
				daycount += 365;
			}
		}

		return daycount;
	}

	void convertEpochDays(int daysSinceEpoch, int&amp; m, int&amp; d, int&amp; y){
		// SHOULD NOT be using m/d/y variables to calculate!
		int mm = EpochMonth;
		int dd = EpochDay;
		int yyyy = EpochYear;

		while (daysSinceEpoch &gt; 0){
			//cout &lt;&lt; &quot;days left: &quot;&lt;&lt; daysSinceEpoch &lt;&lt; endl;
			if (daysSinceEpoch &gt;= 366){
				// we have at least a year left
				yyyy++;	// increment year now to avoid taking credit for already elapsed leap day
				if (isLeapYear(yyyy)){
					daysSinceEpoch -= 366;
				} else {
					daysSinceEpoch -= 365;
				}
			} else if (daysSinceEpoch &gt;= 31){
				// we have 31 or more days left
				if (mm == 12){
					daysSinceEpoch -= daysInMonth(mm,yyyy);
					mm = 1;
					yyyy++;
				} else {
					daysSinceEpoch -= daysInMonth(mm,yyyy);
					mm++;
				}
			} else {
				// we have up to 30 days left
				if (dd &lt; daysInMonth(mm,yyyy)){
					dd++;
					daysSinceEpoch--;
				} else if (dd == daysInMonth(mm,yyyy)){
					mm++;
					dd = 1;
					daysSinceEpoch--;
				} else {
					cout &lt;&lt; &quot;You didn&#039;t account for something!&quot;&lt;&lt; endl;
				}
			}
		}

		m = mm;
		d = dd;
		y = yyyy;
	}

public:
	// constructors
	Date(){
		// set default date to September 14, 1752
		month = 9;
		day = 14;
		year = 1752;
		epochdays = 0;
		validdate = true;
	}

	Date(int m, int d, int y){
		 /*
		|	Sets date with user input, verifies if proper date is provided
		 \	for any problem with user input: status member function will return false
		  | - do not allow date prior to September 14, 1752
		*/	

		// set defaults, assume the user is wrong about everything
		month = 9;
		day = 14;
		year = 1752;
		epochdays = 0;
		validdate = false;

		// month cannot be less than 1 or greater than 12
		if (m &gt;= 1 &amp;&amp; m &lt;= 12){
			// month is valid. so far, so good
			// what about days? they can less than &lt;1 or greater than that month&#039;s days
			if (d &gt;= 1 &amp;&amp; d &lt;= daysInMonth(m,y)){
				// date format is valid, but is it at least 9/14/1752?
				if (getEpochDays(m,d,y) &gt;= 0){
					month = m;
					day = d;
					year = y;
					epochdays = getEpochDays(m,d,y);
					validdate = true;
				}
			}
		}
	}

	// member functions
	bool status(void){
		// if date setting has any problems, returns false
		return validdate;
	}

	bool setdate(int m, int d, int y){
		 /*
		|	Sets date with user input, verifies if proper date is provided
		 \	for any problem with user input, returns false, no date change made
		  | - do not allow date prior to September 14, 1752
		*/	

		bool validnewdate = false;	// assume invalid new date (guilty until proven innocent)

		// month cannot be less than 1 or greater than 12
		if (m &gt;= 1 &amp;&amp; m &lt;= 12){
			// month is valid. so far, so good
			// what about days? they can less than &lt;1 or greater than that month&#039;s days
			if (d &gt;= 1 &amp;&amp; d &lt;= daysInMonth(m,y)){
				// date format is valid, but is it at least 9/14/1752?
				if (getEpochDays(m,d,y) &gt;= 0){
					month = m;
					day = d;
					year = y;
					epochdays = getEpochDays(m,d,y);
					validdate = true;
					validnewdate = true;
				}
			}
		}
		return validnewdate;
	}

	int getmonth(void) const {
		// returns month if status is true (Jan=1, Feb=2, etc)
		// if status is false, returns -1
		if (validdate)
			return month;
		else
			return -1;
	}

	int getday(void) const {
		// returns day if status is true; if status is false returns -1
		if (validdate)
			return day;
		else
			return -1;
	}

	int getyear(void) const {
		// returns year if status is true (eg: 2009,2010,1976)
		// if status is false returns -1
		if (validdate)
			return year;
		else
			return -1;
	}

	bool advance(int i){
		// adds i days to date, i may be positive or negative
		// returns false if there any problems
		if ((epochdays + i) &gt;= 0){
			// increment epochdays to advance date
			epochdays += i;

			// now that we know the new count of epochdays, set m/d/y
			convertEpochDays(epochdays,month,day,year);

			return true;
		} else {
			cerr &lt;&lt; &quot;Could not set date prior to September 14, 1752.&quot; &lt;&lt; endl;
			return false;
		}
	}

	int dleft(void){
		// returns days left in the year (eg, December 1st would return 30)
		int daysleft;

		if (validdate)
			daysleft = dayOfYear(12,31,year) - dayOfYear(month,day,year);
		else
			daysleft = -1;

		return daysleft;
	}

	int diff(Date d){
		 /*
		|	determine the number of day difference from argument
		 \	positive return value means date in argument is after class date, negative means before
		  | (eg; if object date is 2/3/09 and argument d is 2/6/09, function will return 3
		*/
		int m,dom,y,diffDays;
		m = d.getmonth();
		dom = d.getday();
		y = d.getyear();

		if (d.status())
			diffDays = epochdays - getEpochDays(m,dom,y);
		else
			diffDays = 0;	// return 0 for comparisons to invalid dates

		return diffDays;
	}

	int dofw(void){
		 /*
		|	returns day of week (Sunday=1,Monday=2, etc)
		 \	NOTE: September 14th, 1752 was a Thursday (dofw = 5)
		  | So if (epochdays % 7) == 0 then dofw = 5; 1 then dofw = 6; etc
		*/
		int dayofweek;
		if (validdate)
			dayofweek = ((epochdays % 7) + EpochDoW);
		else
			dayofweek = -1;

		return dayofweek;
	}

};
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.bryansimonson.com/2009/11/15/c-date-class-manipulate-dates-in-c/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Vote Counting Machine: Borda &amp; Plurality</title>
		<link>http://www.bryansimonson.com/2009/11/05/vote-counting-machine-borda-plurality/</link>
		<comments>http://www.bryansimonson.com/2009/11/05/vote-counting-machine-borda-plurality/#comments</comments>
		<pubDate>Fri, 06 Nov 2009 03:15:24 +0000</pubDate>
		<dc:creator>bryan</dc:creator>
				<category><![CDATA[c++]]></category>

		<guid isPermaLink="false">http://www.bryansimonson.com/?p=235</guid>
		<description><![CDATA[This was my version of a C++ assignment to count votes from a text file. It&#8217;s not super useful outside the classroom, but I&#8217;m posting it anyway. // // Bryan Simonson // Assignment #3 // Vote Counter // #include &#60;fstream&#62; #include &#60;string&#62; #include &#60;iostream&#62; using namespace std; // Function prototypes int MenuSelect(void); void LoadData(char vote[][100], [...]]]></description>
			<content:encoded><![CDATA[<p>This was my version of a C++ assignment to count votes from a text file. It&#8217;s not super useful outside the classroom, but I&#8217;m posting it anyway.</p>
<pre class="brush: cpp; ">

//
// Bryan Simonson
// Assignment #3
// Vote Counter
//

#include &lt;fstream&gt;
#include &lt;string&gt;
#include &lt;iostream&gt;
using namespace std;

// Function prototypes
int MenuSelect(void);
void LoadData(char vote[][100], int&amp; candcount, int&amp; votercount);
void PrefSched(char vote[][100], int&amp; candcount, int&amp; votercount);
void Plurality(char vote[][100], int&amp; candcount, int&amp; votercount);
void Borda(char vote[][100], int&amp; candcount, int&amp; votercount);
void PrintSpace(void);

int MenuSelect(){
	int menuoption = 0;

	cout &lt;&lt; &quot;\n\n\nMain Menu&quot; &lt;&lt; endl;
	cout &lt;&lt; &quot;==================================&quot; &lt;&lt; endl;
	cout &lt;&lt; &quot;1) Load Data&quot; &lt;&lt; endl;
	cout &lt;&lt; &quot;2) Preference Schedule&quot; &lt;&lt; endl;
	cout &lt;&lt; &quot;3) Plurality&quot; &lt;&lt; endl;
	cout &lt;&lt; &quot;4) Borda Count&quot; &lt;&lt; endl;
	cout &lt;&lt; &quot;5) Exit Program&quot; &lt;&lt; endl;
	cout &lt;&lt; &quot;==================================&quot; &lt;&lt; endl &lt;&lt; endl;

	while (menuoption != 1 &amp;&amp; menuoption != 2 &amp;&amp; menuoption != 3 &amp;&amp; menuoption != 4 &amp;&amp; menuoption != 5){
		// Selection is invalid, prompt again
		cout &lt;&lt; &quot;Please enter a number between 1 and 5:&quot; &lt;&lt; endl;
		cin &gt;&gt; menuoption;
	}
	return menuoption;
}

void LoadData(char vote[][100], int&amp; candcount, int&amp; votercount){
	ifstream datafile;
	string filename, line;
	int cand = 0;
	int voter = 0;

	// Prompt for the filename. Unfortunately they&#039;ll have to type for now...
	cout &lt;&lt; &quot;Please type name of the file that contains vote data. (eg, \&quot;votedata.txt\&quot;)&quot; &lt;&lt; endl;
	cin &gt;&gt; filename;

	// try to open file... if not, they&#039;re screwed (for now)
	datafile.open(filename.c_str());

	while (! datafile.eof()){
		getline(datafile,line);
		if (line.size() == 0){				// reached a blank line
			voter++;						// count a new voter
			cand = 0;						// reset &quot;ballot&quot; for new voter
		} else {
			vote[cand][voter] = line.at(0); // record vote
			cand++;
		}
	}

	// correct off by one issue from parsing empty lines
	voter = voter + 1;

	// set reference variables to the last count of voters/candidates
	candcount = cand;
	votercount = voter;

	// close the datafile
	datafile.close();

	cout &lt;&lt; &quot;Data loaded: &quot;&lt;&lt; cand &lt;&lt; &quot; candidates, &quot; &lt;&lt; voter &lt;&lt; &quot; voters\n\n&quot; &lt;&lt; endl;
}

void PrefSched(char vote[][100], int&amp; candcount, int&amp; votercount){
	// Preference Schedule
	// Need to find all the different voting combos
	// and tell the user how many times they appeared

	// preference is a voter attribute
	// to get something comparable we need to create a string by concatenating each column
	string voterpref,comparestring;
	int score;

	for (int i=0;i&lt;votercount;i++){
		voterpref = &quot;&quot;;		//reset compare string
		for (int n=0;n&lt;candcount;n++){
			voterpref.push_back(vote[n][i]);

			// time to compare
			score = 0;
			if (n == (candcount-1)){
				// end of column, we have the full string so let&#039;s compare

				for (int x=0;x&lt;votercount;x++){
					// reset compare string
					comparestring = &quot;&quot;;

					for (int y=0;y&lt;candcount;y++){
						// generate same string for comparison purposes
						comparestring.push_back(vote[y][x]);

						if (y == (candcount-1)){
							if (voterpref == comparestring){
								score++;
							}
						}
					}
				}

				// finally, let&#039;s print the result
				cout &lt;&lt; voterpref &lt;&lt; &quot; - &quot; &lt;&lt; score &lt;&lt; endl;
			}
		}
	}
}

void Plurality(char vote[][100], int&amp; candcount, int&amp; votercount){
	int score;

	cout &lt;&lt; &quot;==========================&quot; &lt;&lt; endl;
	cout &lt;&lt; &quot;Plurality Count&quot; &lt;&lt; endl;
	cout &lt;&lt; candcount &lt;&lt; &quot; candidates, &quot; &lt;&lt; votercount &lt;&lt; &quot; voters&quot; &lt;&lt; endl;
	cout &lt;&lt; &quot;==========================&quot; &lt;&lt; endl;

	// Need to count first place votes for each candidate
	for (int n = 0; n&lt;candcount; n++){
		score = 0;
		for (int i = 0; i&lt;votercount; i++){
			// compare first column to first row
			if (vote[n][0] == vote[0][i]){
				score++;
			}
		}
		cout &lt;&lt; vote[n][0] &lt;&lt; &quot; - &quot; &lt;&lt; score &lt;&lt; endl;
	}
}

void Borda(char vote[][100], int&amp; candcount, int&amp; votercount){
	// Borda scoring
	// Scoring depends on number of candidates
	int score = 0;

	cout &lt;&lt; &quot;==========================&quot; &lt;&lt; endl;
	cout &lt;&lt; &quot;Borda Count&quot; &lt;&lt; endl;
	cout &lt;&lt; candcount &lt;&lt; &quot; candidates, &quot; &lt;&lt; votercount &lt;&lt; &quot; voters&quot; &lt;&lt; endl;
	cout &lt;&lt; &quot;==========================&quot; &lt;&lt; endl;

	// we want to print out each candidate&#039;s score only once, so loop through candidates
	for (int i = 0; i&lt;candcount; i++){
		score = 0;
		cout &lt;&lt; vote[i][0] &lt;&lt; &quot; - &quot;;

		// for each candidate we have to go through the entire table for matches
		// this time as x gets higher, preference (multiple) gets lower
		for (int x = 0, multiple = candcount; x&lt;candcount; x++, multiple--){
			for (int n = 0; n&lt;votercount; n++){
				if (vote[i][0] == vote[x][n]){
					// match found, add points to score
					score += multiple;
				}
			}
		}
		cout &lt;&lt; score &lt;&lt; endl;
	}
}

void PrintSpace(void){
	cout &lt;&lt; &quot;\n\n\n\n\n\n\n\n\n\n&quot;;
}

int main(){
	int menuoption;// = MenuSelect();
	bool exitprogram = false;		// default (of course) to not exiting
	int candcount = 0;
	int votercount = 0;
	char vote[7][100];

	do {
		menuoption = MenuSelect();	// set the menuselection
		switch (menuoption){
			case 1: PrintSpace(); LoadData(vote, candcount,votercount); break;
			case 2: PrintSpace(); PrefSched(vote, candcount, votercount); break;
			case 3: PrintSpace(); Plurality(vote, candcount, votercount); break;
			case 4: PrintSpace(); Borda(vote, candcount, votercount); break;
			case 5: exitprogram = true; break;
			default: cout &lt;&lt; &quot;Make another selection.\n\n&quot;; break;
		}
	} while (! exitprogram);

	// Give user an airline goodbye
	cout &lt;&lt; &quot;Buh-bye now.&quot; &lt;&lt; endl;

	return 0;
}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.bryansimonson.com/2009/11/05/vote-counting-machine-borda-plurality/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>C++ Change Dispenser (My First C++ Program)</title>
		<link>http://www.bryansimonson.com/2009/10/07/my-first-c-program/</link>
		<comments>http://www.bryansimonson.com/2009/10/07/my-first-c-program/#comments</comments>
		<pubDate>Thu, 08 Oct 2009 06:51:59 +0000</pubDate>
		<dc:creator>bryan</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[School]]></category>
		<category><![CDATA[c++]]></category>
		<category><![CDATA[change dispenser]]></category>
		<category><![CDATA[computer science]]></category>
		<category><![CDATA[homework assignement]]></category>

		<guid isPermaLink="false">http://www.bryansimonson.com/?p=140</guid>
		<description><![CDATA[One of these days I&#8217;ll actually know how to program c++ pretty well, and when that happens, I plan to write some kickass software. But when that happens, I figured it would be pretty amusing to look back at my very first c++ program (besides the mandatory &#8220;Hello World!&#8221; app). This was our first assignment [...]]]></description>
			<content:encoded><![CDATA[<p>One of these days I&#8217;ll actually know how to program c++ pretty well, and when that happens, I plan to write some kickass software. But when that happens, I figured it would be pretty amusing to look back at my very first c++ program (besides the mandatory &#8220;Hello World!&#8221; app).</p>
<p>This was our first assignment in Computer Science 210, page 98, #15 in <a rel="nofollow" href="http://www.amazon.com/gp/product/0321450051?ie=UTF8&#038;tag=manticorcom-20&#038;linkCode=as2&#038;camp=1789&#038;creative=9325&#038;creativeASIN=0321450051manticorcom-20" >Problem Solving, Abstraction &#038; Design Using C++ (5th Edition)</a><img src="http://www.assoc-amazon.com/e/ir?t=manticorcom-20&#038;l=as2&#038;o=1&#038;a=0321450051" width="1" height="1" border="0" alt="" style="border:none !important; margin:0px !important;" />. To quote:<br/></p>
<blockquote><p>Write a program that dispenses change. The program should read the amount of the purchase and the amount paid and then display the number of dollars, quarters, dimes, nickels, and pennies given in change.</p></blockquote>
<p>Actually if you keep reading, they tell you the wrong way to do it, as a &#8220;hint&#8221;. Jerks.</p>
<p>But notwithstanding, this is what I wrote:<br />
<script type="syntaxhighlighter" class="brush: cpp"><![CDATA[
// Bryan Simonson
// 10/06/09
// CS210 - Assignment #1
//
// NOTE:
// The book is trying to mislead us into using the % operator for this assignment.
// This shall not be forgotten.
// 
#include <iostream>
using namespace std;
int main() {
	int dollars,quarters,dimes,nickels,pennies;
	double due,payment,change;
	// Get the amount due
	cout << "Please enter the price:\n";
	cin >> due;
	// Check the amount due for problems
	while (due <= 0.01) {
		// Somebody entered zero or less, probably trying to get some free money
		cout << "Sorry cheapskate, you must spend at least $0.01\n\n";		
		// Ask again for the real price
		cout << "Please enter the ACTUAL price:\n";
		cin >> due;
		cout << endl;
	}	
	// Get the payment amount
	cout << "Please provide payment amount (using numbers only):\n";
	cin >> payment;
	// Check payment amount for problems
	while (payment < due) {
		// Somebody is trying to pay less than what's due
		// but we're not accepting ANY money unless we get it all at once
		cout << "No, you owe $" << due << ", not $" << payment << ".\n\n";
		cout << endl << "Please provide FULL payment:\n";
		cin >> payment;
	}
	if (payment > due){
		// They paid more than what's due, time to give out change
		change = payment - due;
		cout << "----------------------------------------------\n";
		cout << "Your change is $" << change << endl;
		// dollars
		for (dollars = 0; change >= 1.00; dollars++){
			change -= 1.00;
		}		
		// quarters
		for (quarters = 0; change >= 0.25; quarters++){
			change -= 0.25;
		}
		// dimes
		for (dimes = 0; change >= 0.10; dimes++){
			change -= 0.10;
		}
		// nickels
		for (nickels = 0; change >= 0.05; nickels++){
			change -= 0.05;
		}
		// pennies, just for good measure
		for (pennies = 0; change > 0.00; pennies++){
			change -= 0.01;
		}
		cout << "You get " << dollars << " dollars, " << quarters << " quarters, " << dimes << " dimes, " << nickels << " nickels, and " << pennies << " pennies.\n\n";
	} else {
		// They must have given exact change
		cout << "Thanks for using exact change!\n";
	}
	return 0;
}
</script></p>
<p>I promise, there was lots more whitespace in the actual program. WordPress is just being stupid. Here's the file for download: <a href='http://www.bryansimonson.com/wp-content/uploads/2009/10/ChangeDispenser1.cpp'>ChangeDispenser.cpp</a>.</p>
<p>Warning: Don't cheat off me.</p>
<p>UPDATE 10-19-09: Fixed a bug in how pennies were calculated.<br />
UPDATE 11-01-09: Fixed formatting / lack of whitespace.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.bryansimonson.com/2009/10/07/my-first-c-program/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
