<?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>Rodrigo Silveira</title>
	<atom:link href="http://www.rodrigo-silveira.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.rodrigo-silveira.com</link>
	<description>Hybrid Web Developer &#38; Web Designer</description>
	<lastBuildDate>Thu, 02 Feb 2012 05:26:53 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>C Challenge: Manipulating Bits</title>
		<link>http://www.rodrigo-silveira.com/challenge-manipulating-bits/</link>
		<comments>http://www.rodrigo-silveira.com/challenge-manipulating-bits/#comments</comments>
		<pubDate>Wed, 18 Jan 2012 21:24:40 +0000</pubDate>
		<dc:creator>Rodrigo Silveira</dc:creator>
				<category><![CDATA[BYU-I]]></category>
		<category><![CDATA[C++]]></category>
		<category><![CDATA[Fun Projects]]></category>

		<guid isPermaLink="false">http://www.rodrigo-silveira.com/?p=244</guid>
		<description><![CDATA[A quick challenge for the C programmers out there wanting something to do this week. The challenge is to complete each function skeleton using only straightline code (i.e., no loops or conditionals) and a limited number of C arithmetic and logical operators. Specifically, you are only allowed to use the following eight operators: ! ~ &#038; ^ &#124; + > ]]></description>
			<content:encoded><![CDATA[<p>The challenge is to complete each function skeleton using only straightline code (i.e., no loops or conditionals) and a limited number of C arithmetic and logical operators.  Specifically, you are only allowed to use the following eight operators: <b>! ~ &#038; ^ | + << >></b></p>
<pre class="i_code">
#include "btest.h"
#include &lt;limits.h>

/*
 * Instructions to Students:
 *
 * STEP 1: Fill in the following struct with your
 *         identifying info.
 */
team_struct team =
{
   /* Team name: Replace with either:
      Your login ID if working as a one person team
      or, ID1+ID2 where ID1 is the login ID of the
      first team member and ID2 is the login ID of
      the second team member */
    "", 

   /* Student name 1:
      Replace with the full name of first team member */
   "",

   /* Login ID 1:
      Replace with the login ID of first team member */
   "",

   /* The following should only be changed if there are
      two team members */
   /* Student name 2: Full name of the second team member */
   "",

   /* Login ID 2: Login ID of the second team member */
   ""
};
</pre>
<p><br/></p>
<pre class="i_code">
#if 0
/*
 * STEP 2: Read the following instructions carefully.
 */

You will provide your solution to the Data Lab by
editing the collection of functions in this source file.

CODING RULES:

  Replace the "return" statement in each function with one
  or more lines of C code that implements the function.
  Your code must conform to the following style:

  int Funct(arg1, arg2, ...) {
      /* brief description of how your implementation works */
      int var1 = Expr1;
      ...
      int varM = ExprM;

      varJ = ExprJ;
      ...
      varN = ExprN;
      return ExprR;
  }

  Each "Expr" is an expression using ONLY the following:
  1. Integer constants 0 through 255 (0xFF), inclusive. You are
      not allowed to use big constants such as 0xffffffff.
  2. Function arguments and local variables (no global variables).
  3. Unary integer operations ! ~
  4. Binary integer operations &#038; ^ | + &lt;&lt; >>

  Some of the problems restrict the set of allowed operators even
  further.
  Each "Expr" may consist of multiple operators. You are not
  restricted to one operator per line.

  You are expressly forbidden to:
  1. Use any control constructs such as if, do, while, for,
     switch, etc.
  2. Define or use any macros.
  3. Define any additional functions in this file.
  4. Call any functions.
  5. Use any other operations, such as &#038;&#038;, ||, -, or ?:
  6. Use any form of casting.

  You may assume that your machine:
  1. Uses 2s complement, 32-bit representations of integers.
  2. Performs right shifts arithmetically.
  3. Has unpredictable behavior when shifting an integer by more
     than the word size.

EXAMPLES OF ACCEPTABLE CODING STYLE:
  /*
   * pow2plus1 - returns 2^x + 1, where 0 &lt;= x &lt;= 31
   */
  int pow2plus1(int x) {
     /* exploit ability of shifts to compute powers of 2 */
     return (1 &lt;&lt; x) + 1;
  }

  /*
   * pow2plus4 - returns 2^x + 4, where 0 &lt;= x &lt;= 31
   */
  int pow2plus4(int x) {
     /* exploit ability of shifts to compute powers of 2 */
     int result = (1 &lt;&lt; x);
     result += 4;
     return result;
  }

NOTES:
  1. Use the dlc (data lab checker) compiler (described in the
     handout) to check the legality of your solutions.
  2. Each function has a maximum number of operators
     (! ~ &#038; ^ | + &lt;&lt; >>) that you are allowed to use for
     your implementation of the function.
     The max operator count is checked by dlc. Note that '=' is
     not counted; you may use as many of these as you want
     without penalty.
  3. Use the btest test harness to check your functions for
     correctness.
  4. The maximum number of ops for each function is given in the
     header comment for each function. If there are any
     inconsistencies between the maximum ops in the writeup
     and in this file, consider this file the authoritative source.
#endif
</pre>
<p><br/></p>
<pre class="i_code">
/*
 * STEP 3: Modify the following functions according the coding rules.
 *
 *   IMPORTANT. TO AVOID GRADING SURPRISES:
 *   1. Use the dlc compiler to check that your solutions conform
 *      to the coding rules.
 *   2. Use the btest test harness to check that your solutions
 *      produce the correct answers. Watch out for corner cases
 *      around Tmin and Tmax.
 */

/*
 * bitNor - ~(x|y) using only ~ and &#038;
 *   Example: bitNor(0x6, 0x5) = 0xFFFFFFF8
 *   Legal ops: ~ &#038;
 *   Max ops: 8
 *   Rating: 1
 */
int bitNor(int x, int y) {
  return 2;
}

/*
 * bitXor - x^y using only ~ and &#038;
 *   Example: bitXor(4, 5) = 1
 *   Legal ops: ~ &#038;
 *   Max ops: 14
 *   Rating: 2
 */
int bitXor(int x, int y) {
  return 2;
}
/*
 * isNotEqual - return 0 if x == y, and 1 otherwise
 *   Examples: isNotEqual(5,5) = 0, isNotEqual(4,5) = 1
 *   Legal ops: ! ~ &#038; ^ | + &lt;&lt; >>
 *   Max ops: 6
 *   Rating: 2
 */
int isNotEqual(int x, int y) {
  return 2;
}

/*
 * getByte - Extract byte n from word x
 *   Bytes numbered from 0 (LSB) to 3 (MSB)
 *   Examples: getByte(0x12345678,1) = 0x56
 *   Legal ops: ! ~ &#038; ^ | + &lt;&lt; >>
 *   Max ops: 6
 *   Rating: 2
 */
int getByte(int x, int n) {
  return 2;
}

/*
 * copyLSB - set all bits of result to least significant bit of x
 *   Example: copyLSB(5) = 0xFFFFFFFF, copyLSB(6) = 0x00000000
 *   Legal ops: ! ~ &#038; ^ | + &lt;&lt; >>
 *   Max ops: 5
 *   Rating: 2
 */
int copyLSB(int x) {
  return 2;
}

/*
 * logicalShift - shift x to the right by n, using a logical shift
 *   Can assume that 1 &lt;= n &lt;= 31
 *   Examples: logicalShift(0x87654321,4) = 0x08765432
 *   Legal ops: ~ &#038; ^ | + &lt;&lt; >>
 *   Max ops: 16
 *   Rating: 3
 */
int logicalShift(int x, int n) {
  return 2;
}

/*
 * bitCount - returns count of number of 1's in word
 *   Examples: bitCount(5) = 2, bitCount(7) = 3
 *   Legal ops: ! ~ &#038; ^ | + &lt;&lt; >>
 *   Max ops: 40
 *   Rating: 4
 */
int bitCount(int x) {
  return 2;
}

/*
 * bang - Compute !x without using !
 *   Examples: bang(3) = 0, bang(0) = 1
 *   Legal ops: ~ &#038; ^ | + &lt;&lt; >>
 *   Max ops: 12
 *   Rating: 4
 */
int bang(int x) {
  return 2;
}

/*
 * leastBitPos - return a mask that marks the position of the
 *               least significant 1 bit. If x == 0, return 0
 *   Example: leastBitPos(96) = 0x20
 *   Legal ops: ! ~ &#038; ^ | + &lt;&lt; >>
 *   Max ops: 6
 *   Rating: 4
 */
int leastBitPos(int x) {
  return 2;
}

/*
 * TMax - return maximum two's complement integer
 *   Legal ops: ! ~ &#038; ^ | + &lt;&lt; >>
 *   Max ops: 4
 *   Rating: 1
 */
int tmax(void) {
  return 2;
}

/*
 * isNonNegative - return 1 if x >= 0, return 0 otherwise
 *   Example: isNonNegative(-1) = 0.  isNonNegative(0) = 1.
 *   Legal ops: ! ~ &#038; ^ | + &lt;&lt; >>
 *   Max ops: 6
 *   Rating: 3
 */
int isNonNegative(int x) {
  return 2;
}

/*
 * isGreater - if x > y  then return 1, else return 0
 *   Example: isGreater(4,5) = 0, isGreater(5,4) = 1
 *   Legal ops: ! ~ &#038; ^ | + &lt;&lt; >>
 *   Max ops: 24
 *   Rating: 3
 */
int isGreater(int x, int y) {
  return 2;
}

/*
 * divpwr2 - Compute x/(2^n), for 0 &lt;= n &lt;= 30
 *  Round toward zero
 *   Examples: divpwr2(15,1) = 7, divpwr2(-33,4) = -2
 *   Legal ops: ! ~ &#038; ^ | + &lt;&lt; >>
 *   Max ops: 15
 *   Rating: 2
 */
int divpwr2(int x, int n) {
    return 2;
}

/*
 * abs - absolute value of x (except returns TMin for TMin)
 *   Example: abs(-1) = 1.
 *   Legal ops: ! ~ &#038; ^ | + &lt;&lt; >>
 *   Max ops: 10
 *   Rating: 4
 */
int abs(int x) {
  return 2;
}

/*
 * addOK - Determine if can compute x+y without overflow
 *   Example: addOK(0x80000000,0x80000000) = 0,
 *            addOK(0x80000000,0x70000000) = 1,
 *   Legal ops: ! ~ &#038; ^ | + &lt;&lt; >>
 *   Max ops: 20
 *   Rating: 3
 */
int addOK(int x, int y) {
  return 2;
}
</pre>
<div id="crp_related"><h1> Related Posts</h1><p><a href="http://www.rodrigo-silveira.com/zero-one-matrix-relations/" rel="bookmark" class="crp_title">Zero-one Matrix Relations &raquo; CS238 Exploration 3</a></p><p><a href="http://www.rodrigo-silveira.com/cs-238-exploration-2-slight-progress/" rel="bookmark" class="crp_title">CS 238 Exploration 2 &#8211; Slight Progress</a></p><p><a href="http://www.rodrigo-silveira.com/binary-matrix-multiplication/" rel="bookmark" class="crp_title">Binary Matrix Multiplication</a></p><p><a href="http://www.rodrigo-silveira.com/html5-stock-market-simulation-php/" rel="bookmark" class="crp_title">HTML5 Stock Market Simulation in PHP</a></p><p><a href="http://www.rodrigo-silveira.com/sudoku-solver-algorithm-javascript/" rel="bookmark" class="crp_title">Sudoku Solver Algorithm in JavaScript</a></p></div>]]></content:encoded>
			<wfw:commentRss>http://www.rodrigo-silveira.com/challenge-manipulating-bits/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Code Formatter &amp; Syntax Highlighter jQuery Plugin</title>
		<link>http://www.rodrigo-silveira.com/jquery-plugin-rokkocode-syntax-highlighter/</link>
		<comments>http://www.rodrigo-silveira.com/jquery-plugin-rokkocode-syntax-highlighter/#comments</comments>
		<pubDate>Mon, 12 Dec 2011 04:09:39 +0000</pubDate>
		<dc:creator>Rodrigo Silveira</dc:creator>
				<category><![CDATA[Articles]]></category>
		<category><![CDATA[Javascript]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[plugins]]></category>
		<category><![CDATA[RokkoCode]]></category>

		<guid isPermaLink="false">http://www.rodrigo-silveira.com/?p=166</guid>
		<description><![CDATA[A simple plugin for jQuery that I wrote today. The plugin takes C, C++, C#, Java, Javascript, or PHP source code in  plain text inside any HTML tag(s) that you specify, and formats it adding line numbers, syntax highlighting, and preserving spacing. You can change the theme through a very basic CSS style sheet file.]]></description>
			<content:encoded><![CDATA[<p><img style="display: none;" src="http://rodrigo-silveira.com/wp-content/uploads/2011/12/source-code-syntax-highlighter-172x116.jpg" alt="Syntax Highlighting for source code in webpages" /></p>
<p>Today I decided to write a simple plugin to extend the functionality of everybody&#8217;s favorite Javascript library: jQuery. The entire process only took around 20 minutes, so I won&#8217;t be surprised if to find major bugs in it in the next few days. I did test the plug in a little bit, but I can&#8217;t promise buglessness in this version.</p>
<p>All the plugin does is take source code that you write inside your HTML file, and format it with line numbers, and syntax highlighting. The highlighting part is styled through an external CSS file, which you can theme to your liking. Since I&#8217;m writing this in mid-December, I decided to style to resemble the Christmas season.</p>
<h1>How it works</h1>
<p>Using the plugin is pretty simple: Import jQuery, my plugin (which I decided to call Rokko Code, after the great Brazilian coder), and the accompanying style sheet (or a custom style sheet if you prefer).</p>
<div class="i_code">
<pre>&lt;script type="text/javascript" src=" jquery.js"&gt;&lt;/script&gt;
&lt;script type="text/javascript" src=" rokkocode.js"&gt;&lt;/script&gt;
&lt;link ref="stylesheet" href="rokkocode.css"/&gt;</pre>
</div>
<p>The next step is to identify where in your HTML you want the plugin to be applied. In this example, I&#8217;ll write all my code inside a DIV tag with a class of “src_code&#8221;.</p>
<div class="i_code">
<pre>&lt;div class="src_code"&gt;
function Person(pName)
{
     this.name = pName;
     this.greet = function()
     {
          return 'Hello. My name is ' + this.name + '.';
     };
}
&lt;/div&gt;</pre>
</div>
<p>Right now, if you look at your file, you should see something like this: </p>
<p><em>function Person(pName){this.name = pName;this.greet = function(){return &#8216;Hello. My name is &#8216; + this.name + &#8216;.&#8217;;};}</em></p>
<p>Pretty boring, since you haven&#8217;t called upon RokkoCode. So now the next step is to call the Rokko Code plugin on that DIV. If you have multiple elements that are matched in the jQuery expression, they will all be formatted.</p>
<div class="i_code">
<pre>&lt;script&gt;
$('src_code').rokkoCode();
&lt;/script&gt;</pre>
</div>
<p>And the final result after the call to $().rokkoCode() is this:</p>
<div id="rokkocode_demo">
function Person(pName)<br />
{<br />
     this.name = pName;<br />
     this.greet = function()<br />
     {<br />
          return &#8216;Hello. My name is &#8216; + this.name + &#8216;.&#8217;;<br />
     };<br />
}<br />
&nbsp;<br />
var me = new Person(&#8216;Rodrigo&#8217;);<br />
alert( me.greet() );
</div>
<p>&nbsp;<br />
<h1>Live Demo</h1>
<ul>
<li>View a demo of my <a href="http://rodrigo-silveira.com/dharma/web-demos/rokkocode-jquery-plugin-demo.html">RokkoCode jQuery Plugin</a>.</li>
</ul>
<h1>Download Source Code</h1>
<p>Download my RokkoCode plugin and start formatting and highlighting any C, C++, C#, Java, Javascript, and PHP code in your HTML files today.</p>
<ul>
<li><a href="http://www.rodrigo-silveira.com/dharma/web-demos/src/jquery.rokkocode.0.23.js">RokkoCode jQuery Plugin (.js file)</a></li>
<li><a href="http://www.rodrigo-silveira.com/dharma/web-demos/src/jquery.rokkocode.css">RokkoCode Christmas Theme (.css file)</a></li>
</ul>
<div id="src_injection_rokkocode_demo"></div>
<link rel="stylesheet" type="text/css" href="http://rodrigo-silveira.com/dharma/web-demos/src/jquery.rokkocode.css" media="all" />
<script>$('#src_injection_rokkocode_demo').append('<script src="/dharma/web-demos/src/jquery.rokkocode.0.23.js"/>');$('#rokkocode_demo').rokkoCode();</script></p>
<div id="crp_related"><h1> Related Posts</h1><p><a href="http://www.rodrigo-silveira.com/html5-stock-market-simulation-php/" rel="bookmark" class="crp_title">HTML5 Stock Market Simulation in PHP</a></p><p><a href="http://www.rodrigo-silveira.com/sudoku-solver-algorithm-javascript/" rel="bookmark" class="crp_title">Sudoku Solver Algorithm in JavaScript</a></p><p><a href="http://www.rodrigo-silveira.com/challenge-manipulating-bits/" rel="bookmark" class="crp_title">C Challenge: Manipulating Bits</a></p><p><a href="http://www.rodrigo-silveira.com/binary-matrix-multiplication/" rel="bookmark" class="crp_title">Binary Matrix Multiplication</a></p><p><a href="http://www.rodrigo-silveira.com/cs-238-exploration-2-slight-progress/" rel="bookmark" class="crp_title">CS 238 Exploration 2 &#8211; Slight Progress</a></p></div>]]></content:encoded>
			<wfw:commentRss>http://www.rodrigo-silveira.com/jquery-plugin-rokkocode-syntax-highlighter/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>HTML5 Stock Market Simulation in PHP</title>
		<link>http://www.rodrigo-silveira.com/html5-stock-market-simulation-php/</link>
		<comments>http://www.rodrigo-silveira.com/html5-stock-market-simulation-php/#comments</comments>
		<pubDate>Sun, 20 Nov 2011 05:34:38 +0000</pubDate>
		<dc:creator>Rodrigo Silveira</dc:creator>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Web 2.0]]></category>
		<category><![CDATA[HTML5 Demo]]></category>
		<category><![CDATA[Screen Cast]]></category>
		<category><![CDATA[Web Sockets]]></category>

		<guid isPermaLink="false">http://www.rodrigo-silveira.com/?p=153</guid>
		<description><![CDATA[I have decided to take the time to post the source code for my HTML5 Stock Market simulator written in PHP. I wrote a PHP implementation of HTML5 Web Sockets for a networking class I was taking at school, and made a simple Stock Exchange simulator application out of it with HTML5 (Javascript's Web Socket object).]]></description>
			<content:encoded><![CDATA[</p>
<h2>Update: Source code now available</h2>
<p>Download <a href="http://rodrigo-silveira.com/wp-content/uploads/2012/01/websocket.html5server.zip">the source code</a> for this application.</p>
<hr/>
<h2>HTML5 WebSocket Server in PHP</h2>
<p>In response to the several emails I have received in the last two weeks, I have decided to take the time to post the source code for my HTML5 Stock Market simulator written in PHP. I wrote a PHP implementation of HTML5 Web Sockets, and made a simple Stock Exchange simulator application out of it with HTML5 (Javascript&#8217;s Web Socket object). While I&#8217;m at it, I&#8217;ll go ahead and post a brief explanation of what I did and how things work, so check back soon if that is of any interest to you. Here&#8217;s a link to the <a href="http://www.youtube.com/watch?v=oJxWhmt5m-o">YouTube screen cast</a> that I posted about it. Or if you&#8217;d like, I guess you can just watch the video right here:</p>
<p><iframe width="420" height="315" src="http://www.youtube.com/embed/oJxWhmt5m-o" frameborder="0" allowfullscreen></iframe></p>
<h2>The Code</h1>
<p>For those of you who have been waiting for me to post the code for this, I apologize for the delay. Download <a href="http://rodrigo-silveira.com/wp-content/uploads/2012/01/websocket.html5server.zip">the source code</a> and play around with this stock simulator for yourself. I was just trying out the app a few minutes ago, and I noticed that the latest version of <a href="http://www.google.com/aclk?sa=L&#038;ai=C_hgX2HkXT4iDJee0iAKMs-iDC6mmrvQB0bDj5huJlNy_CwgAEAEgyZiiC1CigbjN_v____8BYMmO9ofso9wXyAEBqgQbT9DdaSW_86o0Bmjs2bih_M92kGmRaAsui4XagAWQTqAGGg&#038;sig=AOD64_2dpDxeSa8hhn6pnogyKmb_CPx0tg&#038;ved=0CBMQ0Qw&#038;adurl=http://www.google.com/chrome/intl/en/make/download.html%3F%26brand%3DCHMB%26utm_campaign%3Den%26utm_source%3Den-ha-na-us-sk%26utm_medium%3Dha&#038;rct=j&#038;q=download+chrome">Chrome </a>wasn&#8217;t connecting to the PHP server for some reason. The server recognized the connection request, and even maintained the socket opened, but the browser threw some exception. I haven&#8217;t looked into it too much due to current time constraints, so someone that finds out something about it please post. The code does work just fine in <a href="http://www.google.com/url?sa=t&#038;rct=j&#038;q=&#038;esrc=s&#038;source=web&#038;cd=1&#038;sqi=2&#038;ved=0CCsQFjAA&#038;url=http%3A%2F%2Fwww.apple.com%2Fsafari%2Fdownload%2F&#038;ei=8HkXT4rjEbLKiALy3o2KAQ&#038;usg=AFQjCNHWLTA9xzeCUYjWJ9KECN1AnsRgKA">Safari</a>, though. I have not tested it in <a href="http://www.google.com/url?sa=t&#038;rct=j&#038;q=&#038;esrc=s&#038;source=web&#038;cd=1&#038;ved=0CDAQFjAA&#038;url=http%3A%2F%2Fwww.mozilla.org%2Fen-US%2Ffirefox%2Fnew%2F&#038;ei=_XkXT-u4BKzViAKCxMDXDw&#038;usg=AFQjCNHXR7GrDNHIc3plcSvQSx_ByCacYQ">Firefox</a>, but I&#8217;d assume it&#8217;d work fine. If not, make sure that there&#8217;s no settings that prevent websocket connections from being established. As far as <a href="http://www.google.com/aclk?sa=L&#038;ai=CIwnUCnoXT-CfNMjoiAKFxIXfCbW_m4kDxarTvjLli7SXewgAEAEgyZiiC1CNocKq-f____8BYMmO9ofso9wXyAEBqgQYT9AbjH94c8zNq7odhw4_Uoejbq0YdWeXgAWQTg&#038;sig=AOD64_1OYYf9_WQQLqZFeUGw_tbrVCQY4w&#038;ved=0CAwQ0Qw&#038;adurl=http://clk.atdmt.com/MRT/go/336236240/direct/01/%3Fhref%3Dhttp://view.atdmt.com/action/mrt101_PFXUSMSFTIEUSGenericActionTag_1/v3/sz9CZgzqI_13467314741_e_8754bh8916/%3Fhref%3Dhttp%253A%252F%252Fpixel.quantserve.com%252Fr%253Ba%253Dp-5eu58oSpL1cEs%253Blabels%253D_click.publisher.SEARCH%252BGoogle%252C_click.campaign.IE9_RTWDR%252C_click.placement.*http%253A%252F%252Fwindows.microsoft.com%252Fen-US%252Finternet-explorer%252Fproducts%252Fie%252Fhome%253Focid%253Die9_bow_Google%2526WT.srch%253D1%2526mtag%253DSearGoogle&#038;rct=j&#038;q=download+ie9">Internet Explorer 9</a> is concerned, I haven&#8217;t tried it either, but wouldn&#8217;t be surprised if it worked with it, too.</p>
<p>So there you have it. There are instructions in the zip file on how to run the application. As far as extending the app, or building different apps using the server, feel free to do whatever you want with it. Although the code was written for a networking class that I took at school, the elegance and clarity of the code was not the priority. Thus, any graphics about a CS460 class, or poor code documentation can be justified for this reason.</p>
<div id="crp_related"><h1> Related Posts</h1><p><a href="http://www.rodrigo-silveira.com/sudoku-solver-algorithm-javascript/" rel="bookmark" class="crp_title">Sudoku Solver Algorithm in JavaScript</a></p><p><a href="http://www.rodrigo-silveira.com/binary-matrix-multiplication/" rel="bookmark" class="crp_title">Binary Matrix Multiplication</a></p><p><a href="http://www.rodrigo-silveira.com/jquery-plugin-rokkocode-syntax-highlighter/" rel="bookmark" class="crp_title">Code Formatter &#038; Syntax Highlighter jQuery Plugin</a></p><p><a href="http://www.rodrigo-silveira.com/cs-238-exploration-2-slight-progress/" rel="bookmark" class="crp_title">CS 238 Exploration 2 &#8211; Slight Progress</a></p><p><a href="http://www.rodrigo-silveira.com/challenge-manipulating-bits/" rel="bookmark" class="crp_title">C Challenge: Manipulating Bits</a></p></div>]]></content:encoded>
			<wfw:commentRss>http://www.rodrigo-silveira.com/html5-stock-market-simulation-php/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Sudoku Solver Algorithm in JavaScript</title>
		<link>http://www.rodrigo-silveira.com/sudoku-solver-algorithm-javascript/</link>
		<comments>http://www.rodrigo-silveira.com/sudoku-solver-algorithm-javascript/#comments</comments>
		<pubDate>Fri, 18 Nov 2011 08:41:17 +0000</pubDate>
		<dc:creator>Rodrigo Silveira</dc:creator>
				<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[Fun Projects]]></category>
		<category><![CDATA[HTML5]]></category>
		<category><![CDATA[Javascript]]></category>
		<category><![CDATA[Artificial Intelligence]]></category>
		<category><![CDATA[C++ to Javascript port]]></category>
		<category><![CDATA[Javascript Games]]></category>
		<category><![CDATA[Sudoku]]></category>
		<category><![CDATA[Sudoku Algorithm]]></category>

		<guid isPermaLink="false">http://www.rodrigo-silveira.com/?p=141</guid>
		<description><![CDATA[ My final project for one of my C++ classes is a game of Sudoku. The program, to be written in C++, must be able to read a board from a text file, allow the human player to play the game, with simple rules enforced, as well as allow the user to save the game to an external text file. For extra credit the professor challenged us to write the AI to solve the game. My goal is to get the extra credit, but later to convert the code to Javascript and make a Google Chrome App out of it. Sounds like a fun challenge.]]></description>
			<content:encoded><![CDATA[<p>The end of the semester is here. Just about one more project for each of the Computer Science classes I&#8217;m taking right now&#8230; With that comes the opportunity to port C++ code to the browser, and put out some cool HTML5 apps. My final project for one of my C++ classes is a game of <a href="http://en.wikipedia.org/wiki/Sudoku" target="_blank">Sudoku</a>. The program, to be written in C++, must be able to read a board from a text file, allow the human player to play the game, with simple rules enforced, as well as allow the user to save the game to an external text file. For extra credit the professor challenged us to write the AI to solve the game. My goal is to get the extra credit, but later to convert the code to Javascript and make a Google Chrome App out of it. Sounds like a fun challenge.</p>
<p><img src="http://rodrigo-silveira.com/wp-content/uploads/2011/11/sudoku-board-300x300.jpg" alt="Sudoku Board" title="Sudoku Board" width="200" height="200" align="right" /></p>
<p>From the little preliminary research I have done on the subject of <a href="http://en.wikipedia.org/wiki/Sudoku_algorithms" target="_blank">sudoku algorithms</a>, it doesn&#8217;t seem like it&#8217;s too complicated. Since efficiency isn&#8217;t a factor in my assignment, I&#8217;m confident I&#8217;ll at least be able to finish that pretty [relatively] quickly. </p>
<p>As I get more work done on it, both the C++ version of the game, as well as the Javascript version, I&#8217;ll be posting my findings, source code, and so forth.</p>
<p>As always, please post your questions and comments, as well as, and especially any tips to suggestions to help me out. Those are always welcome.</p>
<div id="crp_related"><h1> Related Posts</h1><p><a href="http://www.rodrigo-silveira.com/html5-stock-market-simulation-php/" rel="bookmark" class="crp_title">HTML5 Stock Market Simulation in PHP</a></p><p><a href="http://www.rodrigo-silveira.com/cs-238-exploration-2-slight-progress/" rel="bookmark" class="crp_title">CS 238 Exploration 2 &#8211; Slight Progress</a></p><p><a href="http://www.rodrigo-silveira.com/cs-238-exploration-2/" rel="bookmark" class="crp_title">CS 238 Exploration 2</a></p><p><a href="http://www.rodrigo-silveira.com/binary-matrix-multiplication/" rel="bookmark" class="crp_title">Binary Matrix Multiplication</a></p><p><a href="http://www.rodrigo-silveira.com/challenge-manipulating-bits/" rel="bookmark" class="crp_title">C Challenge: Manipulating Bits</a></p></div>]]></content:encoded>
			<wfw:commentRss>http://www.rodrigo-silveira.com/sudoku-solver-algorithm-javascript/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Binary Matrix Multiplication</title>
		<link>http://www.rodrigo-silveira.com/binary-matrix-multiplication/</link>
		<comments>http://www.rodrigo-silveira.com/binary-matrix-multiplication/#comments</comments>
		<pubDate>Wed, 26 Oct 2011 05:34:02 +0000</pubDate>
		<dc:creator>Rodrigo Silveira</dc:creator>
				<category><![CDATA[BYU-I]]></category>
		<category><![CDATA[C++]]></category>
		<category><![CDATA[Math & Programming]]></category>
		<category><![CDATA[School Projects]]></category>
		<category><![CDATA[The Matrix]]></category>

		<guid isPermaLink="false">http://rodrigo-silveira.com/?p=120</guid>
		<description><![CDATA[A simple and efficient way to multiply two or more matrices, but more specifically, a binary matrix (also known as zero-one matrix). This code has many uses, but was written specifically to solve the problem of determining whether a given binary matrix is transitive.]]></description>
			<content:encoded><![CDATA[<p>I put this code together as part of my CS 238 class (Discrete Math 2). In our current exploration (project), we need to analyze binary (zero-one) matrices for certain properties. One of these properties is transitive. The easiest way to test if a binary matrix is transitive is to square the matrix (multiply it by itself), and see if the result is equal to the original. Pretty easy. </p>
<h1>How to Multiply a Binary Matrix</h1>
<p>The strategy we&#8217;ll use is super easy: Start performing matrix multiplication with the same matrix (adding the sum of a row with a column) to determine each element. Of course, since this is a binary (boolean) matrix, instead of multiplication, you will AND (boolean math) the elements, and instead of adding, you will OR the elements. After you&#8217;ve ANDed all the pairs, remember that having a single TRUE value will cause the entire OR operation to evaluate to TRUE. So as you&#8217;re ANDing each pair, you can stop checking as soon as you find a TRUE value from the AND operation, and conclude that the resulting element is 1 (TRUE). If you never find a TRUE value from the ANDings, then by default the OR operation will be FALSE, so we don&#8217;t even need to bother actually checking it.</p>
<p>Here&#8217;s some sample code that you can use. This code sets up a 4&#215;4 binary matrix (which is indeed transitive, by the way), then traverses it and display it to the screen, and at the same time take the product of it with itself (M x M). After that is done, if both matrices are equal, then the original matrix is in fact transitive.</p>
<pre class="i_code">
int boolProd()
{
   bool m1[4][4] = { {1,1,0,0},
                     {1,1,0,0},
                     {1,0,1,1},
                     {0,0,0,1}
                  };

   // This is the resulting matrix
   bool m2[4][4];

   cout << "M1 = " << endl;

   /***************************************************
    * Matrix multiplication:
    *
    * M1 = [[a,b]    M2 = [[1,2]
    *       [c,d]]         [3,4]]
    *
    * M1 x M2 = [[(a1+b3), (a2+b4)
    *            [(c1+d3), (c2+d4)]]
    *
    * When multiplying binary matrices,
    * the product is found by the AND operation,
    * and the sum by the OR operation.
    * Thus, if a single TRUE value is found
    * while performing the AND operation,
    * the SUM (OR) will be TRUE no matter what,
    * since a singe TRUE value makes an OR evaluation
    * TRUE.
    ***************************************************/

   // Check every column
   for(int x = 0; x < 4; x++)
   {
      // Check every row
      for(int y = 0; y < 4; y++)
      {
         cout << setw(4) << m1[x][y];

         // Until proven innocent, the product is guilty (not free)
         bool sum = false;

         // Go through the entire row/column and check each element
         for(int j = 0; j < 4; j++)
         {
            // A single true is enough to make it all true
            if(m1[j][y] &#038;&#038; m1[x][j])
            {
               // Set the product to true
               sum = true;

               // No need to keep checking. Set the it free!
               break;
            }
         }

         m2[x][y] = sum;
      }

      cout << endl;
   }

   cout << endl;
   cout << "M2 = " << endl;
   for(int x = 0; x < 4; x++)
   {
      for(int y = 0; y < 4; y++)
      {
         cout << setw(4) << m2[x][y];
      }

      cout << endl;
   }

   return 0;
}
</pre>
<h1>Boolean Product</h1>
<p>The output of this program is simple. It prints the matrix M1:</p>
<p>1, 1, 0, 0<br />
1, 1, 0, 0<br />
0, 0, 1, 1<br />
0, 0, 1, 1</p>
<p>And the boolean product of M1 x M1, which in this case is equal to M1 (thus showing that M1 is transitive).</p>
<div id="crp_related"><h1> Related Posts</h1><p><a href="http://www.rodrigo-silveira.com/zero-one-matrix-relations/" rel="bookmark" class="crp_title">Zero-one Matrix Relations &raquo; CS238 Exploration 3</a></p><p><a href="http://www.rodrigo-silveira.com/cs-238-exploration-2/" rel="bookmark" class="crp_title">CS 238 Exploration 2</a></p><p><a href="http://www.rodrigo-silveira.com/cs-238-exploration-2-slight-progress/" rel="bookmark" class="crp_title">CS 238 Exploration 2 &#8211; Slight Progress</a></p><p><a href="http://www.rodrigo-silveira.com/challenge-manipulating-bits/" rel="bookmark" class="crp_title">C Challenge: Manipulating Bits</a></p><p><a href="http://www.rodrigo-silveira.com/html5-stock-market-simulation-php/" rel="bookmark" class="crp_title">HTML5 Stock Market Simulation in PHP</a></p></div>]]></content:encoded>
			<wfw:commentRss>http://www.rodrigo-silveira.com/binary-matrix-multiplication/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Zero-one Matrix Relations &#187; CS238 Exploration 3</title>
		<link>http://www.rodrigo-silveira.com/zero-one-matrix-relations/</link>
		<comments>http://www.rodrigo-silveira.com/zero-one-matrix-relations/#comments</comments>
		<pubDate>Sun, 23 Oct 2011 21:23:17 +0000</pubDate>
		<dc:creator>Rodrigo Silveira</dc:creator>
				<category><![CDATA[BYU-I]]></category>
		<category><![CDATA[C++]]></category>
		<category><![CDATA[Math & Programming]]></category>
		<category><![CDATA[School Projects]]></category>
		<category><![CDATA[The Matrix]]></category>

		<guid isPermaLink="false">http://rodrigo-silveira.com/?p=84</guid>
		<description><![CDATA[This is the third exploration in CS 238 (Discrete Math 2) that Brother Neff assigned. So far this is the easiest exploration I've seen since I started BYU-Idaho. All that we need to do is analyze a bunch of 2x2 and 4x4 matrices, and determine if they are symmetric, antisymmetric, asymmetric, reflexive, nonreflexive, irreflexive, and transitive. Most of the code is already provided (as always, the code is all C++). All we need to do is implement the functions that check for those properties in the matrices. Extra points are awarded for efficient, non-redundant code.]]></description>
			<content:encoded><![CDATA[<p>The purpose of this exploration is for you to explore and enhance an implementation of a representation of relations to discover their basic properties.</p>
<h2>Requirements</h2>
<p>Write a C++ program that takes inputs which are ﬁles containing connection (zero-one) matrices of binary<br />
relations of a set with itself. Determine which properties each relation has. Start with the stub code supplied. Add your code and submit the ﬁle with the same name (relations.cpp). If conditions are right, you can build and test your code in the Linux Lab via the command: <em>make it just so</em></p>
<h2>What the code does so far</h2>
<p>So far my code does the following:</p>
<ul>
<li>Determines if <strong>reflexive</strong>, <strong>irreflexive</strong>, and <strong>nonreflexive</strong></li>
</ul>
<p>The way I&#8217;m determining reflexiveness is by storing the sum of the main diagonal (mSumOfDiagonal) in a member variable. Then the check for reflexiveness is simple:</p>
<pre class="i_code">
bool isReflexive()
{
   // TRUE if diagonal is all 1
   return mSumOfDiagonal == mSize;
}
</pre>
<p>Check for irreflexiveness is equally obvious:</p>
<pre class="i_code">
bool isIrreflexive()
{
   // TRUE if diagonal is all 0
   return mSumOfDiagonal == 0;
}
</pre>
<p>Finally, test for nonreflexive (main diagonal has 1s and 0s in it) is equally simple:</p>
<pre class="i_code">
bool isNonreflexive()
{
   // TRUE if diagonal is all 1
   return !isReflexive() &amp;&amp; !isIrreflexive;
}
</pre>
<h1>The rest of the code</h1>
<pre  class="i_code">
class Relation operator*(Relation&amp; r1, Relation&amp; r2);

class Relation
{
private:
   bool** mMatrix;
   int mSize;
   int mSumOfDiagonal;

   void init()
   {
      mMatrix = new bool*[mSize];
      for (int i = 0; i &lt; mSize; i++)
      {
         mMatrix[i] = new bool[mSize];
      }
   }

public:
   Relation(int size)
   {
      mSize = size;
      mSumOfDiagonal = 0;
      init();
   }

   Relation&amp; operator=(const Relation&amp; rtSide)
   {
      if (this == &amp;rtSide)
      {
         return *this;
      }
      else
      {
         mSize = rtSide.mSize;
         for (int i = 0; i &lt; mSize; i++)
         {
            delete [] mMatrix[i];
         }
         delete [] mMatrix;
         init();
         for (int x = 0; x &lt; mSize; x++)
         {
            for (int y = 0; y &lt; mSize; y++)
            {
               mMatrix[x][y] = rtSide[x][y];
            }
         }
      }
      return *this;
   }

   Relation(const Relation&amp; relation)
   {
      mSize = relation.getConnectionMatrixSize();
      init();
      *this = relation;
   }

   ~Relation()
   {
      for (int i = 0; i &lt; mSize; i++)
      {
         delete [] mMatrix[i];
      }
      delete [] mMatrix;
   }

   int getConnectionMatrixSize() const
   {
      return mSize;
   }

   bool* operator[](int row) const
   {
      return mMatrix[row];
   }

   bool operator==(const Relation&amp; relation)
   {
      int size = relation.getConnectionMatrixSize();
      if (mSize != size)
      {
         return false;
      }
      for (int i = 0; i &lt; size; i++)
      {
         for (int j = 0; j &lt; size; j++)
         {
            if (mMatrix[i][j] != relation[i][j])
            {
               return false;
            }
         }
      }
      return true;
   }

   bool isReflexive();
   bool isIrreflexive();
   bool isNonreflexive();
   bool isSymmetric();
   bool isAntisymmetric();
   bool isAsymmetric();
   bool isTransitive();
   void describe();

   // Rodrigo's touch
   int sumOfDiagonal();
};

ostream&amp; operator&lt;&lt;(ostream&amp; os, const Relation&amp; relation)
{
   int n = relation.getConnectionMatrixSize();
   for (int i = 0; i &lt; n; i++)
   {
      for (int j = 0; j &lt; n; j++)
      {
         os &lt;&lt; relation[i][j] &lt;&lt; " ";
      }
      os &lt;&lt; endl;
   }
   return os;
}

istream&amp; operator&gt;&gt;(istream&amp; is, Relation&amp; relation)
{
   int n = relation.getConnectionMatrixSize();
   for (int i = 0; i &lt; n; i++)
   {
      for (int j = 0; j &lt; n; j++)
      {
         is &gt;&gt; relation[i][j];
      }
   }
   return is;
}

void Relation::describe()
{
   mSumOfDiagonal = sumOfDiagonal();

   cout &lt;&lt; "\nThe relation represented by the "
        &lt;&lt; mSize &lt;&lt; "x" &lt;&lt; mSize &lt;&lt; " matrix\n";
   cout &lt;&lt; *this &lt;&lt; "is\n";
   cout &lt;&lt; (isReflexive() ? "" : "NOT ") &lt;&lt; "Reflexive;\n";
   cout &lt;&lt; (isIrreflexive() ? "" : "NOT ") &lt;&lt; "Irreflexive;\n";
   cout &lt;&lt; (isNonreflexive() ? "" : "NOT ") &lt;&lt; "Nonreflexive;\n";
   cout &lt;&lt; (isSymmetric() ? "" : "NOT ") &lt;&lt; "Symmetric;\n";
   cout &lt;&lt; (isAntisymmetric() ? "" : "NOT ") &lt;&lt; "Antisymmetric;\n";
   cout &lt;&lt; (isAsymmetric() ? "" : "NOT ") &lt;&lt; "Asymmetric; and\n";
   cout &lt;&lt; (isTransitive() ? "" : "NOT ") &lt;&lt; "Transitive.\n";
}

/******************************************************
*
* MAIN
*
******************************************************/
int main(int argc, char* argv[])
{
   // __DEBUG__
   argc = 2;
   argv[1] = "../relations/16.15";
   argv[1] = "../relations/16.08";
   argv[1] = "../relations/8.3.32.b";
   // __DEBUG__

   for (int i = 1; i &lt; argc; i++)
   {
      string file = argv[i];
      ifstream inFile(file.c_str());

      if (inFile.is_open())
      {
         int size;
         inFile &gt;&gt; size;
         Relation relation(size);
         inFile &gt;&gt; relation;
         inFile.close();
         relation.describe();
      }
      else
      {
         cout &lt;&lt; "Unable to open " + file;
      }
   }

   return 0;
}

int Relation::sumOfDiagonal()
{
   int sumOfDiagonal = 0;

   // Go through every column
   for(int y = 0; y &lt; mSize; y++)

      // Go through every row
      for(int x = 0; x &lt; mSize; x++)

         // Sum the elements in the main diagonal
         if(x == y)
            sumOfDiagonal += mMatrix[x][y];

cout &lt;&lt; sumOfDiagonal &lt;&lt; endl;
   return sumOfDiagonal;
}

/******************************************************
*
* IS REFLEXIVE
*
* TRUE if main diagonal is all 1. In other words, TRUE
*      when sum of main diagonal is the same as the
*      size of the matrix (4x4 has size of 4)
*
******************************************************/
bool Relation::isReflexive()
{
   return mSumOfDiagonal == mSize;
}

/******************************************************
*
* IS IRREFLEXIVE
*
* TRUE if main diagonal is all 0. In other words, TRUE
*      when sum of main diagonal is zero
*
******************************************************/
bool Relation::isIrreflexive()
{
   return mSumOfDiagonal == 0;
}

/******************************************************
*
* IS NON REFLEXIVE
*
* TRUE if matrix is neither reflexive or irreflexive
*
******************************************************/
bool Relation::isNonreflexive()
{
   return !isIrreflexive() &amp;&amp; !isReflexive();
}

/******************************************************
*
* IS SYMMETRIC
*
******************************************************/
bool Relation::isSymmetric()
{
   return false;
}

/******************************************************
*
* IS ANTISYMMETRIC
*
******************************************************/
bool Relation::isAntisymmetric()
{
   return false;
}

/******************************************************
*
* IS ASYMMETRIC
*
******************************************************/
bool Relation::isAsymmetric()
{
   return false;
}

/******************************************************
*
* IS TRANSITIVE
*
******************************************************/
bool Relation::isTransitive()
{
   return false;
}
</pre>
<div id="crp_related"><h1> Related Posts</h1><p><a href="http://www.rodrigo-silveira.com/binary-matrix-multiplication/" rel="bookmark" class="crp_title">Binary Matrix Multiplication</a></p><p><a href="http://www.rodrigo-silveira.com/cs-238-exploration-2-slight-progress/" rel="bookmark" class="crp_title">CS 238 Exploration 2 &#8211; Slight Progress</a></p><p><a href="http://www.rodrigo-silveira.com/cs-238-exploration-2/" rel="bookmark" class="crp_title">CS 238 Exploration 2</a></p><p><a href="http://www.rodrigo-silveira.com/challenge-manipulating-bits/" rel="bookmark" class="crp_title">C Challenge: Manipulating Bits</a></p><p><a href="http://www.rodrigo-silveira.com/html5-stock-market-simulation-php/" rel="bookmark" class="crp_title">HTML5 Stock Market Simulation in PHP</a></p></div>]]></content:encoded>
			<wfw:commentRss>http://www.rodrigo-silveira.com/zero-one-matrix-relations/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>CS 238 Exploration 2 &#8211; Slight Progress</title>
		<link>http://www.rodrigo-silveira.com/cs-238-exploration-2-slight-progress/</link>
		<comments>http://www.rodrigo-silveira.com/cs-238-exploration-2-slight-progress/#comments</comments>
		<pubDate>Fri, 21 Oct 2011 04:34:22 +0000</pubDate>
		<dc:creator>Rodrigo Silveira</dc:creator>
				<category><![CDATA[C++]]></category>
		<category><![CDATA[Discrete Math]]></category>
		<category><![CDATA[Recurrence Relations]]></category>
		<category><![CDATA[School Projects]]></category>

		<guid isPermaLink="false">http://rodrigo-silveira.com/?p=78</guid>
		<description><![CDATA[So far I've implemented the functionality to calculate total payments with the extra monthly payments, but it's not using the start and end dates for the extra payments (as optional parameters passed into the app).]]></description>
			<content:encoded><![CDATA[<p>This calculates the total payments with the extra payments, but it&#8217;s not using the start and end dates for the extra payments (as optional parameters passed into the app).</p>
<p>There&#8217;s an earlier post with <a href="http://rodrigo-silveira.com/cs-238-exploration-2/">some code</a> if you&#8217;re interested, even though the following is more complete.</p>
<pre class="i_code">

/****************************************************************
 * Program:
 *    Exploration 2, Recurrence
 *    Brother Neff, CS 238
 * Author:
 *    Rodrigo Silveira
 * Summary:
 *    Amortization Program, exploring a practical recurrence relation.
 ***********************************************************************/
#include <cmath>
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <streambuf>
#include <iomanip>
#include <sstream>
#include <vector>
using namespace std;

#include "properties.h"

/***********************************************************************
 * See http://www.drcalculator.com/mortgage/ for one example of an
 * online mortgage calculator that works better in many ways.
 ***********************************************************************/
class Amortize
{
private:
   int reducedTerm;
   int shorterBy;
   float totalPayments;
   float extraPayments;
   float totalInterest;
   float totalSavings;
   float interest;

   double mPrincipal; // principal (p)

   int mTermInMonths; // term in months (n)

   double mRate; // annual interest rate (r)

   double mPeriodicRate; // periodic (monthly) rate (i)

   double mMonthlyPayment; // monthly payment (m)

   double mExtraMonthlyPayment; // extra monthly payment (x)

   bool mShowAmortizationSchedule; // verbose (v)

   int mStart; // extra payment starting month number (s)

   int mEnd; // extra payment ending month number (e)

   bool mHavePrincipal;

   bool mHavePeriodicRate;

   bool mHaveTermInMonths;

   bool mHaveMonthlyPayment;

   /***********************************************************************
    * Find p given i, m, n.
    ***********************************************************************/
   void findPrincipal();

   /***********************************************************************
    * Find i given p, m, n.
    ***********************************************************************/
   void findPeriodicRate();

   /***********************************************************************
    * Find m given p, i, n.
    ***********************************************************************/
   void findMonthlyPayment();

   /***********************************************************************
    * Find n given p, i, m.
    ***********************************************************************/
   void findTermInMonths();

   /***********************************************************************
    * Find all missing parameters.
    ***********************************************************************/
   bool findAll()
   {
      if (!mHavePrincipal &#038;&#038; mHaveMonthlyPayment &#038;&#038;
          mHavePeriodicRate &#038;&#038; mHaveTermInMonths)
      {
         findPrincipal();
         mHavePrincipal = true;
      }
      if (!mHavePeriodicRate &#038;&#038; mHavePrincipal &#038;&#038;
          mHaveMonthlyPayment &#038;&#038; mHaveTermInMonths)
      {
         findPeriodicRate();
         mHavePeriodicRate = true;
      }
      if (!mHaveTermInMonths &#038;&#038; mHavePrincipal &#038;&#038;
          mHaveMonthlyPayment &#038;&#038; mHavePeriodicRate)
      {
         findTermInMonths();
         mHaveTermInMonths = true;
      }
      if (!mHaveMonthlyPayment &#038;&#038; mHavePrincipal &#038;&#038;
          mHavePeriodicRate &#038;&#038; mHaveTermInMonths)
      {
         findMonthlyPayment();
         mHaveMonthlyPayment = true;
      }

      return (mHavePrincipal &#038;&#038; mHaveMonthlyPayment &#038;&#038;
              mHavePeriodicRate &#038;&#038; mHaveTermInMonths);
   }

   bool zeroToBool(int val);
   void findTotalPayments();
   void printAll();
   void printPretty();

public:
   Amortize();
   void run();
};

// DO NOT CHANGE ANYTHING BELOW THIS LINE!

/****************************************************************
 * Main reads command-line argument(s) as follows:
 *
 *  Name of a file containing parameter settings, or
 *  (3 of the following 4 parameters are required)
 *
 *      p= principal (amount loaned)
 *      n= term in months (number of payments)
 *      r= annual interest rate (in percent)
 *      m= monthly payment amount
 *
 *      v= (optional) 1 = view amortization schedule
 *      x= (optional) extra monthly payment
 *      s= (optional) month extra payment starts
 *      e= (optional) month extra payment ends (default = n)
 ****************************************************************/
int main(int argc, char* argv[])
{
//   argc = 2;
//   argv[1] = "C:/Users/Rokko/byui/cs238/exploration2/recurrence/amortize.2";
   if (argc <= 1)
   {
      cout << "Usage: " << argv[0] << " <filename> or
<parameters>" << endl;
      return 0;
   }

   if (argc == 2)
   {
      const char* filename = argv[1];
      string data;
      ifstream ifs(filename, ios_base::in);

      if (ifs)
      {
         while (true)
         {
            ifs >> data;

            if (ifs.eof() || ifs.fail())
            {
               break;
            }
            System.setProperty(data);
         }
         ifs.close();
      }
   }
   else
   {
      for (int i = 1; i < argc; i++)
      {
         string data = argv[i];
         System.setProperty(data);
      }
   }

   Amortize().run();

   return 0;
}

Amortize::Amortize()
{
   mHavePrincipal = System.getProperty("p", "") == "" ? false : true;
   mHavePeriodicRate = System.getProperty("r", "") == "" ? false : true;
   mHaveTermInMonths = System.getProperty("n", "") == "" ? false : true;
   mHaveMonthlyPayment = System.getProperty("m", "") == "" ? false : true;

   mPrincipal = mHavePrincipal ?
      atof(System.getProperty("p", "").c_str()) : 0;

   mTermInMonths = mHaveTermInMonths ?
      atoi(System.getProperty("n", "").c_str()) : 0;

   mRate = mHavePeriodicRate ?
      atof(System.getProperty("r", "").c_str()) : 0;

   mMonthlyPayment = mHaveMonthlyPayment ?
      atof(System.getProperty("m", "").c_str()) : 0;

   mPeriodicRate = mRate / 1200;

   mExtraMonthlyPayment = System.getProperty("x", "") == "" ?
      0 : atof(System.getProperty("x", "").c_str());

   mEnd = System.getProperty("e", "") == "" ?
      mTermInMonths : atof(System.getProperty("e", "").c_str());

   mStart = System.getProperty("s", "") == "" ?
      0 : atof(System.getProperty("s", "").c_str());

   reducedTerm = 0;
   shorterBy = 0;
   totalPayments = 0.0;
   extraPayments = 0.0;
   totalInterest = 0.0;
   totalSavings = 0.0;
   interest = 0.0;
}

void Amortize::run()
{
   findAll();

   //
   // since these values will change in findTotalPayments, let's save
   // them for now, so we can print these original values later (in printPretty)
   //
   double tempPrincipal = mPrincipal;
   int tempTermInMonths = mTermInMonths;
   double tempRate = mRate;
   double tempMonthlyPayment = mMonthlyPayment;
   double tempPeriodicRate = mPeriodicRate;

   findTotalPayments();

   mPrincipal = tempPrincipal;
   mTermInMonths = tempTermInMonths;
   mRate = tempRate;
   mMonthlyPayment = tempMonthlyPayment;
   mPeriodicRate = tempPeriodicRate;

   printPretty();
}

void Amortize::findPrincipal()
{
   // I'm updating the principal in ::findTotalPayments...
}

void Amortize::findPeriodicRate()
{
   if (zeroToBool(mRate))
   {
      mPeriodicRate = mRate / 1200;
      mHavePeriodicRate = true;
   }
}

/**
* c = (rP)/(1-(1+r)^-n)
* r = monthly rate
* P = principal
* n = term (monthly payments)
*/
void Amortize::findMonthlyPayment()
{
   mMonthlyPayment = (mPeriodicRate * mPrincipal) / (1 - pow((1 + mPeriodicRate), -mTermInMonths));
}

void Amortize::findTermInMonths()
{
   mTermInMonths = -log(
         (
            (mPrincipal - (mMonthlyPayment / mPeriodicRate)) /
            (1 - (mMonthlyPayment / mPeriodicRate))
         ) /
         log(1 + mPeriodicRate)
      );
}

/**
 * Wrapper function
 * Just saves a few keystrokes and repetitive conditionals
 */
bool Amortize::zeroToBool(int val)
{
   return val != 0;
}

/**
 * Debug function
 * Prints all the numbers and stuff...
 */
void Amortize::printAll()
{
   cout << "mPrincipal = " << mPrincipal << endl;
   cout << "mHavePrincipal = " << mHavePrincipal << endl;

   cout << "mTermInMonths = " << mTermInMonths << endl;

   cout << "mRate = " << mRate << endl;

   cout << "mPeriodicRate = " << mPeriodicRate << endl;

   cout << "mMonthlyPayment = " << mMonthlyPayment << endl;

   cout << "mExtraMonthlyPayment = " << mExtraMonthlyPayment << endl;

   cout << "mShowAmortizationSchedule = " << mShowAmortizationSchedule << endl;

   cout << "mStart = " << mStart << endl;

   cout << "mEnd = " << mEnd << endl;

   cout << "mHavePeriodicRate = " << mHavePeriodicRate << endl;

   cout << "mHaveTermInMonths = " << mHaveTermInMonths << endl;

   cout << "mHaveMonthlyPayment = " << mHaveMonthlyPayment << endl;
}

void Amortize::printPretty()
{
   cout << endl <<
      "##############################################" << endl << endl;

   cout.precision(2);
   cout << setiosflags(ios::fixed) <<
      "      Principal: " << mPrincipal << endl <<
      "           Term: " << mTermInMonths << " months" << endl;

   cout.precision(3);
   cout <<
      "     Annual Rate " << mRate << "%" << endl;

   cout.precision(7);
   cout <<
      "   Periodic Rate " << mPeriodicRate << endl << endl;

   cout.precision(2);
   cout << setiosflags(ios::fixed) <<

      "Monthly Payment:   " << mMonthlyPayment << endl <<
      "  Extra Payment:   " << mExtraMonthlyPayment << endl << endl;

   cout << "   Reduced Term: " << reducedTerm << " months (shorter by " <<
                              shorterBy << " month(s) = " << (int)(shorterBy/12) <<
                              " year(s) " << shorterBy - ((int)(shorterBy/12) * 12) <<
                              " month(s))" << endl;

   cout << setiosflags(ios::fixed) <<

      " Total Payments: " << totalPayments << endl <<
      " Extra Payments:  " << extraPayments << endl <<
      " Total Interest:  " << totalInterest << endl <<
      "  Total Savings:  " << totalSavings << endl <<
      "  Intrst/Prncpl:  " << interest << "%" << endl;
}

/**
 * This makes monthly payments until the balance goes down to zero.
 * This is done by:
 *    1. Finding amount due for the month
 *    2. Making a monthly payment by first paying towards the interest,
 *       then paying the balance against the principal.
 *    3. Principal is recuded accordingly.
 *
 * Known issues:
 *    This does not take the extra payment flags into account. The
 *    extra payments must start and end on the monts indicated by
 *    the [optional] parameters s and e. This implementation
 *    makes extra payments from month 0 to end whenever x is
 *    present.
 *
 *    This does not calculate:
 *        1. Total Savings
 *        2. Intrst/Prncpl
 *
 * Any questions, contact me at <a href="mailto:rodrixar@gmail.com">rodrixar@gmail.com</a> or txt @ 8015103813
 */
void Amortize::findTotalPayments()
{
   int termsPaid = 0;
   double totalExtraPayments = 0;
   double originalPrincipal = mPrincipal;
   bool donePaying = false;

   while (!donePaying)
   {
      findMonthlyPayment();
      findPeriodicRate();

      double paymentMadeThisMonth = (mMonthlyPayment + mExtraMonthlyPayment) - (mPeriodicRate * mPrincipal);

      if (mPrincipal - paymentMadeThisMonth < 0)
      {
         donePaying = true;
         continue;
      }

      mPrincipal -= paymentMadeThisMonth;

      totalPayments += mMonthlyPayment + mExtraMonthlyPayment;
      termsPaid++;
      totalExtraPayments += mExtraMonthlyPayment;
   }

   reducedTerm = termsPaid;
   shorterBy = mTermInMonths - reducedTerm;
   extraPayments = totalExtraPayments;
   totalInterest = totalPayments - originalPrincipal;
}
</pre>
<h2>Share the love</h2>
<p>If you make further progress before this is due, let me know =) </p>
<div id="crp_related"><h1> Related Posts</h1><p><a href="http://www.rodrigo-silveira.com/cs-238-exploration-2/" rel="bookmark" class="crp_title">CS 238 Exploration 2</a></p><p><a href="http://www.rodrigo-silveira.com/binary-matrix-multiplication/" rel="bookmark" class="crp_title">Binary Matrix Multiplication</a></p><p><a href="http://www.rodrigo-silveira.com/zero-one-matrix-relations/" rel="bookmark" class="crp_title">Zero-one Matrix Relations &raquo; CS238 Exploration 3</a></p><p><a href="http://www.rodrigo-silveira.com/sudoku-solver-algorithm-javascript/" rel="bookmark" class="crp_title">Sudoku Solver Algorithm in JavaScript</a></p><p><a href="http://www.rodrigo-silveira.com/challenge-manipulating-bits/" rel="bookmark" class="crp_title">C Challenge: Manipulating Bits</a></p></div>]]></content:encoded>
			<wfw:commentRss>http://www.rodrigo-silveira.com/cs-238-exploration-2-slight-progress/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>CS 238 Exploration 2</title>
		<link>http://www.rodrigo-silveira.com/cs-238-exploration-2/</link>
		<comments>http://www.rodrigo-silveira.com/cs-238-exploration-2/#comments</comments>
		<pubDate>Thu, 20 Oct 2011 00:02:32 +0000</pubDate>
		<dc:creator>Rodrigo Silveira</dc:creator>
				<category><![CDATA[Articles]]></category>
		<category><![CDATA[C++]]></category>

		<guid isPermaLink="false">http://rodrigo-silveira.com/?p=70</guid>
		<description><![CDATA[My initial post on CS 238's exploration 2. This exploration is all about calculating a home loan, and printing out an amortization schedule. While not as simple as Brother Ercanbrack's CS 213 mortgage calculator apps, this exploration is not nearly as complicated as RSA or most other explorations Brother Neff assigned in Discrete Math 1.]]></description>
			<content:encoded><![CDATA[<p>Hey guys&#8230; Here&#8217;s my code so far. Let me know if you have any questions about it.</p>
<h2>Display Results</h2>
<p>Displays all the numbers in the proper format</p>
<pre class="i_code">void Amortize::displayResults() {
cout &lt;&lt; endl &lt;&lt;
      "##############################################" &lt;&lt; endl &lt;&lt; endl;

   cout.precision(2);
   cout &lt;&lt; setiosflags(ios::fixed) &lt;&lt;
      "      Principal: " &lt;&lt; mPrincipal &lt;&lt; endl &lt;&lt;
      "           Term: " &lt;&lt; mTermInMonths &lt;&lt; " months" &lt;&lt; endl;

   cout.precision(3);
   cout &lt;&lt;
      "     Annual Rate " &lt;&lt; mRate &lt;&lt; "%" &lt;&lt; endl;

   cout.precision(7);
   cout &lt;&lt;
      "   Periodic Rate " &lt;&lt; mPeriodicRate &lt;&lt; endl &lt;&lt; endl;

   cout.precision(2);
   cout &lt;&lt; setiosflags(ios::fixed) &lt;&lt;

      "Monthly Payment:   " &lt;&lt; mMonthlyPayment &lt;&lt; endl &lt;&lt;
      "  Extra Payment:   " &lt;&lt; mExtraMonthlyPayment &lt;&lt; endl &lt;&lt; endl;

   cout &lt;&lt; "   Reduced Term: "
         &lt;&lt; reducedTerm &lt;&lt; " months (shorter by "
         &lt;&lt; shorterBy &lt;&lt; " month(s) = " &lt;&lt; (int)(shorterBy/12)
         &lt;&lt; " year(s) " &lt;&lt; shorterBy - ((int)(shorterBy/12) * 12)
         &lt;&lt; " month(s))" &lt;&lt; endl;

   cout &lt;&lt; setiosflags(ios::fixed) &lt;&lt;

      " Total Payments: " &lt;&lt; totalPayments &lt;&lt; endl &lt;&lt;
      " Extra Payments:   " &lt;&lt; extraPayments &lt;&lt; endl &lt;&lt;
      " Total Interest:   " &lt;&lt; totalInterest &lt;&lt; endl &lt;&lt;
      "  Total Savings:   " &lt;&lt; totalSavings &lt;&lt; endl &lt;&lt;
      "  Intrst/Prncpl:   " &lt;&lt; interest &lt;&lt; "%" &lt;&lt; endl;
}</pre>
<h2>Find Monthly Payments</h2>
<p>Um&#8230; finds the monthly payments&#8230;</p>
<pre class="i_code">/**
* c = (rP)/(1-(1+r)^-n)
* r = monthly rate
* P = principal
* n = term (monthly payments)
*/
void Amortize::findMonthlyPayment()
{
   mMonthlyPayment = (mPeriodicRate * mPrincipal)
                     / (1 - pow((1 + mPeriodicRate), -mTermInMonths));
}</pre>
<h2>Zero to Bool</h2>
<p>A subtle wrapper that converts a string (if the string can be coerced into an int) to bool</p>
<pre class="i_code">bool Amortize::zeroToBool(int val)
{
   return val != 0;
}</pre>
<h2>Find Periodic Rate</h2>
<p>Breaks the APR into the monthly rate</p>
<pre class="i_code">void Amortize::findPeriodicRate()
{
   // returns true if mRate is not zero
   if (zeroToBool(mRate))
   {
      mPeriodicRate = mRate / 1200;
      mHavePeriodicRate = true;
   }
}</pre>
<div id="crp_related"><h1> Related Posts</h1><p><a href="http://www.rodrigo-silveira.com/cs-238-exploration-2-slight-progress/" rel="bookmark" class="crp_title">CS 238 Exploration 2 &#8211; Slight Progress</a></p><p><a href="http://www.rodrigo-silveira.com/binary-matrix-multiplication/" rel="bookmark" class="crp_title">Binary Matrix Multiplication</a></p><p><a href="http://www.rodrigo-silveira.com/zero-one-matrix-relations/" rel="bookmark" class="crp_title">Zero-one Matrix Relations &raquo; CS238 Exploration 3</a></p><p><a href="http://www.rodrigo-silveira.com/sudoku-solver-algorithm-javascript/" rel="bookmark" class="crp_title">Sudoku Solver Algorithm in JavaScript</a></p><p><a href="http://www.rodrigo-silveira.com/html5-stock-market-simulation-php/" rel="bookmark" class="crp_title">HTML5 Stock Market Simulation in PHP</a></p></div>]]></content:encoded>
			<wfw:commentRss>http://www.rodrigo-silveira.com/cs-238-exploration-2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

<!-- www.000webhost.com Analytics Code -->
<script type="text/javascript" src="http://analytics.hosting24.com/count.php"></script>
<noscript><a href="http://www.hosting24.com/"><img src="http://analytics.hosting24.com/count.php" alt="web hosting" /></a></noscript>
<!-- End Of Analytics Code -->

<!-- Performance optimized by W3 Total Cache. Learn more: http://www.w3-edge.com/wordpress-plugins/

Minified using disk: basic
Page Caching using disk: enhanced
Database Caching 1/27 queries in 0.150 seconds using disk: basic
Object Caching 1442/1472 objects using disk: basic

Served from: www.rodrigo-silveira.com @ 2012-02-23 04:34:30 -->
