Tuesday, December 8, 2009

Finding a Path Algorithm - Driver Program

The following (and the 3-4 posts before) is an incomplete, not-working-quite-right program I wrote in the equivalent of a CMPT 306 class while at Snow; just tossing it up here to get some feedback on it. Take a gander if ya like, though it's not my best work...

/*
Title: Programming Project 5 - Maze and Creature
Author: Daniel J. Tanner
Class: CS 2420 - Data Abstraction & Problem Solving w/ C++
Date: October 17th, 2005 (latest update)
*/

#include
#include
#include
#include "TannMaze.h"
#include "TannCreature.h"
#include
using namespace std;

//function declarations
void displayGreeting();

int main()
{
displayGreeting();

//set variables
Coord start, end;
int width, height;
char choice;
string filename;
TannMaze basicMaze;
TannCreature bob;
bool success;

//Find out if user has a file he'd like to use or if he'd like to
//manually input the data
cout << "Would you like to get the data from a file?:(y/n) "; cin >> choice;
if(toupper(choice) != 'Y')
{
//get width and height
cout << "input the width: "; cin >> width;
cout << "input the height: "; cin >> height;

//get start and exit
cout << "Please enter the coordinates for the entrance of your\n" << "maze in the form (x y): "; cin >> start.x >> start.y;
cout << "Do the same for the exit: "; cin >> end.x >> end.y;

//adjust for proper array usage
start.x--; start.y--;
end.x--; end.y--;

//generate maze
basicMaze.generateMaze(width, height, start, end);
}
else
{
//get filename
cout << "Please input the name of your file, including the extension: "; cin >> filename;

//generate maze based on file
basicMaze.generateMaze(filename);
}

//create a creature and have it go through the maze after displaying it
cout << "Your maze appears as follows: \n\n";
basicMaze.displayMaze();
cout << endl;
bob.setMaze(basicMaze);

//show the solution to the maze:
cout << "The solution to your maze is as follows: \n\n";
success = bob.findExit();
if(!success)
cout << "Unfortunately your maze is unsolveable.\n\n";
else
{
basicMaze.displayMaze();
cout << endl << endl;
}


return 0;
}

void displayGreeting()
{
cout << "Greetings! This program will generate a maze and provide a solution\n"
<< "should there be one. You can tell the program the width and height\n"
<< "yourself or you can open a file that you've already input the data\n"
<< "into.\n\n";
}

Finding a Path - Creature Class Definition

/*
Title: Creature Class Function Definitions
Author: Daniel J. Tanner
Class: CS 2420 - Data Abstraction & Problem Solving w/ C++
Date: October 17th, 2005 (latest update)
*/

#include
#include
#include
#include "TannCreature.h"
using namespace std;

//Function definitions

/* Default Constructor
Sets the creature to (0,0) and makes the maze pointer point to NULL
*/
TannCreature::TannCreature()
{
position_.y = 0; position_.x = 0;
maze_ = NULL;
}

/* Explicit value constructor
Purpose: This functions will take a maze as a parameter and set the position
of the creature to the start of the maze
Rec./Ref: an instance of the maze class
*/
TannCreature::TannCreature(TannMaze &maze)
{
maze_ = &maze;
position_ = maze.getStart();
}

/* set function
Purpose: this function will do the same as the explicit value constructor, but
will allow it to be done after initialization
*/
void TannCreature::setMaze(TannMaze &maze)
{
maze_ = &maze;
position_ = maze.getStart();
}

/* findExit function
Purpose: This function will begin a set of recursive calls that will take the
creature from the start to the end if possible. It will return a bool
representing success or failure.
Return: bool representing success or failure
*/
bool TannCreature::findExit()
{
//Book problem had a way to have start and end at same point but this program
//doesn't, so it does not make a check to see if the start is the end
if(goNorth())
return true;
else if(goWest())
return true;
else if(goEast())
return true;
else
return false;
}

/* movement functions
Purpose: These functions will move the creature north, west, south, or east,
and return a bool representing success or failure. failure is when
the move north is blocked by a wall or is not inside the maze
If the creature can move in a specified direction, it marks the new
space as path...if it has to backtrack, it marks the space as 'visited'
Return: A bool representing success or failure
*/
//move North function
bool TannCreature::goNorth()
{
if(position_.y - 1 > 0
&& maze_->checkCoord(position_.x, position_.y - 1) != WALL
&& maze_->checkCoord(position_.x, position_.y - 1) != VISITED)
{
position_.y--;
if(maze_->checkCoord(position_.x, position_.y) == EXIT)
return true;
else
{
maze_->mark(position_, PATH);
if(goNorth())
return true;
else if(goWest())
return true;
else if(goEast())
return true;
else
{
maze_->mark(position_, VISITED);
position_.y++;
return false;
}
}
}
else
return false;
}

//move West function
bool TannCreature::goWest()
{
if(position_.x - 1 > 0
&& maze_->checkCoord(position_.x - 1, position_.y) != WALL
&& maze_->checkCoord(position_.x - 1, position_.y) != VISITED)
{
position_.x--;
if(maze_->checkCoord(position_.x, position_.y) == EXIT)
return true;
else
{
maze_->mark(position_, PATH);
if(goNorth())
return true;
else if(goWest())
return true;
else if(goSouth())
return true;
else
{
maze_->mark(position_, VISITED);
position_.x++;
return false;
}
}
}
else
return false;
}

//move East Function
bool TannCreature::goEast()
{
if(position_.x + 1 <>getWidth()
&& maze_->checkCoord(position_.x + 1, position_.y) != WALL
&& maze_->checkCoord(position_.x + 1, position_.y) != VISITED)
{
position_.x++;
if(maze_->checkCoord(position_.x, position_.y) == EXIT)
return true;
else
{
maze_->mark(position_, PATH);
if(goNorth())
return true;
else if(goEast())
return true;
else if(goSouth())
return true;
else
{
maze_->mark(position_, VISITED);
position_.x--;
return false;
}
}
}
else
return false;
}

//move South Function
bool TannCreature::goSouth()
{
if(position_.y + 1 <>getHeight()
&& maze_->checkCoord(position_.x, position_.y + 1) != WALL
&& maze_->checkCoord(position_.x, position_.y + 1) != VISITED)
{
position_.y++;
if(maze_->checkCoord(position_.x, position_.y) == EXIT)
return true;
else
{
maze_->mark(position_, PATH);
if(goWest())
return true;
else if(goEast())
return true;
else if(goSouth())
return true;
else
{
maze_->mark(position_, VISITED);
position_.y--;
return false;
}
}
}
else
return false;
}

Finding a Path Algorithm - Maze Class Definition

/*
Title: Maze Class Function Definitions
Author: Daniel J. Tanner
Class: CS 2420 - Data Abstraction & Problem Solving w/ C++
Date: October 17th, 2005 (latest update)
*/

#include
#include
#include
#include
#include
#include
#include "TannMaze.h"
using namespace std;

//Maze Class Definitions
//Destructor
TannMaze::~TannMaze()
{
delete [] maze;
}

//Constructors
/* Default
Purpose : This constructor will simply create an instance of the Maze
class
and have the 2-d array pointer point to null
Rec./Ref.: N/A
*/
TannMaze::TannMaze()
{
try
{
mazeHeight_ = 5; mazeWidth_ = 5;
start_.x = 2; start_.y = 4;
end_.x = 2; end_.y = 0;
generateMaze();
}
catch(MazeError error)
{throw(error);}
}

/* Explicit Value Constructor
Purpose: To accept from the user a height, a width, and a start and an end
and then to redirect this information to the generateMaze function
Rec.: height, width, start coord and end coord
Call: function generateMaze(height, width, start, end)
*/
TannMaze::TannMaze(int width, int height, Coord &start, Coord &end)
{
cout << "using explicit input constructor to generate maze..." << endl;
try
{
generateMaze(width, height, start, end);
}
catch(MazeError error){throw error;}
}

/* Filename Constructor
Purpose: This constructor will redirect the program to the generateMaze
function that deals with files directly
Rec/Ref: the filename of the file that will be opened and read from
Send: that same filename to the appropriate maze generator function
*/
TannMaze::TannMaze(string filename)
{
try{
generateMaze(filename);
}
catch(MazeError error)
{
throw(error);
}
}

//Maze generation functions
/* Explicit Value Maze Generator
This function will set all the different variables at once and then redirect
the program to the default generateMaze function
*/
void TannMaze::generateMaze(int width, int height, Coord &start, Coord &end)
{
mazeHeight_ = height; mazeWidth_ = width; start_ = start; end_ = end;
try{generateMaze();}
catch(MazeError error)
{ throw(error);}
}

/* Explicit Value (from file) Maze Generator
This function will set all the variables based on a file as described by the
problem definition in the book
*/
void TannMaze::generateMaze(string filename)
{
fstream fileIn(filename.c_str());
if(!fileIn)
throw MazeError("Error opening file " + filename);
int height, width;
Coord start, end;
fileIn >> width >> height >> end.x >> end.y >> start.x >> start.y;
mazeHeight_ = height; mazeWidth_ = width; start_ = start; end_ = end;
try{generateMaze();}
catch(MazeError error)
{ throw(error);}
}



/* Default Maze Generator
This is THE main maze generator function
Purpose: To generate a 2-dimensional array-based maze made up of ascii
characters, and then randomly fill it with walls and open spaces
along with a specific startpoint and a specific endpoint.
Precondition: The height, width, start, and end variables must have already
been assigned to the class' variables for this to work
correctly
it is therefore only able to be called by member functions which
already assign those properties.
*/
void TannMaze::generateMaze()
{
//create the 2d array, throwing an error if there's not enough memory
try
{
maze = new mazeSquare*[mazeWidth_];
for(int index = 0; index < mazeWidth_; index++)
maze[index] = new mazeSquare[mazeHeight_];
}
catch(bad_alloc error) {throw MazeError("Error allocating memory");}

//set up random number generator to be based off current time
srand(unsigned(time(NULL)));

//fill the maze with squares of either WALL or CLEAR
for(int heightCount = 0; heightCount < mazeHeight_; heightCount++)
{
for(int widthCount = 0; widthCount < mazeWidth_; widthCount++)
{
switch(rand() % 2)
{
case 0:
maze[widthCount][heightCount] = WALL;
break;
case 1:
maze[widthCount][heightCount] = CLEAR;
break;
}
}
}

//set the start and end
maze[start_.x][start_.y] = START;
maze[end_.x][end_.y] = EXIT;
}

