Skip to content

Project Euler, Problem 6, in Erlang

Problem 6 was surprisingly straight-forward.

“Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.”

Really, just a straight-forward calculation, easily implemented in Erlang recursive-speak. No real comments on this one.

-module(euler6).
 -export([difference/1]).

 difference(N) ->
    SumSquare = sumofsquares(0,N),
    Sum = squareofsum(0,N),
    SquareSum = Sum * Sum,
    io:format("Square ~w Sum ~w ~n", [SquareSum, SumSquare]),
    Difference = SquareSum - SumSquare,
    Difference.  

sumofsquares(Sum,N) ->
    if N >= 1 ->
       NewSum = (N*N) + sumofsquares(Sum,N-1);
    true ->
       NewSum = Sum
    end,
    NewSum.

squareofsum(Sum, N) ->
     if N >= 1 ->
       NewSum =  N + squareofsum(Sum, N-1);
     true ->
       NewSum = 0
      end,
     NewSum.

Project Euler, Problem 4, in Erlang

Problem 4 is an interesting one. “A palindromic number reads the same both ways. Find the largest palindrome made from the product of two 3-digit numbers.”

I thought about this for a few minutes and decided the best way to approach it would be to build candidate palindromic numbers and and then test them to see if they were the product of two 3 digit numbers.

It’s easy to see that the product of two 3 digit numbers could at most be 6 digits, so I decided that I would start building my candidate palindromes by counting down from 999 and adding the mirror of the number as a suffix. Example – take 998 and add 899 to the end for 998899. Then I would test each candidate by dividing by all possible three digit numbers and seeing if I could find a three digit cofactor for any even divisions. For example, if a candidate was evenly divisible by 123, was the cofactor also a three digit number?

So this problem was mostly centered in the approach. Once I’d settled on that, the Erlang code came easily. A little more work than I’d like building the palindromes due to single assignment, but nothing too bad. I can see how single assignment will be a pain in some situations though.

The code – - edoc ehT

 -module(euler4).
 -import(lists).
 -export([greatestpalindrome/1]).

 greatestpalindrome(N) ->
     Greatest = palindrome(N),
     io:format("Greatest is ~w", [Greatest]).

 palindrome(N) ->
    if N >= 100 ->
      Candidate = buildpalindrome(N),
      Success = testpalindrome(Candidate,999),
      if Success == true ->
         Candidate;
      true ->
         palindrome(N-1)
      end;
    true ->
      io:format("no match found~n")
    end.  

 buildpalindrome(N) ->
    Nstring = integer_to_list(N),
    ReverseN = lists:reverse(Nstring),
    Palindrome = Nstring ++ ReverseN,
    Npalindrome = list_to_integer(Palindrome),
    Npalindrome.

testpalindrome(N,Testfactor) ->
    if Testfactor >= 100 ->
       if N rem Testfactor == 0 ->
          Cofactor = round(N / Testfactor),
            if Cofactor >= 100, Cofactor =< 999 ->
                true;
            true ->
                false
            end;
       true ->
            testpalindrome(N,Testfactor - 1)
       end;
     true ->
       false
    end.

Project Euler, Problem 5, in dirty dirty Erlang

I did complete Problem 4 already, but the write up will take a bit of time. So I went ahead and did Problem 5, in a very quick and dirty way.

Problem 5 – “What is the smallest number that is evenly divisible by all of the numbers from 1 to 20?”

The total elapsed time from reading the problem to having the answer was less than 10 minutes. The first instinct is to just brute force the thing, and that’s what I did.

I did make some small optimizations, things that occurred to me in the couple of minutes I spent thinking about it.

1 – There’s no point in testing divisibility by numbers 1-10, since anything that’s divisible by 11-20 will of necessity by divisible by 1-10. (ie each of the numbers 1-10 are factors of at least one of the numbers 11-20).

2- There’s no point in testing divisibility by 20, since we’re starting with 20 and incrementing by 20. All candidates will be divisible by 20.

I have no doubt that this can be optimized considerably. It takes 22 seconds to complete on my netbook, an eternity! But this code makes me laugh, so here it is.

Called by euler5:lowest(20).

Brutish code -

 -module(euler5).
 -export([lowest/1]).

  lowest(N) ->
     if
	N rem 19 == 0,
 	N rem 18 == 0,
 	N rem 17 == 0,
 	N rem 16 == 0,
 	N rem 15 == 0,
 	N rem 14 == 0,
 	N rem 13 == 0,
 	N rem 12 == 0,
 	N rem 11 == 0 ->
              N;
      true ->
          lowest(N+20)
      end.

