letsthinkabout.us

technology, healthcare, people

iOS Game of Life

iOS Game of Life

The live demo for this can be seen here: 


Game of Life is a cellular automaton created in 1970 by mathematician John Conway. There are only 4 rules of the game:

  1. An alive cell with 0 or 1 alive neighbors dies in the next generation (underpopulation)
  2. An alive cell with 2 or 3 alive neighbors lives in the next generation
  3. An alive cell with > 3 alive neighbors dies in the next generation (overpopulation)
  4. A dead cell with exactly 3 neighbors comes to life in the next generation.


The implementation here uses a 2D boolean array that serves as the "board." Using a standard model of states, we iterate over the entire array in each generation to determine which cells will be alive or dead in the next generation.  If you are interested in the code, see the implementation in the GitHub project here


Runge Kutta in C++

Continuing on my series for Runge Kutta in multiple languages, today's topic is C++. The other implementations can be found here:


So again, Runge Kutta is a numerical evaluation of an ordinary differential equation. It is more generalized than Euler method in that 2nd order Runge Kutta = Euler method. Here, we use the very common 4th order method, which is simple to program and very accurate for appropriate time-steps.
 



Given the differential equation and initial bounds:


What is y( 1 )?

ps: this equation solves to y = exp(x)


Let's implement the Runge Kutta equations in a method returning double named rk4( ... ):

const double sixth = 1.0 / 6.0;
double rk4(double x, double y, double dx, double(*f)(double, double)) {
	double halfdx = 0.5 * x;
	double k1 = dx * f(x, y);
	double k2 = dx * f(x + halfdx, y + k1 * halfdx);
	double k3 = dx * f(x + halfdx, y + k2 * halfdx);
	double k4 = dx * f(x + dx, y + k3 * dx);
	return (y + sixth * (k1 + 2 * k2 + 2 * k3 + k4));
}
The very last argument of the rk4 method is a pointer to a function which is called 'f' in the scope of rk4. 'f' takes 2 arguments of type double.


Next, we'll create an Equation object, that contains the x, y, dx and target variables. I use a C++ struct to let all methods and fields/properties default to public accessor.
struct Equation {
	double x, y, dx, target;
	static double dy_dt(double x, double y){ return y; }
	void Run(){
		while (x < target){
			y = rk4(x, y, dx, dy_dt);
			x += dx;
		}
		std::cout << "x=" << x << "\n" << "y=" << y << "\n";
	}
	Equation(double x_arg, double y_arg, double dx_arg, double target_arg){
		x = x_arg;
		y = y_arg;
		dx = dx_arg;
		target = target_arg;
	}
};
The method dy_dt is marked static because in C++ you cannot pass a member function as a function pointer. There is a nice writeup about why:

[33.2] How do I pass a pointer-to-member-function to a signal handler, X event callback, system call that starts a thread/task, etc?
Don't.
Because a member function is meaningless without an object to invoke it on, you can't do this directly (if The X Window System was rewritten in C++, it would probably pass references to objects around, not just pointers to functions; naturally the objects would embody the required function and probably a whole lot more).

Finally, our entry point creates a local variable of type Equation using the defined constructor, and we call Run( ) on it:
int main(int argc, const char * argv[]) {
	Equation eq(0.0, 1.0, 0.000001, 1.0);
	eq.Run();
	return 0;
}

Result:

y = 2.71828

which is close to the value of e = 2.7182818284590452353602874713527


Here's the full code:

#include <iostream>
const double sixth = 1.0 / 6.0;
double rk4(double x, double y, double dx, double(*f)(double, double)) {
	double halfdx = 0.5 * x;
	double k1 = dx * f(x, y);
	double k2 = dx * f(x + halfdx, y + k1 * halfdx);
	double k3 = dx * f(x + halfdx, y + k2 * halfdx);
	double k4 = dx * f(x + dx, y + k3 * dx);
	return (y + sixth * (k1 + 2 * k2 + 2 * k3 + k4));
}
struct Equation {
	double x, y, dx, target;
	static double dy_dt(double x, double y){ return y; }
	void Run(){
		while (x < target){
			y = rk4(x, y, dx, dy_dt);
			x += dx;
		}
		std::cout << "x=" << x << "\n" << "y=" << y << "\n";
	}
	Equation(double x_arg, double y_arg, double dx_arg, double target_arg){
		x = x_arg;
		y = y_arg;
		dx = dx_arg;
		target = target_arg;
	}
};
int main(int argc, const char * argv[]) {
	Equation eq(0.0, 1.0, 0.000001, 1.0);
	eq.Run();
	return 0;
}