void TannMaze::displayMaze()const
{
for(int hIndex = 0; hIndex < mazeHeight_; hIndex++)
{
for(int wIndex = 0; wIndex < mazeWidth_; wIndex++)
{
switch(maze[wIndex][hIndex])
{
case WALL:
cout << 'X';
break;
case CLEAR:
cout << ' ';
break;
case EXIT:
cout << 'E';
break;
case START:
cout << 'S';
break;
case PATH:
cout << '@';
break;
case VISITED:
cout << '*';
break;
default:
break;
}
}
cout << endl;
}
}

/* Mark Function
Purpose: This function will change the status of one maze square to visited or to path
Rec.: the location of the square as a coord, and the new status
*/
void TannMaze::mark(const Coord &sqLoc, enum mazeSquare demarcation)
{
maze[sqLoc.x][sqLoc.y] = demarcation;
}

Finding a Path algorithm - Maze Class Declaration

/*
Title: Maze Class Declaration
Author: Daniel J. Tanner
Class: CS 2420 - Data Abstraction & Problem Solving w/ C++
Date: October 17th, 2005 (latest update)
*/

#ifndef TANNMAZE_H
#define TANNMAZE_H

/*This maze will be made up of several individual squares (represented by
characters).
C = a clear space the creature can walk thru
P = the correct path as travelled by the creature from the entrance to the
exit
X = exit of maze
W = a wall that the creature cannot walk through.
S = start of maze
V = a clear space that the creature has visited, but lead to a dead end.
*/

#include
#include
#include
#include
#include
using namespace std;

//Define enumerated data type for squares
enum mazeSquare{CLEAR, WALL, EXIT, START, PATH, VISITED};

//Special structure for handling incoming and outgoing squares
struct Coord
{
int x, y;
};

//Class TannMaze Declaration
class TannMaze
{
private:
mazeSquare **maze;
int mazeHeight_;
int mazeWidth_;
Coord start_;
Coord end_;

public:
//Error class
class MazeError
{
private:
string problem_;
public:
MazeError(string problem) {problem_ = problem;}
string getProblem() {return problem_;}
};

void mark(const Coord &sqLoc, mazeSquare demarcation);
void displayMaze()const;

//inline get & set functions
int getHeight()const {return mazeHeight_;}
int getWidth()const {return mazeWidth_;}
Coord getStart()const {return start_;}
Coord getEnd()const {return end_;}
mazeSquare checkCoord(int y, int x) {return maze[y][x];}
void setStart(Coord &start) {start_ = start;}
void setEnd(Coord &end) {end_ = end;}
void setHeight(int height) {mazeHeight_ = height;}
void setWidth(int width) {mazeWidth_ = width;}

//Maze Generator functions
void generateMaze(int width, int height, Coord &start, Coord &end);
void generateMaze(string filename);
void generateMaze();

//Constructors
TannMaze();
TannMaze(int width, int height, Coord &start, Coord &end);
TannMaze(string filename);

//Destructor
~TannMaze();
};

#endif

Finding a path algorithm - Creature Class Declaration

/*
Title: Creature Class Declaration
Author: Daniel J. Tanner
Class: CS 2420 - Data Abstraction & Problem Solving w/ C++
Date: October 17th, 2005 (latest update)
*/

#include
#include
#include
#include "TannMaze.h"
using namespace std;

//Class declaration
class TannCreature
{
private:
Coord position_;
TannMaze *maze_;
bool goNorth();
bool goSouth();
bool goWest();
bool goEast();

public:
TannCreature();
TannCreature(TannMaze &maze);
void setMaze(TannMaze &maze);
bool findExit();
};

Tuesday, December 1, 2009

Analytical Report on 5 Topics from Speech Class

The following is an analytical report I had to write for my speech class, covering 5 things over 5 pages we studied in class and my opinions/experience with them. Some of it may be kind of common sense stuff and thus rather boring, but lemme know what ye webonauts out there think via comments.

Maslow’s Heirarchy of Needs – The Boomerang Effect

Among the more interesting concepts discussed in our Speech class this semester was “The Boomerang Effect.” This is, basically, a turnaround of a person’s opinion after they have given deeper thought to something they were convinced of earlier on a Peripheral basis. (Peripheral referring to quick-response decisions made when offered reciprocation, consistency, social proof, etc). In my own experiences I have seen and heard many such peripheral persuasions, and my own sense of pride makes me prejudice any argument presented this way, especially after I have agreed to do something based on said agreements. For example, whenever my elder sister asks me for some favor or another (such as recently when she got me to drive her dryer down to a shop to get fixed and back up to her apartment) by way of a “guilt trip” (usually suggesting she’d get my father to carry out said errand, even at the risk of possible injury), I usually find myself resenting her for it. So, yes, the boomerang effect is a real psychological aftereffect.









“It’s For The Children!!” And Other Appeals to Emotion – Logical Fallacy?

Prior to presenting persuasive speeches, we went over a variety of logical fallacies to avoid in making arguments, and while “Appeal to Emotion” isn’t technically a logical fallacy per se, I think it fits in a bit with what we were just discussing (Boomerang Effect) and is thus, well, kind of a logical fallacy. While I can not speak for others, when I hear politicians on television or the internet making arguments based around emotionalism (usually accompanied by a little bit of exaggerated hyperbole) I find myself discouraged from listening to whatever otherwise logical arguments they were trying to make to support a given course of action. A good example of this in recent memory is found in the healthcare debate, where many politicians are using an ever-changing number of “millions of people” who are uninsured as a reason to further regulate hospitals, doctors, and related insurance companies. While it is not necessarily a logical fallacy to point out a societal problem and ask for empathy on behalf of the afflicted, it is at the least distasteful to use the existence of said problem as a reason to “do something.” So, again, while appeal to emotion is not a logical fallacy in and of itself, I think it is fair to say that it could cause a boomerang effect in an audience and is inadvisable, or at least merits careful thought before using.






On Powerpoint Usage – Keep It Simple!

When presenting a speech on a given topic we were advised against using very complex and fancy powerpoints; advice which in my experience is right on the money. A recent project I was doing for my Corporate Finance class required a powerpoint to accompany a ten minute presentation on whether or not starting a software development company was a worthwhile investment. How lucky I was to be in Speech class at the same time! Where many of my classmates had used a wide variety of colors in their powerpoints, and images that often obscured the spreadsheets and numerical figures which were supposed to be the meat of the research; my partner and I had a simple, straight-to-the-point set of slides to get across our main points. While the grades have yet to come in I am reasonably confident that we probably scored fairly well overall, and likely got full points for the powerpoint. Therefore, I have to agree with the book and lectures on powerpoint presentations, that conciseness and clarity are far more important than boisterous effects and fashionista design.









Cultivation Theory – How Accurate Are Our “Informed” Perceptions?

Do TV and the Internet present an accurate image of the world around us? Most of us would likely agree that television and movies give people over-exaggerated perceptions of the kinds of physical beauty and intelligence they should expect in potential mates, for starters. Certainly not every guy has as clean a face as Brad Pitt and certainly not all women are as curvaceous as Angelina Jolie, yet I wonder how many marriages have been broken because one spouse or the other thinks not only that they can find someone better, but that they deserve someone better than whomever they are currently paired with? I have personally seen such “entitled” behavior present in my sisters and female cousins (granted, their chosen beaus are often rather unimpressive individuals…perhaps that is only my own twisted perceptions speaking, though), where they always seem to think that “the grass is greener” someplace or with someone else.
Of course, looks are not the only things that are perceived improperly; I doubt you would find it surprising that a number of political positions held by a number of people are often misrepresented on a daily basis. It almost seems that the more fallacious an argument, the more news coverage it gets. As a for instance, a strong memory of mine is scenes of people pulling cots and mattresses into the House of Representatives back in the middle of the nineties, when Clinton, the president at the time, was vetoing and trying to shut out Republicans from important budget votes. I can not tell you how many people I have run into who credit Clinton with the budget and the net surplus that was arrived at as a result of that moment in history. Then again, maybe it is I who have been given “a spin” on that particular bit of history.

Uses and Gratification Theory

How easy is it to close your ears, hum to yourself, and ignore everything you do not want to hear, only paying attention to the sources you want to listen to? Far too easy, according to our Speech textbook. The idea that people in this day and age who use social media on the internet tend to close their circle off to other points of view is certainly easy to imagine. And surely, there is a bubble I could lock myself into on the net. Take twitter, for example, the much-maligned 140-word-limit social media service. There exists a way of “tweeting” to a certain set of individuals and only that certain set, and you can block and ignore anyone who would say something you do not want to hear. In particular, there’s a “channel” of sorts on twitter known as “#p2” which is full of people who generally hold ‘liberal’ points of view… and a channel called “#tcot” typically representing the opposing side. So here we have two bubbles of mutually exclusive groups and a method available to tune out opposing sides. Does this happen in practice? Surprisingly, no. You see, internet communication has a long history of “trolling,” “flame wars,” and “baiting” in which people go online with the sole purpose of debating people on the other side, either to ridicule them by baiting them into an argument where they look foolish, or to ‘win’ an argument, thus showing off supposed intellectual fortitude. All in all, I think this meme-like behavior will prevent social media users to ever completely cordon themselves off (though some certainly give a good effort).

Wednesday, November 25, 2009

Pondering Manufacturing

For whatever reason I was reflecting this afternoon on a conversation I had awhile back with a friend of the family about manufacturing, quality of goods, and long-term profit seeking vs short-term profit seeking vs liberal ideas. I know, that was a long winded list, but bear with me here.

What got the conversation started was the usual complaint about this or that manufactured diddy from Wal-Mart breaking before you get it out of the store (in this case a plastic attache case thingamajigger whose handle broke off on the way to the checkout line from its own weight). My friend and I both agreed that businesses interested in long term profits have to strike some balance between replaceable goods (so as to have repeat business) and durable, quality goods (so as to make people want said goods in the first place). This is the reason behind the oft-heard "they don't make things like they used to" ... because the companies that made a product that'd last forever didn't have repeat customers.

Which gets me wondering something else...the "green push," so to speak, on manufactured goods is to make things out of materials that decompose quickly, which inevitably leads to deficiencies in terms of durability and reliability. However, what's more environmentally damaging I wonder? Having to change out your appliances and furniture every 5-10 years or having appliances and furniture that last almost or more than the average lifetime? In the first case you have lots and lots and lots of trash (and increasingly more so as population increases) while in the second you still have an increasing number of items to dispose of as population grows, but I should think the rate of growth / population would grow logarithmically instead of exponentially. So, which is better?