Project Euler, Problem 3, in Erlang

When I first read Problem 3 I thought it was going to be more involved than it turned out to be.

“What is the largest prime factor of the number 600851475143 ?”

And I started thinking I’ll need to list the factors and test them for primality, or find primes first and test only those for being factors, etc.

But after thinking about how to actually factor the number, I remembered factor trees and how they’d lead me to prime factors by default. And as an added bonus, factor trees are inherently recursive! This wasn’t going to be so bad after all.

For some reason I got hooked on the idea that I needed to build a list of the factors, and then at the end I would find the largest of them. Eventually I realized I just needed to track the largest so far; I think I just wanted to fiddle with lists in Erlang.

The Erlang came pretty easy to me this time. I’m adjusting to the structures imposed by Single Assignment, which was conceptually a challenge at first. The idea of immutable variables just seemed so wrong! But I’ve read more and understand why that’s the case and I’m getting a feel for how to deal with them.

The only real Erlang catch came from the line that finds the co-factor of the most recently found factor – “Cofactor = round(N / Factor)”. You’ll notice the “round” function there. The division returned a floating point number, when what I wanted was an integer. Casting variable types turns out to be a bit clunky in Erlang, mostly done by BIFs (Built In Functions) with unwieldy names like “integer_to_list” and so on. But there is no “float_to_integer” BIF! So it had to be the “round()” function. While fine in this case, I’m not sure this will always do what I need it to do.

A couple of other notes- This isn’t very optimized, I’m intentionally not optimizing in this initial pass. I do plan to revisit and refactor down the road, once I have a better idea what I’m doing. I did sneak in an optimization in the factor search, limiting the upper end to the square root of the number we’re looking for factors of. That’s a very simple trick which does save some iterations (if you haven’t found a factor by the time you reach the square root of a number, you’re not going to). I could have further limited the search range by limiting the lower end to being equal to or greater than the previously found factors, but that would add parameters to the functions so I skipped it for now.

One last thing, the program doesn’t seem to work properly on very large numbers (giving me a factor of “2″ on numbers that aren’t even, for example), I’m not sure why. Probably some sort of overflow condition.

My code of codes-

 -module(euler3).
  -import(math).
  -export([greatestprimefactor/1]).

  greatestprimefactor(N) ->
     Greatest = factor(1,N),
     io:format("GPF is ~w~n", [Greatest]).

  factor(Greatestsofar,N) ->
    Max=math:sqrt(N),
    Factor = nextfactor(Max,2,N),
    if
      Factor > Greatestsofar ->
            Newgreatest = Factor;
      true ->
            Newgreatest = Greatestsofar
    end,
    Cofactor = round(N / Factor),
    io:format("Factor ~w~n",[Factor]),
    if
      Cofactor == 1 ->
           Newgreatest;
      true->
           factor(Newgreatest,Cofactor)
    end.

 nextfactor(Max,X,N)->
      if
       N rem X == 0 ->
 	    X;
       X =< Max ->
            nextfactor(Max,X+1,N);
       true ->
            N
       end.

Project Euler in Erlang, Problem 2

Problem 2 is again stated simply- “Find the sum of all the even-valued terms in the (Fibonacci) sequence which do not exceed four million.”

The Fibonacci Sequence is the sequence which runs 1, 2, 3, 5, 8, 13, 21 etc. in which each term is the sum of the previous two terms.

Again, conceptually easy. Just run the terms until one exceeds 4,000,000 and sum those which are divisible by 2.

In a procedural language, this is another problem that I can solve as fast as I can type. It’s very straight-forward in approach.

But I’ve quickly learned that recursion is the default thought-process for the functional language Erlang, so I immediately set about trying to think of the problem recursively. I admit to heading down a couple of dead end paths at first, really just approaching it from the wrong end. I kept worrying about building the terms when what I really wanted to do was focus on accumulating the sum. Once I realized that, everything fell into place quickly. The end result is a little messy, having to call the function with seed values – sumofevenfib(1,1,0) and having the cutoff value of 4,000,000 hardcoded. But it works.

Only a couple of problems into the euler series, but I’m getting the effects I wanted. Spending a lot more time studying up on Erlang, reading about why it’s designed the way it is, and understanding what the syntax is really saying and so on. Also learning to move from the procedural-by-reflex mindset I’ve developed over years and years of coding to a more functional approach. There’s definitely a switch I need to flip over in my head about that kind of thing.

Le code -


-module(euler2).
-export([sumofevenfib/3]).

