Saturday, January 29, 2011

Primes, Sums of Primes, 2011 in C#

{

I had no idea:

2011 = 157 + 163 + 167 + 173 + 179 + 181 + 191 + 193 + 197 + 199 + 211

After learning that not only was 2011 was prime, but that it was the sum of consecutive primes, I sought to write some C# code that would demonstrate this. I wrote it in a functional style, meaning at some point to port it to F# – you'll recognize my in a forthcoming post on computing primes with F# which is actually an implementation of the algorithm I first worked through in the below C#.

Func<long[], IEnumerable<KeyValuePair<long, string>>> GenerateConsecutivePrimeSums = (primes) =>
{
List<KeyValuePair<long, string>> primeSums = new List<KeyValuePair<long, string>>();
for (int i = 0; i < primes.Count(); i++)
{
List<string> operands = new List<string>();
long primeSum = primes[i];
operands.Add(primeSum.ToString());
for (int j = i + 1; j < primes.Count(); j++)
{
primeSum += primes[j];
operands.Add(primes[j].ToString());
if (!primeSums.Any(ps => ps.Key == primeSum) && primes.Contains(primeSum))
{
primeSums.Add(new KeyValuePair<long, string>(primeSum, String.Join(" + ", operands.ToArray())));
}
}
}

return primeSums;
};

Action primesAndSums = () => {
// generate primes up to 2020
var primes = GeneratePrimes(2020);
// generate arrays of consecutive primes that add up to prime
var primesSummed = GenerateConsecutivePrimeSums(primes.OrderBy(a => a).ToArray());
// go through the summed primes (dictionary of prime as key, added numbers as value)
// Console.WriteLine formatted results
primesSummed
.OrderBy(ps => ps.Key)
.ToList()
.ForEach(ps => Console.WriteLine(ps.Key + " = " + ps.Value));
};

primesAndSums();


 



The code actually calculates sums of the primes it generates, click here for all the other primes which are sums of consecutive primes up to 2020:



}

Monday, January 24, 2011

Interesting Data Points From How Facebook Ships Code

{

I ran across this blog entry which is an unofficial attempt by somoene to glean the internal workings of Facebook’s product and software development processes. There are some very interesting things to be noted, most of which I’ll just quote from the article directly:

“resourcing for projects is purely voluntary”

It’s interesting from this unofficial post that project dynamics are organic and based on what engineers want to work on. It begs the question of how the more difficult and less pleasing problems are solved but I would hedge that by having people who are talented and motivated, difficult and more grimy problems might be what attract people that are always seeking challenges. Indeed, from later in the article: “engineers generally want to work on infrastructure, scalability and “hard problems” — that’s where all the prestige is.”.

“Engineers handle entire feature themselves — front end javascript, backend database code, and everything in between.  If they want help from a Designer (there are a limited staff of dedicated designers available), they need to get a Designer interested enough in their project to take it on.  Same for Architect help.  But in general, expectation is that engineers will handle everything they need themselves.”

This is one of the more fascinating points because it reflects one side of an approach to programming that I’ve encountered: that delivering some functionality is a process of ownership where a person generalizes across disciplines and technologies. The opposing viewpoint sees programming more in terms of division of labor with staff assigned to “tiers” of the technological back end: database developers, “business layer” or component programmers, user interface and so on. I always think of sports with this dichotomy where the former thinks of software development like basketball – a game that involves some specialization but really rewards the generalist who can play any role on a team, and football – a game of specialists where it’s a liability to do too many things since even the physique is developed on a per position basis.

Many people acknowledge generalists for small organization but it appears that Facebook, a company as large as they come, prefers them.

“engineers responsible for testing, bug fixes, and post-launch maintenance of their own work.  there are some unit-testing and integration-testing frameworks available, but only sporadically used.”

There are a few edits and comments to this point but the reason I find it interesting is that they are a corollary to the views that Joel Spolsky expressed on the StackOverflow podcast. Many developers, myself included, berate ourselves on a lack of unit testing with the assumption that “everyone is doing it, why can’t I?” As time passes, however, I realize that TDD and Unit Testing are very important but not essential. It’s a very unpopular opinion and while I admit that I strive to make my code testable and, especially on personal projects where I have enough control, architect my software so that it’s testable from the get-go.

}

Saturday, January 22, 2011

Learning F# with FizzBuzz: Match