Given these two factors, it's only natural that companies, hoping to a) maintain high PR (vis-a-vis being "greener" than the competition) and b) establish a more recurrent need for their product in the market (repeat customers) tend to produce low-quality goods out of quick-decomposition materials. Given the logical conclusion of exponentially more trash to deal with in the future because of these choices, are "environmentalists" really helping the environment with this?

Update 1: Something else relevant that strikes a nerve...all these "I'd Tap That" signs I'm seeing on campus. Wasn't it the environmentalists/nanny staters that got everyone in crisis mode over the pollutants in tap water in the first place, which lead to mass production and popularity of bottled water? More evidence of environmentalism hurting the environment/ecology more than helping it.

Friday, November 20, 2009

On Real Values (Or, Why I Think Stock Has No Intrinsic Value)

Basic economics says that every item has some "real" value to it based first on a concept called utility value. Second, it has increased or decreased value based on scarcity (supply). Third, it has increased or decreased value based on the various subjective views of the population about said item (demand). I think we can all agree that these are the basic factors surrounding any item.

It is also of note that classic liberal economic theory assumes that the first concept above (what we might call intrinsic, 'real' value) applies to any/all manufactured good and is widely recognized by any/all given populations (IE, build it and they will come, a supply creates its own demand) which is usually true but not always (and the theory is thus 'false' by predicative logical standards).

Why do I mention this when by the title I clearly wanna talk about stock? Because stock is that rare thing which has absolutely no intrinsic value by the virtues of its own existence. That is, the only reason people value it, is because they think they can convince someone else that it's worth more than its current market value (IE they think its 'value' is going to rise amongst the population at large). I should admit, though, that just as a half eaten hot dog has increased value if the other half is in some celebrity's stomach, there is _some_ intrinsic value to owning some nth of a company simply because it's an nth of a certain company (which may have a bit of a celebrity status of its own). And, obviously, owning a large percentage of a company enough to exert influence on the company, and/or stock with regular dividends have their own intrinsic values. But, I digress.

My main point is that, the idea of buying something ONLY because you think you can turn around and sell it to someone else for a higher price especially when said good is pretty much intangible in and of itself... is fundamentally flawed. And, I wonder if, if we didn't have people messing around with stuff like this (especially the derivatives market) the free market would be totally stable?

If you're wondering what got me thinking about this it's Warren Buffet, and a discussion in our business finance class about his idea that a good company never gives their shareholders dividends... I would argue that the idea of holding onto stock (no matter how high the 'value' goes) solely for the purpose of seeing the value increase is patently absurd. Because, again, if the stock is only serving as a better way to store money than ... well, money... what's the point? I mean, sure, you could make oodles of cash, but Buffet's company is strictly nonproductive, only ever redistributing money and capital in the economy, and usually not in the sense of initial investments. I come back to wondering, what is the stock really worth at that point? It's never going to be a controlling interest in the company (in fact, B stocks from Buffet's company can't EVER have voting rights), and the company itself has a relatively low intrinsic value (compare to a company that manufactures something) so the stock has basically none. I dunno, economists out there, am I making sense or am I off my rocker?

Wednesday, November 11, 2009

Some Scary Stuff Out There In The World

Now, while I don't typically put much salt into the typical government conspiracy paranoia, this stuff about swine flu vaccinations containing live avian flu is... concerning. Add in the fact that Obama announced swine flu a national emergency just recently, despite mounting skepticism about its seriousness. Remember, take this stuff with a grain of salt, but still, be a little concerned:

Tuesday, November 10, 2009

Function to Print A Value's Bit Representation in Hex (by Casting as an Unsigned Int) in C

void printHex(int someInt)
{
unsigned int temp;
for(temp = (someInt); temp != 0; temp /= 16)
if(temp % 16 <>= 0)
printf("%d", temp % 16);
else
{
switch(temp % 16)
{
case 10:
putchar('A');
break;
case 11:
putchar('B');
break;
case 12:
putchar('C');
break;
case 13:
putchar('D');
break;
case 14:
putchar('E');
break;
case 15:
putchar('F');
break;
}
}
}

Function for Printing An Item in Binary (Will Print in Little Endian) in C

void printBits(int someInt)
{
int counter, mask;

//Loop through the bits 1 by 1, putting out a 1 for every 1 encountered and a 0 for every 1 encountered
for(counter=1, mask=1; counter <= sizeof(int) * CHAR_BIT; counter++, mask*=2)
{
putchar(((someInt & mask)==0) ? '0' : '1');

//Put spaces between every 8 bits
if(counter != 0 && counter % (CHAR_BIT) == 0 && counter <= (sizeof(int) * CHAR_BIT))
putchar(' ');
}
printf("\n\n");
}

Function for Finding the Modulo of A Polynomial Without Having to Worry About Exponents

function modulo = modWOExp(a, n, z)
modulo = 1;
x = intDivision(a, z);
while n > 0
mod2 = intDivision(n, 2);
if mod2(2) == 1
modulo = modulo * x(2);
modZ = intDivision(modulo, z);
modulo = modZ(2);
end
mod2(1) = x(2) * x(2);
x = intDivision(mod2(1), z);
someTemp = intdivision(n, 2);
n = someTemp(1);
end

GCDPlus Function (Returns s & t for function gcd = sa + tb)

function sAndT = gcdPlus(a, b)
if a < b
temp = a;
a = b;
b = temp;
end
if b == 0
sAndT(1) = 1;
sAndT(2) = 0;
return;
end
q = intDivision(a, b);
r = q(2);
sAndTPrime = gcdPlus(b, r);
sAndT(1) = sAndTPrime(2);
sAndT(2) = sAndTPrime(1) - sAndTPrime(2) * q(1);
return;

Thursday, November 5, 2009

An Algorithm to Find the Greatest Common Divisor (Non-Recursive) (Very Inefficient)

function greatestCommonDivisor = greatestCommonDivisor(num1, num2)
facNum1 = factor(num1);
facNum2 = factor(num2);
index1 = 1;
index2 = 1;
greatestCommonDivisor = 1;
if facNum1(index1) == facNum2(index2)
greatestCommonDivisor = greatestCommonDivisor * facNum1(index1);
facNum2(index2) = 1;
end
index1 = 2;
index2 = 2;
while index1 <= length(facNum1) - 1
while index2 <= length(facNum2) - 1 && facNum1(index1) ~= facNum2(index2)
index2 = index2 + 1;
end
if facNum1(index1) == facNum2(index2)
greatestCommonDivisor = greatestCommonDivisor * facNum2(index2);
facNum2(index2) = 1;
end
index1 = index1 + 1;
end

Oh My Stars and Garters

Over at Maggie's Farm they're tossing up oooooold predictions of "technology of tomorrow" type stuff. I remember seeing/watching the same kind of thing when I was a kid (albeit the stuff I watched was more flying cars and giant holograms / circa 1990s don'cha'know). Still, amazing to see how far off the mark predictions can be, or how close to the future they can be.
(H/T Captain Capitalism)

Still, kinda makes me wonder, with the increasing amounts of red tape and gov't bureaucracy involved in getting patent rights these days (and the increasing amount of frivolousness allowed with some patents)... I wonder what, if any, future technology is gonna come about by, say, 2050. Obviously the incremental decrease in size of transistors and increasing use of high speed fiber-optic technologies are going to continue, but what about entirely new devices, or ways of doing things?

Don't really want to sink into paranoia (oh noes, net neutrality!) but I think the looks of things in a general sense leave me somewhat cynical, at least to a certain extent. Will say the allosphere project looks damn cool, though. On second thought, maybe I'm not all that pessimistic that technology will advance, but I am pessimistic about the pace. C'mon people, let's get our priorities straight: Socialism in the name of helping the poor (and ultimately only increasing the # of poor) or eliminating the corporate tax and letting the sky be the limit on technological investment and innovation?

Factorization Algorithm in MATLAB

function factor = factor(number)
factor(1) = 0;
tempVal = number;
numFactors = 0;
divisor = 2;
modulo = intDivision(tempVal, divisor);
while isPrime(tempVal) == 0
while modulo(2) > 0
divisor = divisor + 1;
modulo = intDivision(tempVal, divisor);
end
if modulo(2) == 0
numFactors = numFactors + 1;
factor(numFactors) = divisor;
tempVal = modulo(1);
modulo = intDivision(tempVal, divisor);
end
end
numFactors = numFactors + 1;
factor(numFactors) = tempVal;

IsPrime Implemented in MATLAB (Using IntDivision Implementation)

function isPrime = isPrime(number)
if number == 2 %base case
isPrime = 1;
return;
end

divisor = 2;
modulo = intDivision(number, divisor);
while modulo(2) > 0 && divisor <= sqrt(number)
divisor = divisor + 1;
modulo = intDivision(number, divisor);
end
if modulo(2) > 0
isPrime = 1;
return;
end
isPrime = 0;
return;

Algorithm Which Returns the Next Prime After the Number Entered

function nextPrime = nextPrime(number)
number = number + 1;
while isPrime(number) == 0
number = number + 1;
end
nextPrime = number;

An Algorithm For Dividing Integers (Returning the Quotient and the Remainder) in MATLAB

function quotient = intDivision(dividend, divisor)
if divisor > dividend
quotient = [0, dividend];
return;
end
if divisor == 0
quotient = [0, 0];
return;
end
counter = 0;
tempVal = 0;
while tempVal <= dividend
tempVal = tempVal + divisor;
counter = counter + 1;
end
if tempVal == dividend
quotient = [counter, 0];
return;
end
tempVal = tempVal - divisor;
quotient = [counter - 1, dividend - tempVal];

Wednesday, November 4, 2009

Binary Morality and other Religious Quandaries

So, I had a conversation the other day with one of my classmates about religion and the way we view morality; both of us are in a discrete math class and we came up with a few basic axioms of religion we figured were mutually exclusive (that is, only one can be true):

A) There is one and only one God
B) There are many gods
C) There is no god

Here we would likely define the "kami" of Shintoism and the boddhisatvas of Buddhism as a religion favoring the many gods axiom (as well as similar beliefs).

As much as everyone would like to be accepting or tolerant, this is kind of the way it is: By believing in any particular religion you are accepting the premise that people who don't believe the same way you do about one of the basic axioms are wrong.