sumofevenfib(Prev,Cur,Sum) ->
   Next = Prev + Cur,
   if
      Next =< 4000000 ->
       if
         Next rem 2 == 0 ->
           sumofevenfib(Cur,Next,Sum+Next);
         true ->
           sumofevenfib(Cur,Next,Sum)
       end;
      true -> Sum
    end.

Project Euler, Problem 1

Getting started with my quest via my first attempt at a solution in Erlang to Project Euler’s problem number 1.

The problem itself is simply stated : “Find the sum of all the multiples of 3 or 5 below 1000.”

A naive algorithm is immediately apparent- cycle through each number between below 1000 and sum those that are evenly divisible by 5 or 3. While hardly sophisticated or efficient, it’s an algorithm that will work.

In thinking about how to do this in a functional language like Erlang, it seems the obvious approach is recursion. A function that takes a number N as an input and calls itself for N-1, adding N to the result of the recursive call if N is evenly divisible by 3 or 5. I also decided to make the determination if N was a 3 or 5 multiple its own function.

So conceptually, the answer and the approach came pretty quickly. I stumbled a bit on implementation mostly due to not understanding Erlang’s if-statement at all. Once I sussed out the oddities there (including not being able to call a function in a guard expression- this puzzles me, but I also get the feeling that understanding why this is true is important to my grokking Erlang. I must explore further), the functions fell into place and I had a tiny understanding of how to start thinking about this sort of thing.

It’s been too long for me. Tiny little baby steps needed. I could have written this in a C-like language as fast as I can type. This took a bit longer. :-)

My magnificent code for Problem 1.

-module(euler1).
-export([sumof3and5multiples/1]).

sumof3and5multiples(0)->
	0;
sumof3and5multiples(N) ->
	Multiple = ismultipleof3or5(N),
	if
          Multiple == true ->
	    N + sumof3and5multiples(N-1);
          true ->
	    sumof3and5multiples(N-1)
	end.   	

ismultipleof3or5(X) ->
	if
	   X rem 3 == 0 ->
	     true;
	   X rem 5 == 0 ->
	     true;
	   true ->
	     false
	end.

Learning Erlang Via Euler

I’ve been doodling with Erlang of late, attempting to make up for what I missed by not diving into functional programming long ago. I’ve slacked off in my progress, lacking any coherent project to apply it to.

But in the last few days I stumbled across Project Euler, a site that presents a number of mathematical problems of increasing difficulty. It’s meant to serve as a structure for learning more about certain computer science and math concepts, which, oddly enough, is something I’m looking to do. It’s also a nice structure to learn to start applying some functional programming concepts. So I’ll have a series of posts about my approaches and solutions to the various problems, starting with problem 1.

Hey, everyone needs a hobby!

Google Wave As Transmedia Hub?

I’ve been reading up on Google Wave and thinking about it’s potential as a hub for transmedia activities.

Wave is the next step in Google’s ongoing move towards development of collaborative tools, following on Google Apps, Calendar, etc. Those were the obvious first step, Wave is the next generation tool, bringing in real time conversation and extensibility. If Wave becomes a default part of the Apps package that Google offers, along with an easy migration path from gmail, it could see relatively quick adoption.

The extensibility of Wave is key- if something useful is missing from Wave, it can be added by the public rather than waiting on Google to add it. We can expect most major social applications to eventually supply Wave support of some kind. Alternatively, if there’s something Google does “wrong” in the basic Wave server, developers can “fix” the problem with their own custom development. For example, if Wave search is as poorly implemented as gmail search, a developer could provide a better search module (perhaps even using the Google Custom Search api!).

It’s also important to note that Wave itself is essentially a set of open protocols, and that users are allowed to provide their own Wave servers. Indeed, it’s quite possible to develop custom extended servers. We will quickly see special-purpose Wave servers developed for a variety of custom needs.

There will probably even be custom Wave servers developed for transmedia campaigns. Since the basic technology is already highly social, collaborative, and real-time, it’s well suited for transmedia events. Twitter, Facebook, wikis, Youtube, blogs -they can all tie in or be replaced via Wave technology. All parts of the campaign could eventually be collected and centralized on a Wave. Games can be added, music could be added, maps, etc. And link friction (a measure of how easily a link can be spread) should be near zero, due to the real-time collaborative nature of a Wave.

There’s a lot of potential in Wave, can’t wait to see what happens when it’s released to the public!

Project Natal and Milo- Real, Fake, or Scripted? An Analysis

So there’s the video from E3 of Peter Molyneux showing off a project his company is working on, based on Microsoft’s Project Natal.   It’s a character named Milo living in a tiny virtual world.  The video shows a woman named Claire interacting with Milo in ways that seem wondrous and amazing.