4 Life Lessons from Powerlifting

From 2007 to 2011, I was a competitive powerlifter. I squatted 625 lbs, benched 460 lbs, and deadlifted 551 lbs at my best. I also lost 60 pounds going from 220 to 160 in 16 weeks from Jan - May 2009. I hired (now pro) bodybuilder Shelby Starnes.



During this time, I learned about the more fanatical ends of myself. I was willing to sacrifice personal time, friends, and family time just so I could train.  Almost anything was secondary to progression of myself. Not an optimal approach to life. I did pick up some things along the way when I reflect back:


1. You push back hardest when resistance is greatest

I learned this early on. While doing some warm-up sets on squat, I found that I simply could not push the weight as hard when it was light. For example, I would warm up with 135 lbs for a set of 10, but each individual rep had maybe a force worth 185 lbs behind it. When the weight was 185 lbs, I was able to apply 225 lbs worth of force behind it. It wasn't until 315 lbs that I was able to apply 365 lbs worth of force to the weight.

This was the first concept to click in my mind when it came to the parallels of life and powerlifting. You can simply drift at what you do, go through the motions without ever fully applying yourself. However, once the stakes are high, the pressure is on, then you are able to perform at the best of your abilities.


2. Scheduled time-off = big gains

Both in and off-season, I trained using a 4 week cycle. It looked like this:

Week 1 - 3:
  4 Days / week
  2 Days Bench movements
  2 Days Squat / Deadlift

Week 4 (deload):
  3 Days -> Weights not more than 25-30% of week 3 maxes

I would string together these 4 week periods into a coherent 16 week training cycle, where intensity would increase for 3 week waves, with 1 week down. This would lead to week 11 being the absolute heaviest of the training cycle. Week 12 would be a deload, and 13-15 would be a decrease in intensity. 

The span from week 11 to competition day following week 16 is known as delayed transformation. You are actually getting stronger from the decrease in intensity between week 12-16 because you peaked at week 11 and your body is adapting to the training in delayed fashion. These principles are outlined in Mel Siff's Supertraining, a book I highly recommend.

In my experience, this principle of scheduled time-off holds true for other abilities, such as learning, cognition and manual dexterity. In essence, you get better at things when you take the appropriate time-off. But this is provided you followed lesson #1.

3. Do what you suck at

A chain is only as strong as its weakest link. To be a better chain, you have to strengthen that link.

Case in point: in late 2007, my bench stagnated in the high 200's. Whenever I tried anything above 275, I'd lose it completely about 3/4 the way up. My triceps were weak and I couldn't drive the weight any further, no matter the speed coming off my chest. For 2 months, I decided that I would heavily train the top part of the motion. This meant heavy (300 lbs +) board presses, adding bands, and more tricep work. By January 2008, I managed to increase my bench > 40 pounds and with my first 315 lbs bench press.

It's often difficult to identify what exactly are your weak points. Once you do identify them, it's sometimes difficult to accept that you have these deficiencies. But you get it done, and you'll be better off.

4. You can't succeed alone

In powerlifting, you need support. Support when you're training in the form of spotters and partners. Support in your friends who will show up to your meets. Support in your family, who will put up with your lifestyle. And as much as you receive this support, you are also expected to reciprocate this support in appropriate ways. No one made it to the top without a little help from some friends.


Plotting F# Data using Excel Interop: Soaring Life Expectancy Edition

Two centuries after the dawn of the industrial revolution, humanity had its most productive century in the 1900's. The birth of the modern automobile, assembly line, airplane, nuclear bomb, and internet all happened in the same 100-year span. We greatly eliminated infant and child mortality, leading to the first dramatic increase in life expectancy in human history. What are the current trends in this improvement? Let's use the F# Data library and World Bank to find out.


The F# Data library makes it easy to get numbers from the World Bank Data repository. It also features a type provider. If you'd like to read more about type providers in F# Data, see this excellent post.

Let's look for the indicator "Life expectancy at birth, total (years)." We find in that link the key to access that indicator  "SP.DYN.LE00.IN" meaning we can follow the link scheme to access part of the XML data in the World Bank:

http://api.worldbank.org/countries/us/indicators/SP.DYN.LE00.IN?date=2010