Settling that, we started talking about pretty nebulous ideas like justice, mercy, and morality in general. We were mostly talking about Protestantism vs LDS beliefs (since my classmate is LDS and I'm a Protestant with LDS uncles, aunts, and cousins). In talking about the idea of justice, I put forth the idea that justice as we see it is entirely subjective; that is, we see a theft and we judge that a relatively short term of imprisonment is payment enough, but the rape and murder of a child deserves life imprisonment or capital punishment: death.

Now, again this is entirely subjective because, at least in my understanding of the Bible, God sees sin simply as a sin. It has neither a gradient nor is it cumulative. All of that comes down to a premise of mine about the way God looks at things. I think if we think of it in binary terms (1 is clean of sin, 0 is sinful), you can only attain '1' by either accepting Jesus as your savior, or by being Jewish and practicing the cleansing rituals. If we further pontificate on the verses about man being inherently imperfect and the flesh being naturally tempted toward sin, it stands to reason that '0' is the default state; and everyone under completely "fair and just" circumstances deserves to go to Hell (or whatever you wanna call your local burning pit of eternal torment). Me included.

Now when it comes to the idea of justice and mercy, my classmate was saying that you cannot receive mercy from the same entity/being as you would have received justice; that there has to be a third party for God to be "eternally unchanging." And here we went into a friendly debate about the nature of the Trinity (which is one of the main rift points between LDS and other Christians, a big enough point IMO to disinclude LDS as one of the sects of Christianity).

From my interpretation, the trinity is a set of 3 different manifestations of the same being. "The Father" is sort of the general-purpose manifestation that we envision ourselves praying to, that we think of as being on a golden throne in heaven, etc etc yada yada yada. "The Son" is Jesus, the savior, the messiah, the one we think of as lending the merciful hand (some people would even envision him as the defense attorney on our behalf before the Father in some place of ultimate judgement). Last is "The Holy Ghost/Spirit" which is how some envision the conscience, that which nudges us in the right direction when we come to a moral decision (though I think of my own conscience as something separate, and the Holy Ghost is more, God acting as the universal hint system). But anyway, all three manifestations are just our own vision or idea about how things are, like looking at a C++ or Java implementation when what's in Assembly (or even just binary machine language) tells a slightly different story. All 3 are really the same entity.

As for how my classmate interpreted it, it goes back to the argument about God (The Father) being unchanging and incapable of offering Justice and Mercy at the same time; thereby necessitating a third party in the form of Jesus Christ, who under this understanding must be seen as a separate entity than The Father.

Well, if I misunderstood any of that (classmate who may or may not read this) feel free to correct me; and I'd love to hear others' opinions on the matter in the comments.

Tuesday, November 3, 2009

Since It's Election Day...

It calls for some Alice Cooper:

A Discussion on Labels

So, checking out Gadfly's site and I came across some interesting ideas from Conservative Wahoo about coining "neo-socialism" as a term to describe the Obama administration's leanings.

I think the main problem I have with the phrase is that it's suggesting that A) Obama has really thought out his positions in a meaningful way, and B) this administrations ideas ARE new which is something of a fallacy.

Addressing point A, the impression that I've gotten from Obama, from the very beginning was that he was a political opportunist, above all else. This is perhaps why Edward Kennedy (black spot on the Kennedy name as he is/was) endorsed him, maybe sensing a kinship in the lack of a real philosophical foundation upon which to base his politics. The kind of people he associates/d himself with are not just left-leaning radicals, they are also corrupt in every sense of the word (Blago, Rezko, even the scams that went on where Michelle O worked. I'm not saying he's not pursuing socialist-style philosophies, but rather, it's not clear that he's philosophically motivated in the first place. It is therefore a case of jumping the gun to coin a term to define the philosophy backing his policies.

To address point B, I'll go back to the fallacy we were indoctrinated into believing in high school economics and US history, as well as what I've seen in college economics classes. That is, that Karl Marx and John Maynard Keynes presented ideas which were new and untried. If we go back to the "age of enlightenment" in 1700s France we find the same basic ideas from the likes of Rousseau and before that, back to the Greek philosophers you have some branches of stoicism relating much the same ideas. As far as policies based on political philosophies, a lot of the considerations about a federally controlled national bank issuing money and purposefully inflating it have been tried throughout history; by the Khans during their control of China; by the French (again under absolutism in the 1700s) and even a bit of the same under the era of Mercantilism by the British and the Dutch. I could go on but I think you get my drift: Obama's ideas, much the same as Marx's, are not in any sense new. They've been tried by many people in many places in many eras, and have never worked. Period. Constantly trying to reinvent the wheel is not going to lead to major progress (another word relating back to another group of people who tried and failed at centrally planned economies).

To add even more confusion to the mix, the term "liberal" which is now used to generally reference a person with the same ideas as all the bozos I just mentioned, actually used to refer to us; that is, conservatism today is/was also referred to as liberalism at least up until the 1930s or so. In fact, the "movement" of "neoliberalism" is in fact a move towards freeing markets from overactive government regulators. I just wish there was some easy way to wipe all these ideas and policies that have essentially been proven wrong, time and time again, to be thrown off the political map; they don't belong.

Apologies...

Code is an interesting thing to try and post online, since when you try and post it straight from a .h or .cpp file, it often includes less than and greater than signs, which in html means something entirely different, so if you see a blank space, that means there's supposed to be something there, it would just be enclosed in a less than and greater than sign... I'll have to figure out some way to fix that..

Monday, November 2, 2009

getData function example in C++

//getData function ~ validates that the input is of the correct data type
template<class T>
void getData(T data, string prompt)
     {
          T input;
          for(;;)
          {
               cout << prompt; cin >> input;
               if(cin.good())
               break;
               cout << "Error:  bad input.  Try again.\n";
               cin.clear();
               cin.ignore(10);
          }
          data = input;
      }

List Class

/* List Class Template File
Title: CS 1410 Lab 13 - List Template
Author: Daniel J. Tanner
Date: April 10, 2006
*/
#ifndef TANNLIST_H
#define TANNLIST_H

#include
#include
#include
using namespace std;

namespace Metzengerstein
{
//class declaration
template
class List
{
public:
List(){head_ = NULL;}
List(const List & someList);
~List();
void append(const T & newData);
void insert(int index, const T & newData);
void erase(const T & oldData);
void clear();
void display();
List operator=(const List & someList);
private:
struct Node
{
friend List;
T data;
Node * next;
Node(const T & newData, Node * newNext = NULL){data = newData; next = newNext;}
};
Node * head_;
};

//function definitions
//copy constructor
template
List::List(const List & someList)
{
Node * curr = head_;
Node * temp = someList.head_;
while(temp != NULL)
{
curr = new Node(temp->data);
curr = curr->next;
temp = curr->next;
}
}

//Operator = overloader ~ makes = do something appropriate for dynamically
//allocated list
template
List List::operator=(const List & someList)
{
Node * curr = head_;
Node * temp = someList.head_;
while(temp != NULL)
{
curr = new Node(temp->data);
curr = curr->next;
temp = curr->next;
}
}
//Destuctor ~ properly destroys list after it is used
template
List::~List()
{
Node * temp;
while(head_ != NULL)
{
temp = head_;
head_ = head_->next;
delete temp;
}
}

//Display function ~ Traverses the list to display the contents
template
void List::display()
{
Node * curr = head_;
while(curr != NULL)
{
cout << curr->data << ' ';
curr = curr->next;
}
}

//append function ~ adds a new node at the end of the list
template
void List::append(const T & newData)
{
if(head_ == NULL)
head_ = new Node(newData);
else
{
Node * curr = head_;
while(curr->next != NULL)
curr = curr->next;
curr->next = new Node(newData);
}
}

//erase function ~ erases the first item in the list with data equivalent
//to the given data
template
void List::erase(const T & oldData)
{
if(head_ != NULL)
{
//special case ~ first item is the one that needs erasing
if(head_->data == oldData)
{
Node *curr = head_;
delete curr;
head_ = NULL;
return;
}

//regular cases
Node *prev = head_, *curr = head_;
while(curr->next != NULL && curr->data != oldData)
{
prev = curr;
curr = curr->next;
}
if(curr->data == oldData)
{
prev->next = curr->next;
delete curr;
}
else
return;
}
}

//insert function ~ inserts an item at the index given -- or at the beginning
//or end depending on the index given
template
void List::insert(int index, const T & newData)
{
Node *curr, *prev;
if(index <= 0 || head_ == NULL)
head_ = new Node(newData, head_);
else
{
curr = head_;
for(int count = 1; curr->next != NULL && count < index; count++)
{
prev = curr;
curr = curr->next;
}
if(curr->next == NULL && count < index)
append(newData);
else
prev->next = new Node(newData, curr);
}
}

//clear function ~ clears all the nodes from a list
template
void List::clear()
{
Node * temp;
while(head_ != NULL)
{
temp = head_;
head_ = head_->next;
delete temp;
}
}
}

#endif

Shape Class (.cpp file)

/*
Title: Lab 10 - Polymorphism ~ Shape Classes Definitions
Author: Daniel J. Tanner
Date: March 12th, 2006
Class: CS 1410
*/

#include
#include
#include
#include "TannShape.h"
using namespace std;
using namespace Metzengerstein;

namespace Metzengerstein
{
//Triangle Class Definitions
// Constructors ~ To set the sides variable to explicit or default values
Triangle::Triangle()
{
for(int count = 0; count < 3; count++)
sides_[count] = 0;
}

Triangle::Triangle(double sideA, double sideB, double sideC)
{
sides_[0] = sideA; sides_[1] = sideB; sides_[2] = sideC;
}

//Set functions ~ Set the sides to explicit values
void Triangle::setSides(double sideA, double sideB, double sideC)
{
sides_[0] = sideA; sides_[1] = sideB; sides_[2] = sideC;
}

void Triangle::setSides(double * sides)
{
for(int count = 0; count < 3; count++)
sides_[count] = sides[count];
}

//GetArea function ~ returns the area of the Triangle
double Triangle::getArea()const
{
double s = 0;
for(int count = 0; count < 3; count++)
s += sides_[count];
s /= 2;
return sqrt(s * (s - sides_[0]) * (s - sides_[1]) * (s - sides_[2]));
}

/*Print Function
Purpose: To print out the labelled content of a triangle
*/
void Triangle::print()const
{
cout << "Side lengths: " << sides_[0] << ", " << sides_[1] << ", " << sides_[2];
cout << endl;
cout << "Perimeter: " << getPerimeter();
cout << endl;
cout << "Area: " << getArea();
cout << endl;
}
//End Triangle Definition

//Circle Class Definition
//Print Function ~ Prints out the circle info in an appropriate manner
void Circle::print()const
{
cout << "Radius: " << radius_
<< endl
<< "Circumference: " << getPerimeter()
<< endl
<< "Area: " << getArea()
<< endl;
}
//End Circle Definition

//Rectangle Class Definition
//Print Function ~ Prints out rectangle info appropriately
void Rectangle::print()const
{
cout << "Length: " << length_
<< endl
<< "Width: " << width_
<< endl
<< "Perimeter: " << getPerimeter()
<< endl
<< "Area: " << getArea()
<< endl;
}
//End Rectangle Definition

//Square Class Definition
//Print Function ~ Prints out square info appropriately
void Square::print()const
{
cout << "Side: " << getLength()
<< endl
<< "Perimeter: " << getPerimeter()
<< endl
<< "Area: " << getArea()
<< endl;
}
//End Square Class Definition
}

Polymorphism / Class Heirarchy examples ~ Shapes

/*
Title: Lab 10 - Polymorphism ~ Shape Classes Declarations
Author: Daniel J. Tanner
Date: March 12th, 2006
Class: CS 1410
*/

#ifndef TANNSHAPE_H
#define TANNSHAPE_H

#include
#include
#include
using namespace std;

namespace Metzengerstein
{
//named constants
const double PI = 3.141592654;

//Shape Class declaration
class TannShape
{
public:
virtual double getArea()const = 0;
virtual double getPerimeter()const = 0;
virtual void print()const = 0;
};

//Triangle Class Declaration
class Triangle : public TannShape
{
public:
Triangle();
Triangle(double sideA, double sideB, double sideC);
void setSides(double sideA, double sideB, double sideC);
void setSides(double * sides);
virtual double getArea()const;
virtual double getPerimeter()const{return sides_[0] + sides_[1] + sides_[2];}
virtual void print()const;
private:
double sides_[3];
};

//Rectangle Class Declaration
class Rectangle : public TannShape
{
public:
Rectangle(){width_ = 0; length_ = 0;}
Rectangle(double length, double width){width_ = width; length_ = length;}
void setLength(double length){length_ = length;}
void setWidth(double width){width_ = width;}
double getWidth()const{return width_;}
double getLength()const{return length_;}
virtual double getArea()const{return length_ * width_;}
virtual double getPerimeter()const{return 2 * width_ + 2 * length_;}
virtual void print()const;
private:
double length_;
double width_;
};

//Circle Class Declaration
class Circle : public TannShape
{
public:
Circle(){radius_ = 0;}
Circle(double radius){radius_ = radius;}
void setRadius(double radius){radius_ = radius;}
double getRadius()const{return radius_;}
virtual double getArea()const{return PI * pow(radius_, 2);}
virtual double getPerimeter()const {return PI * 2 * radius_;}
virtual void print()const;
private:
double radius_;
};

//Square Class Declaration
class Square : public Rectangle
{
public:
Square() : Rectangle(0,0){}
Square(double side) : Rectangle(side, side){}
void setSide(double side){setLength(side); setWidth(side);}
virtual void print()const;
double getSide()const{return getLength();}
};
}
#endif

Rational class (cpp file)

/*
Title: Rational class function definitions
Author: Daniel Tanner
Date: August 2nd, 2005
Class: CPSC 1720
*/

//TannRational class function declarations
#include
#include
#include
#include "tannRational.h"
using namespace std;

/* constructors
Purpose: to allow for a default and special constructor
*/
TannRational::TannRational() {numerator_ = 1; denominator_ = 1;}
TannRational::TannRational(int numer, int denom)
{
numerator_ = numer;
if(denom == 0)
zeroError();
else
denominator_ = denom;
reduce();
}

/* Set Functions
Purpose: To set the numerator, denominator, or both
*/
void TannRational::setRational(int numerator, int denominator)
{
numerator_ = numerator;
if(denominator == 0)
zeroError();
else
denominator_ = denominator;
reduce();
}
void TannRational::setRational(TannRational ratio2)
{
numerator_ = ratio2.getNumerator();
denominator_ = ratio2.getDenominator();
reduce();
}
void TannRational::setNumerator(int numerator) {numerator_ = numerator;}
void TannRational::setDenominator(int denominator)
{
if(denominator == 0)
zeroError();
else
denominator_ = denominator;
}

/* Get Functions
Purpose: To return the numerator or the denominator
*/
int TannRational::getNumerator()const {return numerator_;}
int TannRational::getDenominator()const {return denominator_;}

/* Denominator = 0 error
Purpose: If user has set 0 as the denominator, make him change it
Output: Error Message
Input: New Denominator
*/
void TannRational::zeroError()
{
int denom2;
cout << "Error: Computer cannot process ratios with denominator of 0.\n"
<< "Please input a correct denominator: ";
cin >> denom2;
while(denom2 == 0)
{
cout << "Try again. Enter any integer except 0: ";
cin >> denom2;
}
denominator_ = denom2;
}
/* reduce function
Purpose: to reduce a given fraction down to its lowest denominator
Ref: a numerator and denominator that it is reducing
*/
void TannRational::reduce()
{
//create a temporary variable which will be used to reduce
int reducer;

//change the negative sign to numerator if denominator is negative
if(numerator_ > 0 && denominator_ < 0)
{
numerator_ -= numerator_ * 2;
denominator_ = abs(denominator_);
}

//if both numerator & denominator are negative, change to positive
if(numerator_ < 0 && denominator_ < 0)
{
numerator_ = abs(numerator_);
denominator_ = abs(denominator_);
}

//set the reducer to whichever variable is lower between the num & denom
if(abs(numerator_) >= (denominator_))
reducer = abs(denominator_);
else
reducer = abs(numerator_);

//Create a loop to find the highest common multiple between the two
while((((numerator_ % reducer) != 0) || ((denominator_ % reducer)) != 0) && (reducer != 0))
{
reducer--;
}

//reduce with reducer that is divisible by both numer & denom
if(reducer != 0)
{
numerator_ /= reducer;
denominator_ /= reducer;
}
}
/* Print Function
Purpose: To Print out the rational in the form numerator/denominator
*/
void TannRational::printRational()
{
cout << getNumerator() << '/' << getDenominator();
}

/* Add Function
Purpose: to return the sum of two rationals
Return: the sum
*/
TannRational TannRational::add(int numer2, int denom2)
{
TannRational sum;
sum.setNumerator(numerator_ * denom2 + denominator_ * numer2);
sum.setDenominator(denominator_ * denom2);
sum.reduce();
return sum;
}

/* Subtract Function
Purpose: to return the difference between this Ratio and another
Return: the difference
*/
TannRational TannRational::subtract(int numer2, int denom2)
{
TannRational diff;
diff.setNumerator(numerator_ * denom2 - denominator_ * numer2);
diff.setDenominator(denominator_ * denom2);
diff.reduce();
return diff;
}

//Operator Overloaders
//Purpose: To overload the various operators so as to work better with ratios
TannRational TannRational::operator=(const TannRational &right)
{
numerator_ = right.getNumerator();
denominator_ = right.getDenominator();
return *this;
}

/*math operator overloaders
Purpose: To overload the 4 basic math operators to work with a rational
*/
//addition operator overloader
TannRational TannRational::operator+(const TannRational &right)const
{
TannRational sum;
sum.numerator_ = numerator_ * right.denominator_ + denominator_ * right.numerator_;
sum.denominator_ = denominator_ * right.denominator_;
sum.reduce();
return sum;
}

//subtraction operator overloader
TannRational TannRational::operator-(const TannRational &right)const
{
TannRational diff;
diff.numerator_ = numerator_ * right.denominator_ - denominator_ * right.numerator_;
diff.denominator_ = denominator_ * right.denominator_;
diff.reduce();
return diff;
}

//multiplication operator overloader
TannRational TannRational::operator*(const TannRational &right)const
{
TannRational product;
product.setNumerator(numerator_ * right.getNumerator());
product.setDenominator(denominator_ * right.getDenominator());
product.reduce();
return product;
}

//division operator overloader
TannRational TannRational::operator/(const TannRational &right)const
{
TannRational quotient;
quotient.setNumerator(numerator_ * right.getDenominator());
quotient.setDenominator(denominator_ * right.getNumerator());
quotient.reduce();
return quotient;
}

//prefix ++ operator overloader
TannRational TannRational::operator++()
{++numerator_; reduce(); return *this;}

//prefix -- operator overloader
TannRational TannRational::operator--()
{--numerator_; reduce(); return *this;}

//postfix ++ operator overloader
TannRational TannRational::operator++(int)
{TannRational temp(*this); ++numerator_; reduce(); return temp;}

//postfix -- operator overloader
TannRational TannRational::operator--(int)
{TannRational temp(*this); --numerator_; reduce(); return temp;}

//relational operators overloaders
bool TannRational::operator>(const TannRational &right)const
{
TannRational temp;
temp = *this - right;
if(temp.getNumerator() > 0)
return true;
else
return false;
}

bool TannRational::operator<(const TannRational &right)const
{
return right > *this;
}

bool TannRational::operator==(const TannRational &right)const
{
if(this->numerator_ * right.getDenominator() == this->denominator_ * right.getNumerator())
return true;
else
return false;
}

bool TannRational::operator!=(const TannRational &right)const
{
if(*this == right)
return false;
else
return true;
}

bool TannRational::operator>=(const TannRational &right)const
{
TannRational temp;
temp = *this - right;
if(temp.getNumerator() >= 0)
return true;
else
return false;
}

bool TannRational::operator<=(const TannRational &right)const
{
return right >= *this;
}

//I/O Operator Overloaders
ostream &operator<<(ostream &strm, TannRational &obj)
{
strm << obj.numerator_ << "/" << obj.denominator_;
return strm;
}

istream &operator>>(istream &strm, TannRational &obj)
{
strm >> obj.numerator_ >> obj.denominator_;
return strm;
}

//Type Conversion Overloaded Operators
TannRational::operator double()
{
return static_cast(numerator_) / static_cast(denominator_);
}

An implementation of a rational class (good use of operator overloading)

/*
Title: Rational class definition
Author: Daniel Tanner
Date: August 2nd, 2005
Class: CPSC 1720
*/

#ifndef TANNRATIONAL_H
#define TANNRATIONAL_H
#include
#include
using namespace std;

//Rational Class Definition
class TannRational
{
//I/O operator Overloaders
friend ostream &operator<<(ostream &strm, TannRational &obj);
friend istream &operator>>(istream &strm, TannRational &obj);
public:
TannRational();
TannRational(int numer, int denom);
void setRational(int numerator, int denominator);
void setRational(TannRational ratio2);
void setNumerator(int numerator);
void setDenominator(int denominator);
int getNumerator()const;
int getDenominator()const;
void printRational();
TannRational add(int numerator2, int denominator2);
TannRational subtract(int numerator2, int denominator2);

//Operator Overloaders
TannRational operator=(const TannRational &right);
TannRational operator+(const TannRational &right)const;
TannRational operator-(const TannRational &right)const;
TannRational operator*(const TannRational &right)const;
TannRational operator/(const TannRational &right)const;
TannRational operator++();
TannRational operator++(int);
TannRational operator--();
TannRational operator--(int);

//Relational Operator Overloaders
bool operator>(const TannRational &right)const;
bool operator<(const TannRational &right)const;
bool operator==(const TannRational &right)const;
bool operator!=(const TannRational &right)const;
bool operator>=(const TannRational &right)const;
bool operator<=(const TannRational &right)const;

//Type Conversion Overloaded Operator
operator double();

private:
int numerator_;
int denominator_;
void reduce();
void zeroError();
};

#endif

Date Class .cpp

/*
Title: Date Class (.cpp file) - implementation
Author: D. Tanner
class: CS 1415
Date: January 5th, 2006
*/

#include "TannDate.h"

//Date Class implementations - Constructors
/* Default Constructor
Purpose: To create an object of class Date with the date at time of\
creation as the default values
Rec./Ref.: N/A
Return: N/A
*/
TannDate::TannDate()
{
//create a string that will hold the current system date
//collected w/ the strdate function
char currentDate[10];
_strdate(currentDate);

//change the different parts of the array into an int
int month = ((currentDate[0] - 48) * 10) + (currentDate[1] - 48);
int dayOfMonth = ((currentDate[3] - 48) * 10) + (currentDate[4] - 48);
int year = 2000 + ((currentDate[6] - 48) * 10) + (currentDate[7] - 48);
setDate(month, dayOfMonth, year);
}

/* Explicit Value Constructor - with month as a number
Purpose: To provide a way to create a Date object with a user-chosen date
Rec./Ref: N/A
Return: N/A
*/
TannDate::TannDate(int month, int dayOfMonth, int year)
{
setDate(month, dayOfMonth, year);
}

/* Explicit Value Constructor - w/ only the day of the year (0-365)
Purpose: same as above, only here the user can give the day of the year
*/
TannDate::TannDate(int dayOfYear, int year)
{
setDate(dayOfYear, year);
}

//Set Functions
void TannDate::setDate(int month, int dayOfMonth, int year)
{
//validate the info except for monthName
if(month < 1 || month > 12)
{
cout << "Incorrect month. Exiting program..."; exit(1);
}
else if(year % 4 && (dayOfMonth < 1 || dayOfMonth > DAYS_PER_MON[month - 1]))
{
cout << "error: Incorrect day of month. Exiting program..."; exit(1);
}
else if(dayOfMonth < 1 || dayOfMonth > DAYS_PER_MON_LPYR[month - 1])
{
cout << "error: Incorrect day of month. Exiting program..."; exit(1);
}
else if(year < 0)
{
cout << "error: Incorrect year. Exiting program..."; exit(1);
}
else

{ //set the data members
setMonth(month); setDayOfMonth(dayOfMonth); setYear(year);
calcMonthName(); calcDayOfYear();
}
}

void TannDate::setDate(int dayOfYear, int year)
{
//validation
if(year % 4 && (dayOfYear < 1 || dayOfYear > 365))
throw BadDate("error: incorrect day of year");
else if(dayOfYear < 1 || dayOfYear > 366)
throw BadDate("error: incorrect day of year");

//set data members
setDayOfYear(dayOfYear); setYear(year);
calcFromDayOfYear(); calcMonthName();
}

//Calculation functions - these will calculate some data members when others
//have appropriate values

/* CalcFromDayOfYear
Purpose: To calculate the month & day from the day of the year
Rec./Ref.:N/A
Return: N/A
*/
void TannDate::calcFromDayOfYear()
{
//create variables
int tempDays = dayOfYear_;
int count = 0;

//find the month and dayOfMonth by subtracting the # of days in each month
while(tempDays > 31)
{
if(year_ % 4)
tempDays - DAYS_PER_MON[count];
else
tempDays - DAYS_PER_MON_LPYR[count];
count ++;
}
setMonth(count + 1);
setDayOfMonth(tempDays);
}

/* Calc DayOfYear
Purpose: To calculate the day of the year from the month and day of month
*/
void TannDate::calcDayOfYear()
{
int dayOfYear = 0;
for(int count = month_ - 1; count > 0; count--)
{
if(year_ % 4)
dayOfYear += DAYS_PER_MON[count];
else
dayOfYear += DAYS_PER_MON_LPYR[count];
}
dayOfYear += dayOfMonth_;
setDayOfYear(dayOfYear);
}

/* Calc MonthName
Purpose: To calculate the name of the month based on the number
*/
void TannDate::calcMonthName()
{
switch(month_)
{
case 1:
setMonth("January");
break;
case 2:
setMonth("February");
break;
case 3:
setMonth("March");
break;
case 4:
setMonth("April");
break;
case 5:
setMonth("May");
break;
case 6:
setMonth("June");
break;
case 7:
setMonth("July");
break;
case 8:
setMonth("August");
break;
case 9:
setMonth("September");
break;
case 10:
setMonth("October");
break;
case 11:
setMonth("November");
break;
default:
setMonth("December");
break;
}
}

//Print Date Functions

/* Shorthand version
Purpose: To print out the date in shorthand format (MM/DD/YY)
*/
void TannDate::printShortDate()
{
cout << month_ << "/" << dayOfMonth_ << "/" << year_;
}

/* Long version
Purpose: To display a date in the form Month Day Of Month, Year
*/
void TannDate::printLongDate()
{
cout << monthName_ << ' ' << dayOfMonth_ << ", " << year_;
}

/* Day of Year Version
Purpose: To display a date in the form: Day of Year, Year
*/
void TannDate::printDOY()
{
cout << dayOfYear_ << ", " << year_;
}

An example of a date class in C++

Tossing some of these up here for my own reference:

/*
Title: Date Class (header file) - prototype
Author: D. Tanner
class: CS 1415
Date: January 5th, 2006
*/

#ifndef TANNDATE_H
#define TANNDATE_H

#include
#include
#include
using namespace std;

//Constants
const int DAYS_PER_YEAR = 365;
const int DAYS_PER_LPYR = 366;
const int DAYS_PER_MON[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30,
31};
const int DAYS_PER_MON_LPYR[12] = {31, 29, 31, 30, 31, 30, 31, 31, 30, 31,
30, 31};

//Date class function declarations
class TannDate
{
private:
int dayOfYear_;
int dayOfMonth_;
int month_;
int year_;
string monthName_;

//General Calculation Functions
//These functions must be called only under the circumstances that the
//corresponding data members have been given appropriate values
void calcDayOfYear();
void calcFromDayOfYear();
void calcMonthName();

//private set functions
void setDayOfYear(int dayOfYear){dayOfYear_ = dayOfYear;}
void setDayOfMonth(int dayOfMonth){dayOfMonth_ = dayOfMonth;}
void setMonth(int month){month_ = month;}
void setMonth(string monthName) {monthName_ = monthName;}
void setYear(int year){year_ = year;}

public:
//Exception class
class BadDate
{
private:
string errorMsg_;

public:
BadDate(string error){errorMsg_ = error;}
string getError(){return errorMsg_;}
};

//Get functions
int getDayOfYear(){return dayOfYear_;}
int getDayOfMonth(){return dayOfMonth_;}
int getMonth(){return month_;}
int getYear(){return year_;}
string getMonthName(){return monthName_;}

//set functions
void setDate(int month, int dayOfMonth, int year);
void setDate(int dayOfYear, int year);

//Constructors
TannDate();
TannDate(int month, int dayOfMonth, int year);
TannDate(int dayOfYear, int year);

//Print Functions
void printShortDate();
void printLongDate();
void printDOY();
};

#endif

Books as Games

Here's an essay I wrote for my folklore class; it was a fluff class but surprisingly fun. Well, enjoy:

Folklore as Presented in Gaming

How does one translate a story from printed paper to an interactive visual experience? Such is the job of many companies hoping to skip the hassle of writing a story for a videogame by using an already written one, though such a choice has its ups and downs. Some of the books we have read this semester would probably make good games, some probably would not; additionally, much of the folklore is easily implementable whether or not the main story of a novel makes for a good game.

To begin with, a good videogame ought to have a goal-oriented plot, where the player understands what he is working towards by at least halfway through the game. Thus, books that have a plot you might call "slice of life" (that is, a story not about swords & sorcery or conspiracy or mystery; a story about regular people) like Their Eyes Were Watching God and Four Souls tend to be difficult to implement into video games. Neither book really has a clear conclusion that you could really call "achieved." At best, one could imagine Their Eyes Were Watching God like a romance game (such as the Japanese eroge Clannad or Air) where the gameplay consists of making choices and attempting to woo one of the three men that Janie had married in the book. Such a game would lose the sense of character development and gain of freedom that is taught via Janie's progression through the three men in the novel, however; furthermore you'd have to design at least six separate endings (success and failure with each romantic endeavour) which, aside from a good ending with Teacake, would have little to do with the original novel. So, Their Eyes Were Watching God would not really fit well on a videogame shelf, in general.

As for Four Souls, it has the same problem as said earlier with not having a clear goal for the player to aim for, though the way Fleur is portrayed is also troublesome. If you have a character that is only ever seen through the eyes of other characters, and her own thoughts and purpose in life are blocked from the reader ... how do you begin to imagine turning her into a playable character? If you were to implement a back-and-forth switching between Nanapush and Fleur, and kept Fleur more as a side character it would be doable I suppose, but I struggle to imagine what kind of game you'd be playing as Fleur. Doing laundry and other chores to get into the good graces of Polly Elizabeth only to suddenly pull a knife on the man of the house in the night hours? I don't think that would really work so well. At least with Nanapush as the protaganist, you could make an adventure game with a lot of item puzzles (setting the snare, gathering materials for medicine) and ending with a set of speech choices (for that last major scene of Nanapush's in the book, where he has to speak before a gathering of his fellow Ojibwe). So, again, not really an easy choice if you were trying to make a game out of a book.

Now that we've looked at two books that are not really all that viable as concepts for videogames, it would be interesting to look at one that is: Haroun and the Sea of Stories. Now here's a book that you could easily imagine as an adventure game or a sidescroller. There's plenty of potential item and conversational puzzles, and the setting is a lot more fantastic and magical. For examples, let's look at the bus station scene (for a conversational puzzle) and the shadow ship scene (for an item puzzle). At the bus station scene in the book, we find Haroun deciding to sit down and watch instead of trying to desperately secure a seat as the other people are trying to do; this nonconformity gets the attention of Butt, who Haroun convinces (could almost call it a bit of trickery with words) to make the race to the valley of K. If we say that the use of a bus as passage to the Valley of K is the objective of our conversational puzzle, we could design a discussion with specific conversation choices you would have to make with Haroun to get Butt to let you onto the bus to the Valley of K. As for the shadow ship scene, in the book Haroun uses an almost-forgotten about bottle of gold wish-water to get rid of all the shadows by wishing for the moon of Kahani to rotate such that the Sun was directly over the spot where the ship was. Therefore, it's easy enough to imagine an item puzzle where you would need to pull the golden wish-water out of your inventory and make a wish. You would then be prompted with a list of choices about what you wanted to wish for. Just to add in some excitement the whole operation would need to be done before shadow priests closed in on you. All that having been said, I think we can conclude Haroun would make for a reasonably good game.

Since we have examined how some books would do as videogames in a general sense, let us look at some of the more specific folklore elements present and how we could turn them into a gameplay element. 'Alchemy' is the usual name for combining items to make a medicine, curse or similar magical object in videogames (some good examples are the Atelier games from Gust or the Kyrandia games). I think we could classify the majority of the folklore activities in Four Souls and Bless Me, Ultima into that category. In Four Souls Nanapush on several occassions and Fleur at least once in the story practice a form of Native American medicinal folklore. Nanapush uses it to make a love potion for himself and Margeret as well as to curse his arch-enemy Shesheeb. Fleur uses it to cure John Mauser. While we don't get a really clear view of what exactly is done we do get the idea that in the first case it is a combination of various items, and in the second that it is something akin to acupuncture or chiropracty. All in all, it'd be relatively easy to implement Nanapush's activities as a kind of 'alchemy' item puzzle. Fleur's chiropracty-like activity ... maybe we could make some kind of gameplay element similar to the Operation! board game.

In Their Eyes Were Watching God there is a folklore activity commonly referred to as "playing the dozens;" basically an insult game, as well as the dice game and references to the "John the Conqueror" and "the town mule" folktales. Insult games are basically conversational puzzles, where you might have a set of responses to choose a reply for a specific insult. The best example I can think of for this is the Monkey Island games from Lucasarts, which is all about pirates and swashbuckling. Instead of a combat system for all the sword-fighting and arm-wrestling and what-not, Lucasarts decided to implement an "insult-fighting" system where you would have to respond to such quips as "You fight like a dairy farmer!" with "only because you're a cow!" So "playing the dozens" is easy enough to implement. The dice game we're not really given a lot of information on, but there are entire videogames all about different ways to play with dice, so it is not all that hard to imagine per se. The allusions made to the various folktales are probably the kind of thing you would implement not really as a major part of the game except in terms of setting, mood, and atmosphere, perhaps leaving hints to other item puzzles in the game by using the folktales; similar to the hints left in a fairytale book as to how to beat the first boss in Silent Hill, or the similar use of a fairytale to explain how to clear an obstacle in Silent Hill 3 when you first enter the Otherworld. Therefore, it is easy to imagine how to implement most of the folklore elements, in and of themselves, into a video game.

In conclusion, videogames are often designed from plots, taken in part or whole, from books. Out of the books we've studied over this semester, it seems fair to say that Four Souls and Their Eyes Were Watching God would not really
make very good videogames due mostly to the way the plot is developed in both books, and somewhat as a result of being "slice of life" types of stories. Haroun on the other hand, has all the basic elements to fit the usual criteria, and is certainly more marketable with its Dr. Seuss-like magical setting. As we examined a few of the more specific elements from the various folklore contained the books, whether it was "playing the dozens" or collecting herbs and making medicines (for good or ill), most of them have already been represented in some fashion in videogames, and as a result it's not hard to imagine how we could interpret an interactive framework to include them in.

Overpopulation Essay

This is a research paper I wrote waaaaay back in my "research paper" class in my Freshman year of college. Enjoy!

14 July 2005
On The Union of Concerned Scientist Warning to the World
Concerning the Threat of Overpopulation

In November of 1992, one thousand seven hundred scientists affiliated with the Union of Concerned Scientists1 signed the “World Scientists’ Warning to Humanity,” which was written by Henry Kendall. In this ‘warning’ Kendall says that:

"Pressures resulting from unrestrained population growth put demands on the natural world that can overwhelm any efforts to achieve a sustainable future. If we are to halt the destruction of our environment, we must accept limits to that growth. A World Bank estimate indicates that world population will not stabilize at less than 12.4 billion, while the United Nations concludes that the eventual total could reach 14 billion, a near tripling of today’s 5.4 billion. But, even at this moment, one person in five lives in absolute poverty without enough to eat, and one in ten suffers serious malnutrition."

How true is this? Is the world really approaching overpopulation? I decided to research the topic and find out, dividing the topic into several basic questions. First, what constitutes overpopulation? Second, is the world facing overpopulation as a problem today? Third, what solutions have been suggested to prevent overpopulation or to at least slow population growth? For those solutions that have already been implemented, what has worked, what has not worked, and why? Lastly, if in actuality population decline is the modern problem (as much of my research has suggested), how did we get there, what problems does it pose, and how do we get back into population growth (if that is needed)? With these questions in mind, I began my research.

What is overpopulation? According to The American Heritage Dictionary of the English Language, it is “The condition of having a population so dense as to cause environmental deterioration, an impaired quality of life, or a population crash.” Kendall and the world scientists seem to agree with this definition. But the problem with this definition is that one can almost say they “feel” the world is overpopulated, or a city is overpopulated, because in their eyes it may fit the aforementioned description. Take, for instance, Salt Lake City. If one is used to a small town atmosphere, the city atmosphere can feel so uncomfortable that it lowers one’s quality of life. The crime rate (especially the murder rate) that naturally rises with the population density might be labeled as a type of population crash. And to top it all off, the air pollution is undoubtedly worse than in places outside the city. So if such conditions are natural for any areas with high population densities (or even medium population densities, such as Salt Lake City), when does one say that there is overpopulation? For my own research, I have decided that severe environmental damage, engendering the over-consumption of resources to the point that the surrounding areas have become barren, and severe changes in quality of life for the residents of an area (such that the majority of people are without food, water, and shelter) are required to call it overpopulation. With this clarification, places like Los Angeles (which I have visited) are not overpopulated because people in those cities have a high quality of life (while there are hungry homeless, they are far from being a majority), the pollution is not so bad as to seriously affect the surrounding environment, and crime is not so bad as to kill a noticeable percentage of those cities’ populations. To call a place overpopulated, then, would require: a) severe negative environmental impact; b) people with little to no quality of life, where any food and shelter is scarce, and quality food and shelter is non-existent; and c) a mass die-off from malnutrition and starvation (death from disease has too many extraneous factors for use as a good criterion).