But how much of what we think we see is what we’re actually seeing?

Let’s go through the video step by step.

First Claire says “Hi Milo, how are you doing?”  Milo stops swinging and walks to camera. What happens here? Milo’s voice recognition hears “Milo” and triggers Milo from the swinging loop to interact with the person. Milo walks towards portion of screen near Claire. Camera could be coordinating that move to that location. If more than one person was in the room, would Milo know where to go? Possibly, with voiceprint matched to facial recognition. There was also a cue icon on the screen that seemed to indicate what the user was to do to start the encounter.

Milo says “Hi Claire, are you ok?” Probably a canned response. Name based on voiceprint? Face? Scripted? How is “Claire” articulated? Prerecorded? Carefully built from phenomes? Milo’s voice in general for that matter.  “Are you ok?”  is a bit of an odd choice.  Was there some sort of stress detected in her voice.

Milo “You? Nervous?” Voice recognition? Milo’s face a little surprised. Eye contact is direct, camera tracking at work?

Claire, “This is the first time thousands of people are going to see this” Milo, “Thousands of people?”.  To me, the most suspicious part of the whole interaction. How is this accomplished? How does Milo identify the phrase to repeat? Voice emphasis from Claire? Again, how is the phrase articulated? Built from phenomes? How big is Milo’s vocabulary? What’s the icon on the screen indicating? It seems to be a microphone.

Milo’s eyes wander nervously. Why? Because thousands of people are watching? No way, too much cognition there, I don’t believe it. Reading Claire’s mood from face and voice cues and reflecting it? Possibly. Possibly.

“Let me beat you at football, that is if you finished your homework”. No reaction to “football”, which you’d sort of expect to be a keyword in a gaming system, if Milo is some sort of operating system interface anyway. He’s looking anxiously off to the side during this, possibly indicating the fishing activity he wants to get to?

“Homework” is a clear vocal keyword, triggering emotional cues from Milo expressing resentment at being reminded of his shirked responsibility. Possible that her scolding tone and “school projects” furthers the shame reaction from Milo.

Milo seems to be confessing while we can’t hear clearly under the narration.

Claire’s mention of “help” in a cheery way seems to trigger Milo’s own cheery response, though he immediately forgets the homework assignment and walks over to the pond. Proximity triggers pond-approach, or was this a plan all along?

Walking along the rocks seems pretty scripted, but note Claire’s turning to the side. Does this trigger camera to follow along as if she is walking beside him?

Milo sort of ignores her, says everything they need is there. Seems to go into brief idle mode until she says “let’s get started”, possible keyword.

Then the goggle tossing, which is brilliantly done with visual and aural cues. Notice the  “slapping” sound that catching the goggles makes.

Milo shows how to put goggles on, perhaps indicating the gesture that Natal will recognize for this action. If so, a nice subtly natural education of the user. Backed up by an icon at the bottom of the screen, somewhat clumsier.

Approach to the water is silent, nothing from Milo. Triggered by putting on goggles? Clearly some computational pausing here, then a version of Claire appears reflected in the water. Another small but brilliant cue. Possibly done via Natal’s skeletal model and then mapping colors via the camera?

The interaction with the water seems to be basic Natal. Track hand motions and animate based on that. Some prodding from Milo to push the user into further interaction.

Is Milo’s response “They’re only fish” a response to Claire’s compliment? Impressive if so, implying vocal tonal cues and possibly vocal vocabulary, maybe expression recognition. But also possibly just canned.

Passing the pic into the screen is a simple but brilliantly immersive trick. Full points!

Milo seems to react to the color of the drawing? Again, simple but effective trick.

A goodbye script triggered by either vocal cues or body language. Nice touch of reminding of Mom’s birthday.

So overall there’s a lot that’s being accomplished by some basic tricks.  These tricks aren’t really “fake”, they’re just effective interactional cues.   Another layer seems to be accomplished via an Eliza like interface, though there’s some implied vocal analysis and synthesis I question.

And a great deal is accomplished just by affective computing- reading, responding to, and synthesizing vocal and kinesthetic emotional cues.

Is the system as intelligent as it’s read to be on a surface reading?  No, probably not.  But does it need to be that smart in order to be effective?  No, I don’t think so.  I think the basic tricks it seems to use are valid, and I think they can be quite powerful.

What we really need is more footage, of course!

Marketing your webseries – entrypoints and interactions

Adapted from a post on the message boards at the fantastic screenwriting site Wordplayer. Read everything everywhere on that site if you want a deep understanding of how to write a screenplay.

So with my web sketch comedy group Monkey With A Shotgun, I’ve got an actual revenue-generating video series over on Babelgum.