{

I had previously done a solution for FizzBuzz in F# (from a long time ago) but now that I’m more familiar with the idioms of F# I tend more towards pattern matching instead of if/else logic for quite a few scenarios. Here is an example of my rewriting what could otherwise been a conditional if/else checking for factors of 3 and 5, but using a pattern match instead.

#light 
let fizz num =
match (num % 3 = 0) with
| true -> "fizz"
| false -> ""

let buzz num =
match (num % 5 = 0) with
| true -> "buzz"
| false -> ""

let outform num fizCalc =
match fizCalc.ToString().Length = 0 with
| true -> num.ToString()
| false -> fizCalc

let rec printer nums =
match nums with
| [] -> printfn "-"
| h::t ->
printfn "%s" (outform h ((fizz h) + (buzz h)))
printer t

let numbers = [1..100]
printer numbers




Although I read claims that if/else conditional operations are more readable, I think the pattern match used consistently across scenarios above makes for something I find quite readable.



}

Thursday, January 20, 2011

On Leadership

{

“If you want to build a ship, don’t drum up people to gather wood, divide the work, and give them orders. Instead, teach them to yearn for the vast and endless sea”

- Antoine De Saint-Exupery, author of "The Little Prince"

Originally posted on Chris Sells’s blog but worth some thought.

}

Wednesday, January 19, 2011

Download .NET Source Code

{

I’ve been having a problem that warrants looking at the source which can be downloaded right here.

}

Learning F# with FizzBuzz

{

Eons ago I'd posted on how I’d rewritten how I would solve FizzBuzz to have a more functional style (here is an imperative version), inspired by Tomas Petricek and John Skeet’s Functional Programming for the Real World. Shortly thereafter I had written a version in F#, I’m not sure what prevented me from posting it but here it is:

let numbers = [1..100]
let fizz num =
let res = if (num % 3 = 0) then "fizz" else ""
res

let buzz num =
let res = if (num % 5 = 0) then "buzz" else ""
res

let outform num fizCalc =
let res = if(fizCalc.ToString().Length > 0) then fizCalc.ToString() else num.ToString()
res

let rec printer nums =
match nums with
| [] -> printfn "-"
| h::t ->
printfn "%s" (outform h ((fizz h) + (buzz h)))
printer t

printer numbers


I can already see now areas that are still influenced by the C# - most notably the use of if rather than using match for everything. I will clean it up, hopefully demonstrating an increased facility with F#. If you are looking at the above and know F#, what are some idioms or language constructs that I am neglecting in the above code? Type annotations for one... what else?



}

Sunday, January 02, 2011

Information Diet Planning – Newsletters

{

Given the amount of information that is out there it’s difficult to throttle back and actually digest it. A quick look at any web page will set that context; hit StackOverflow and you’ve got several dozens of links to follow, each a rabbit hole on its own. The same can be said for Hacker News, Channel 9, and just about every other popular developer site that is out there.

What tools exist to process this more efficiently? Perhaps, I hope, one of the oldest tools out there: email.

I came across this solution reading the Washington Post’s email newsletter I subscribe to one morning. I realized I’d get more out of the news by scheduling a more deliberate reading of the newsletter than by going to the site and being bombarded by stories and links that, while no doubt interesting, would result in an overflow of words that would invariably lose their depth.

I decided for the next week not to visit any news site directly but rather to subscribe to several newsletters and schedule the reading from directly from my email inbox. I also turned off the radio so that rather than hearing multiple versions of syndicated stories from the Associated Press, I would be able to dive more deeply and think more at length about what I read. The goal was to buck the trends of the modern day information seeker:

“characterised as being 'horizontal, bouncing, checking and viewing in nature. Users are promiscuous, diverse and volatile.' 'Horizontal' information-seeking means 'a form of skimming activity, where people view just one or two pages from an academic site then "bounce" out, perhaps never to return.' The average times users spend on e-book and e-journal sites are very short: typically four and eight minutes respectively.”

I wanted to get more vertical with my reading rather than surfing through multiple versions of the same piece of news.

I was so pleased with the results that I decided to use the same strategy with technical news and articles. I have long been a member of The Code Project and of the software development newsletters I receive (surprisingly few) theirs is probably the best. Each day, and then in a weekly digest, there is an email in my inbox with a decent roundup of technical articles. Although not all of them pertain to my skills set or interests, there are usually one or two good links to follow up with; in this newsletter received on the last day of the year I could easily spend an hour on The Best Technology Writing of 2010 or catch up with Rob Connery giving his sentiments on BizSpark.

The experiment will continue and although I do admit to “skimming” from time to time, even the tepid commitment that I’ve made seems to make my time online much more efficient. The next steps regarding newsletters is to find some more development related ones that come in a digest form, preferably weekly so that I can spend a full week on the contents.

}