Now that we have a definition of what overpopulation is, and more importantly, what conditions would exist to suggest overpopulation, is the world overpopulated? Do we have enough resources to support our current world population? Well, from what Tweeten and Zulauf, authors of the Futurist study “Feeding the World: the Long-term Outlook,” say, the world is still harvesting resources, most countries have surpluses of these resources stocked up, and there are more than enough resources to support the current population. Tweeten and Zulauf make this clear when they point out that farms in general are yielding far more per acre now than ever before, even to the point that many plots of farmland are being re-zoned as residential or commercial areas.2

While there are certainly places that have few resources now, such as sub-Saharan Africa, it is not as if they’ve run out of resources. Thomas Sowell, in one of his columns for Townhall.com, makes clear that Africa’s problems are bad leadership, bad geographical location, and bad foreign aid policies from other nations rather than just too many people with too few resources. This is made even clearer when Sowell contrasts the centrally-planned governments of some African nations with the free-market economy of the Ivory Coast. Under then-president Felix Houphouet-Boigny’s democratic government, that country evidently prospered. This shows that overpopulation is, if even a factor, not the decisive factor in causing sub-Saharan Africa’s various problems.

As for environmental problems, who’s to say that the problems we have now, or think we have now, are directly related to overpopulation? I’ve heard lots of arguments by environmentalists that things like deforestation and the loss of species to extinction are caused by rapid human expansion. At the same time, there are many people who I’ve heard claim that the Earth can handle anything that humans do to it, even so far as nuclear winter. And there are, of course, lots of people (myself included) who hold opinions that are somewhere in between. So which argument most accurately describes the state of the environment, and the causes for that state? The main question remains whether or not the environment shows signs of devastation due to human overpopulation. Mark Lynas, in an article for the British magazine New Statesman, claims that because of human overpopulation one fifth of bird species, forty percent of mammals and fish, one third of amphibians, and up to one half of all plant species are threatened with extinction.3 He says, in his title even, that “The Biomass of Human Bodies Now Exceeds by a Hundred Times that of any Large Animal Species that Ever Existed on Land.” So there is a lot of people on the planet Earth, and a lot of lower species are facing extinction. While there is evidence that human encroachment might force certain species’ habitats to be changed (leading to possible extinction), that alone doesn’t show overpopulation. I found nothing in Lynas’ argument that gives evidence of environmental damage due to human overpopulation.