Babelgum is a distribution channel, like YouTube.  Much lower traffic (less than one-half of one percent of Youtube’s traffic), but still a solid, reliable delivery system.  What they are not is a marketing or promotional company.  In fact, the whole reason they’re paying for webseries is to bring more traffic to their site.  So for that to work, the series has to, you know, bring in traffic..

That leaves the filmmakers responsible for marketing.  This is true for any independent project, from video series to feature film.   If you’re on a studio project you’re less responsible for marketing the project, though you should still be very aware of marketing your personal career.   But even if an indie feature gets theatrical distribution, the filmmakers will still be the primary marketers.  Direct to video, you’ll live or die by your own promotion. And internet shorts? There’s no one but you.

The good news is that the internet makes it possible to pull off your own promotion.  You still might get lucky and get some mainstream coverage, say a NPR interview, but even if you don’t you can do much for yourself.

The secret of a good internet marketing campaign is simple- Allow as many entrypoints into the campaign as possible and feed them all into a sticky, central site.

By entrypoints, I mean that you want people to have as many ways to stumble on your work as possible.  You want to be on as many sites as can, hitting as many different audiences as you can.  You don’t really know where your fans are, and you can’t rely on them to come to you, so you want to cast your net wide.  To some extent this is a numbers game.

What does this mean in practice?  Well, ideally you’d put your video on every single video site there is.  That’s not practical with this particular scheme since the revenue is only being generated by Babelgum views, so you want people to watch there.  That could change with other revenue sources, if you had a brand sponsor, or the video itself was promoting other sales, or merchandising of elements of the series itself.

But even in this case there are many other venues for promotion.  There’s mentions on blogs.  On sites that cover the internet video industry.  Interviews with the filmmakers.  I’d push hard to get every reviewer I could, pro and amateur to review the series.  It almost doesn’t matter what they say, as long as they link back to you.  Even a pan review will pique curiosity.

This goes back to an old web aphorism – “Links are the currency of the internet.”   That is, links to your work have a definite value.  The beauty of the web is that it is a web, a mass of interconnections leading from point to the next.  It can all tie back into your site, everything leading to your point of revenue generation.  You want those links, they’re your gold.

You can also use social networks.  I’ve seen some effective work in promoting web series via facebook fan pages.  Fan pages are an easy way to keep people in the loop and aware of what’s going on with your series.  New episodes, where you’re planning to take things, etc.   It’s not something you have to do, but it’s definitely a missed opportunity if you don’t.

Then there’s the king of the social media hill these days, Twitter.  Twitter is a complicated beast to tame. A lot of people give up too soon on it, but Twitter is potentially the most powerful tool in your internet marketing arsenal (at least this year).

The one thing you need to know about Twitter is this- Twitter is personality.

It’s not about hawking your wares, not directly, it’s about making connections with people on the basis of you personality. Your Twitter persona can be a selective version of your personality (or maybe even a constructed version), but it has to be a personality. It’s about being intelligent, interesting, and entertaining.  If you pull that off, people will naturally be interested in what you’re doing, and since they have that personal connection with you, they’ll help you spread the word.

I’ve been watching people build their careers with Twitter being a primary source for their advancement.  Making the connections, building the interest in what they’re doing.  It may sound sales-y to you, but I’m actually saying the sales-y stuff doesn’t work that well. Remember- intelligent, interesting, and entertaining.   Personality.   And if you’re excited about what you’re doing, it’s not exactly work to talk about it.   And if you’re not excited about it, why are you doing it at all?

The nice thing is that a lot of the indie film community- filmmakers, reviewers, reporters, festivals, distributors – have really taken to Twitter, and there’s a nice community already there.  For any of your projects, you really want to get as many of your cast and crew on and talking about the project as possible.  Make those person-to-person connections.

So that’s many-entrypoints part.  What about the sticky, central site part?

What you really want a central site that keeps people coming back once they’ve come to visit it once or twice. The key is to build a community around the site itself.  The filmmakers should be producing longer form blog postings about the experience of making the project and the aftermath.   More insight into the process, into the people.  Allow comments, and RESPOND to those comments! Interact with your audience.  Provide forums for people to discuss your project.  What they think about it, what they would like to see, etc.  Again, INTERACT.  You want people to come to your site for your content discover there’s a whole world there to explore.  And to return to.

One very important note here at the end- NONE OF THIS WORKS IF YOUR PROJECT SUCKS.  Your project has to be good or all is for naught.  Content is still king.  But community has moved into the prince’s seat.

Anyway.  Longer than intended, but there’s much more to say.

Later!