<wb:data xmlns:wb="http://www.worldbank.org" page="1" pages="1" per_page="50" total="1">
    <wb:data>
        <wb:indicator id="SP.DYN.LE00.IN">Life expectancy at birth, total (years)</wb:indicator>
        <wb:country id="US">United States</wb:country>
        <wb:date>2010</wb:date>
        <wb:value>78.5414634146342</wb:value>
        <wb:decimal>0</wb:decimal>
    </wb:data>
</wb:data>


In C#, we would typically find the XML schema, write a custom type, parse the data and mine it from there. F# Data takes care of this for you. Even Intellisense exists:



Given that F# is in .NET and can call the same assemblies as in C#, we can use Microsoft Excel Interop to table the data and graph it. F# makes short work of this task, gets World Bank data of US Life Expectancy, tables it, and plots in an Excel graph, all in 35 lines.

open FSharp.Data
open Microsoft.Office.Interop.Excel
 
let data = WorldBankData.GetDataContext()
 
let app = new ApplicationClass(Visible = true)
let workbook = app.Workbooks.Add(XlWBATemplate.xlWBATWorksheet)
let worksheet = (workbook.Worksheets.[1:?> Worksheet)
 
let titles = [| "Year""Values" |]
 
let getDataFrom indicator = 
    let years = Seq.map fst indicator
    let values = Seq.map snd indicator
    (Seq.map2(fun x y -> (x, y)) years values)
    |> Seq.map (fun (x, y) -> [|float(x); y|])
    |> array2D
 
[<EntryPoint>]
let main argv = 
    let murica = data.Countries.``United States``
    let life = murica.Indicators.``Life expectancy at birth, total (years)``
 
    worksheet.Range("C2""D2").Value2 <- titles
    worksheet.Range("C3""D55").Value2 <- (getDataFrom life)
 
    let chartobject = (worksheet.ChartObjects() :?> ChartObjects).Add(400.020.0550.0350.0) 
    chartobject.Chart.ChartWizard
       (Title = "Life Expectancy (All) at birth in the United States", 
        Source = worksheet.Range("D2""D55"),
        HasLegend = false,
        ValueTitle = "Life Expectancy (years)",
        CategoryTitle = "year (0 = 1960)",
        Gallery = XlChartType.xlXYScatterLines)
    0



Our output:




We've increased life expectancy by 10 years since 1960 in the US!


Edit:

The talented folks working on the lower-level happenings of F# have an FSharp.Charting library which I just found out about. Using this library in a .fsx script file, executing with Alt+Enter, I get the same graph even quicker!

#r "../../../bin/FSharp.Data.dll"
#load "../../../packages/FSharp.Charting.0.90.7/FSharp.Charting.fsx"
open FSharp.Data
open FSharp.Charting
 
let data = WorldBankData.GetDataContext()
let murica = data.Countries.``United States``
let life = murica.Indicators.``Life expectancy at birth, total (years)``
Chart.Line(life,Name="Life Expectancy (All) United States")
     .WithYAxis(Min= 68.0, Title="Life Expectancy in Years")
     .WithXAxis(Title="Year")


Result:


5 Pitfalls of C# Beginners

The programmer's brain is vastly different from the average persons'.  However, a programming mind did not develop overnight. As with any other, it is a product of the experiences placed upon it. Learning programming for the first time with C# can be difficult. There are enough shortcuts in C# that simply aren't clear to the beginner. Here are 5 pitfalls.


1. Reference and value types

This is an extremely fundamental part of C# outside of primitive types (int, bool, string, double, etc).  Meaning, if you are writing consumer-grade software, not Project Euler problems or the like, you will need to know this.

Simply put, value types are just values. Reference types point to something in memory. 

The example that comes to mind that was the ultimate point where it "clicked" for me was when it came to List<T>.  I had a List of objects that I wanted to change. I wanted to change that specific list, not a copy of it. Because List<T> is a reference type, you can pass it through a method and you will modify the List you passed in.  Here's the example:

static List<int> numbers = new List<int>(){
    1,2,3,4,5,6,7,8,9,10
};
 
public static void multiplyBy2(List<int> someList)
{
    for(int i = 0; i < someList.Count; i++)
        someList[i] *= 2;
}
 
static void Main(string[] args)
{
    multiplyBy2(numbers);
 
    //numbers now contains values
    //2,4,6,8,10,12,14,16,18,20
}

2. Object initialization syntax

I already prefaced this in number 1. C# unlike other languages has really sweet object initialization syntax. You can set values of properties when you call the object constructor. This should be taken advantage of to its fullest extent.  In my previous example:

static List<int> numbers = new List<int>(){
    1,2,3,4,5,6,7,8,9,10
};
I created the List<int> named numbers and set all values 1 .. 10 inside it. This was done without calling some kind of loop after using new or calling numbers.add(1).. and so on.  Here's another example:

class Drug
{
    public double Dosage;
    public string Name;
}
 
Drug aspirin = new Drug() {
    Dosage = 81,
    Name = "Aspirin"
};

We can still call the constructor if we wanted, but this makes it very clear that the Drug instance aspirin has Dosage = 81 and Name "Aspirin."  

3. Getters and Setters

This is probably one of the biggest sore spots for beginners. It's worse for newbs in C# because of the shortcut syntax. If we extend our Drug example:

class Drug
{
    public double Dosage { getset; }
    public string Name { getset; }
}
This means very little to a beginner. When I was starting out, I was doing Windows 8 metro apps. Since it had a Windows Presentation Foundation (WPF) base, you had to use the get, set syntax to make things WPF friendly. What exactly does the above syntax mean?  It can be expanded out to this:

class Drug
{
    private double _dosage;
    public double Dosage
    {
        get {
            return _dosage;
        }
        set {
            _dosage = value;
        }
    }
 
    private string _name;
    public string Name
    {
        get {
            return _name;
        }
        set {
            _name = value;
        }
    }
}
Stopping point:
  1. Both Dosage and Name are not variables of Drug. They are convenient names for methods that could be named Drug.getDosage(), Drug.setDosage(double _dosage), etc.
  2. We have private variables named _dosage and _name, which is where the respective values are stored.
  3. value is a built-in C# keyword.

Now suppose we do the following:
Drug aspirin = new Drug() {
    Dosage = 81,
    Name = "Aspirin"
};
 
Console.WriteLine(aspirin.Name) //calling get{ } of Name
We indicate that we want the value of Name from Drug instance named aspirin. Thus, the get() method of aspirin is called, which returns our backing value Drug._name.

Now the set() is a little trickier:
Drug aspirin = new Drug() {
    Dosage = 81,
    Name = "Aspirin"
};
 
aspirin.Name = "Motrin";
We are unhappy with the name "Aspirin" of Drug instance aspirin. We want to give it the brand name "Motrin". So we set the Name = "Motrin". The "=" indicates that we are calling the set(..) method of the property Name.

Look more closely:
private string _name;
public string Name
{
    get {
        return _name;
    }
    set {
        _name = value;
    }
}
Inspect, "_name = value" you will find that value  = "Motrin", so we set_name to be "Motrin".

The purpose of these methods is for better encapsulation of your values, a prime object-oriented concept.

4. LINQ

Some people dislike C# for whatever reason. That reason is never Language Integrated Query (LINQ), which is arguably C#'s best feature.

static List<Drug> drugs = new List<Drug>(){
    new Drug("Aspirin"81),
    new Drug("Tylenol"325),
    new Drug("Aleeve"220),
    new Drug("Dextromethorphan"50),
    new Drug("Benadryl"25),
    new Drug("Claritin"10)
};
 
static void Main(string[] args)
{
    var DrugsILike = (from drug in drugs
                      where drug.Dose > 50
                      orderby drug.Name
                      select drug);
 
    var DrugsILike2 = drugs.Where(d => d.Dose > 50)
                           .OrderBy(d => d.Name);
}
As a pure syntax standpoint, there is no need to iterate over the entire collection with a loop, as you would in Java. Here, drugs is filtered based on Dose and sorted by name. Both are equivalent statements, both using LINQ. 

The output for both these using LINQPad is this:



5. The null coalesce ?? operator

We can protect ourselves from using an object reference that would point to a null instance. Traditionally, we can check to see if the instance is null with an if-statement, however we can just use the null coalesce operator (??)


One of the most infuriating exceptions

Example:
static Drug getNewDrug(Drug d)
{
    return d ?? new Drug("Whoops!"0.0);
}
 
static void Main(string[] args)
{
     Drug a = getNewDrug(null);
     Console.WriteLine(a.Name); //"Whoops!"
}

These were 5 pitfalls of C# newbs. Perhaps some at the intermediate level may forget about some of these language features as well. Any suggestions on other things we forget, please leave a comment!