Thus, it can be seen that there is not an overpopulation problem today, but what about the future? The United Nations Population Fund’s most recent studies show that the current world fertility rate4 is about two and nine tenths, and steadily decreasing. According to Micheal Meyer, a two and one tenth fertility rate is required for population stability, so it appears that the world population will soon move into decline. The studies indicate that Europe’s native populations are already in decline, with Italy and Spain leading with a rate of one and two tenths. Those studies also show that France and Ireland have the highest averages in Europe, with a fertility rate of one and eight tenths. They find that Germany’s fertility rate, and the average in Europe, is at one and four tenths.5 Another interesting fact illuminated by the United Nations Population Fund studies is that, along with Europe, all the developed nations in SE Asia as well as China are already in a state of native population decline. Furthermore, it seems that America is the only developed nation with a fertility rate above replacement levels, but it is barely so. The United Nations Population Fund goes on to estimate a worldwide fertility rate drop below two and one tenth by the year two thousand fifty. Even the nations in the Middle East and in sub-Saharan Africa (which currently have rates well above replacement, according to the UNFPA) are expected to have below replacement levels of fertility rates by that time.6

So what, then, are the effects of population decline? According to Meyer and Boorse, those nations whose leaders were misguided enough to start social security programs (or similar policies) will be in for deep economic troubles. Meyer and Boorse say the worst problems will arise in China, which is expected to have the so called ‘4-2-1' situation. That is, four grandparents and two parents dependent on the income of one child. According to Meyer, this problem arises mainly from the population decline (which means less labor available in every generation, leading to less prosperity, leading to less wages), along with bad health policies (which lead to people retiring at a younger age). More importantly, Meyer says, this will force the government to lower whatever benefits are provided by their social security system, or to raise the taxes on the workers, or both.7 The same problem will undoubtedly occur in every country with a social security system or social security-like policies.

But what of the positive effects of population decline? Tweeten and Zulauf suggest that negative population growth (that is, decline) will alleviate any fears of global food crises. All of the sources I’ve read agree that there will be less crowding, greater per capita income, healthier living, and a healthier environment after a population decline.8 Do these outweigh the problems? While it might be good for China if its financial policies force a government collapse (as discussed earlier), recessions and/or depressions rivaling, or even surpassing, that of black Thursday’s are a bleak future to think of. Granted, not every nation will face this (as not all nations have social security or like programs, and there is the possibility that those countries that currently have social security might rid themselves of it, seeing the coming population decline), but for those that will, are the positive effects worth potential economic ruin? What worries me even more is the idea that in this situation, humanity might see the complete loss of one culture or another (which, to me, is worse by far than the extinctions of any animals). Whether the good effects of population decline outweighs the negative effects is something I suppose people will need to consider themselves.

So now we are left with the question: What led to the change of a world worried about overpopulation to a world worried (or relieved) about population decline? And, at the same time, What were the solutions that led to decline? Potts gives the blame (or credit, if you prefer) to the increasing availability of contraceptives. He claims that without the further spread of contraceptives, the fertility rate will not decrease swiftly enough to meet United Nations Population Fund estimates by the year two thousand fifty.9 Interestingly enough, Spain and Italy, which have the lowest fertility rates in Europe, also have majority populations of Roman Catholics, a sect of Christianity that is strongly against any usage of contraceptives.10 So Potts’ thesis that contraceptives are the main force in decreasing worldwide population is questionable. In China, there is the one-child per household policy11, which has undoubtedly cut down on births in that country. Add to that the tradition that Chinese families carry on their name through male children (much the same as many cultures), and you get a lot of families with only one child, and that child is a boy. Thus, the current generation and the next generations of Chinese males will find it very difficult to find a mate. One other factor mentioned by Potts is that richer people tend to want fewer children, for which he gives Bangladesh as an example. Potts says that Bangladesh decreased from a fertility rate of over five to a little above replacement rates in under five years, alongside rapid economic development and the increasing availability of contraceptives. At the same time, however, one can imagine that materialistic philosophies began to take root, and Christian missionaries were given more freedom to evangelize (which has happened in every nations that has ‘westernized’ itself in the past).12 Which particular event (or set of events) caused the decrease in fertility rate is hard to determine. According to Tweeten and Zulauf, a decrease in fertility rate (and thus, a negative population growth) is just one of the things that characterizes a developed nation. Meyer points out that even in developed countries where the government is supporting systems that promote fertility rates (such as Singapore, which has a subsidized dating service), the rates are dropping. Ultimately, the cause of the change from explosive growth to slow decline is probably not contraceptives, but is hard to determine otherwise. China’s one-child policy was definitely a force for that country, but for Europe, America, and developed Asian countries, the decrease in fertility is still, to me, an unanswered question.

In conclusion, overpopulation is not one of the modern world’s problems. The Union of Concerned Scientists was wrong in that, at least. The real issue seems to be negative population growth and the problems it brings with it. Countries with social security will be devastated by the decrease in available labor and the increase in the number of retirees. These governments will face a very real problem unless some major changes are made. On the other hand, population decline will bring some positive effects for the environment, for individuals, and for some economies. It will undoubtedly reduce the output of pollution and the consumption of resources. Land will be freed up so that houses will be cheaper (as mentioned by Nicholson-lord) in general. Some animals that are currently threatened by human encroachment in their environments may possibly return to nominal population levels13. There will be no worries of a food crisis or any sort of famine. Production of agricultural goods might even increase as the population declines. All these things and more good will probably come of the decrease in population. Whether the economic problems discussed earlier will be worth it (for some nations) is not something I can answer.

But what of the policies that caused the change? China’s one-child policy was a factor for that country, without a doubt. The spread of contraceptives is often tied with lowering fertility rates, but is of questionable viability because it in turn raises wanton promiscuity, which in turn raises illegitimacy. Removing the responsibilities attendant with intercourse is simply an unwise decision no matter how you look at it. Perhaps it’s as Tweeten and Zulauf claim, that population decline is simply a sign of development? If that is the reason, there is an uncountable number of causes for the effect of population decline. Among them may very well be contraceptives, certain religions and philosophies, even prosperity might be a cause. I can’t really point out a definitive reason why populations have started to decline, but I suppose that’s not really what’s important. What’s important is that the UCS’ “World Scientists’ Warning to Humanity” was wrong, and instead of considering solutions to population growth, humanity should now start looking for solutions to a completely opposite concern: population decline.









Notes
1 The Union of Concerned Scientists, from what I can determine from their website, is an organization that’s been around since the seventies, based at MIT. It tends to be slanted toward environmentalism, but the argumentation it uses tends to be well sourced, if not entirely logical (to a conservationist like me, anyway). One of the problems it has, especially with the “World Scientists’ Warning to Humanity” is that it boasts several Nobel laureates among its body, which adds precisely nothing for its credibility, considering the amount of politics involved in the awarding of Nobel Prizes. Though it may be off-topic, it is notable that Zork, a landmark in computer gaming history, was developed by students at MIT, so I tend to like that particular institution.

2 This is undoubtedly an unwise move. In my own valley, while there is certainly a lot of fertile land that has yet to be used for farming, there is even more land that has the qualities most people look for when they want to build a home (a nice view, clean air, etc, etc) in areas that are not so apt for agricultural uses.

3 What Lynas fails to mention is which animals are threatened, and where he gets that information. He doesn’t even provide any evidence that it was humanity that caused those species to become threatened with extinction. Furthermore, the fact that his whole argument is heavily based on evolutionary theory lends very little credibility. Of course, me being a Christian, and creation being the most logical explanation I can find, using evolutionary theory for reasoning purposes would lend little or no credibility to an argument, at least for me anyway.

4 Fertility rate is based on how many children born per woman in a country. So for Sanpete County (where I live), with its average of five to six children per mother, the fertility rate would be about 5.5.

5 All these rates are originally from studies of the United Nations Population Fund, and are mentioned by Tweeten & Zulauf, Potts, Boorse, Nicholson-Lord, and Meyer.

6 According to Potts’ article in Scientific American, this estimate assumes that developed countries will continue to pay for undeveloped and developing countries’ contraceptives. This despite the fact that, logically, contraceptives in general tend to encourage promiscuity. This is in turn results in higher fertility rates. Furthermore, while the ability to perform abortions might result in lower populations (mainly because abortion often kills the mother along with the child, either at the time of surgery, or from complications; especially when you consider that in undeveloped/developing countries, quality surgeons are not exactly in high supply), birth control pills and injections only guarantee that if there is a resultant child it will be defective in some way or another. And it is very seldom that a mother that knows the risks involved in an abortion (which are multiplied by being in a undeveloped/developing area) will have an abortion anyway. (Please make note that this argument is my own reasoning, based on my personal observance of teenagers at a public high school I attended a few years ago, as well as studies and things that pop up in the news every so often and become something like common knowledge).

7 This may actually be, in my humble opinion, a good thing, not only for China, but for the rest of the world. It may end up getting rid of social security forever. If humanity is really lucky, it may end all of the ineffective government entitlement programs. Unfortunately, my experience suggests that even given the obvious failures of those programs as of yet, many politicians are completely oblivious to the idea of getting rid of them. Furthermore, it is probable that they will continue to ignore the problem even after it completely destroys the economy, blaming the economic devastation on something else.

8 Nicholson-Lord especially extols the increasing availability of a home with a view.

9 Potts is an obstetrician by profession so it is expected that he would extol the usage of contraceptives.

10 I know this because I remember reading it somewhere, though I can’t pinpoint exactly where I read it. Should be common knowledge, assuming everyone remembers their high-school history courses.

11 This policy, which you can google if you wish, basically makes it so that every family in China can have one and only one child. If they want more, they have to fill out several papers to get approval, and approval is not given to very many. Being a major violation of human rights, it is a controversial policy that is often discussed on TV, the internet, and in periodicals (which is where I get my information, though I am regrettably unable to pinpoint any specific sources).

12 For example, when Japan started to westernize, the people that came to teach them were Jesuits (again, this should be common knowledge to anyone who attended high school World History).

13 Again, Mark Lynas never did give specific info to relate the decrease in the number of particular species to overpopulation. He didn’t really prove, per se, that it was even human encroachment, but we can probably assume that human encroachment is at least one of the factors.










Works Cited
Borse, Dorothy. “Overpopulation: Ecological & Biblical Principles Concerning Limitation.” Worldviews: Environment Culture Religion. 7.05 (2003): 154-170.
Kendall, Henry. “World Scientists’ Warning to Humanity.” Union of Concerned Scientists. 29 Oct. 2002. Union of Concerned Scientists. 8 July 2005 .
Lynas, Mark. “The Biomass of Human Bodies Now Exceeds by a Hundred Times that of any Large Animal Species that Ever Existed on Land.” New Statesman 23 Feb. 2004: 23-25.
Meyer, Micheal. “Birth Dearth.” Newsweek 27 Sept. 2005. 8 July 2005 .
Nicholson-Lord, David. “The Fewer the Better.” New Statesman 8 Nov. 2004: 24-26.
“Overpopulation.” The American Heritage Dictionary of the English Language. 4th ed. New York: Houghton Mifflin Company, 2000.
Potts, Malcom. “The Unmet Need for Family Planning.” Scientific American 282.1 (2000): 88-93. Vocational and Career Coalition. 8 July 2005 .
Sowell, Thomas. “The Tragedy of Africa.” Townhall.com Ed. Johnathon Garthwaite et al. 12 July 2005. Townhall.com. 13 July 2005 .
Tweeten, Luther and Carl Zulauf. “Feeding the World: the Long-term Outlook.” Futurist Sep. 2002: 54-59.
United Nations Population Fund. July 2005. United Nations Population Fund. 8 July 2005 .

Update: Wow that did not copy and paste as well as I thought. Edited for better white spacing and line breaking.