Breaking up programs
I often do small programming problems in Mathematica. The reason for this is I want to learn more about functional programing. Mathematica offers every kind of programming I’ve ever heard of. It also lets you mix them so it’s really very important to break things down first.
I happen to be working on #185 from projecteuler.net. It’s building a program that can play a game that is similar to mastermind. Yet this is the tiny brick I’m working on:
Given two lists of the same length return a list of positions where those lists are the same.
If I can’t find a function that does that, then I need to write a very fast version of it myself. (Ever play “NameThatFunction” with any library? It’s the hardest part of searching docs.) This function will be called… many times.
After things are broken down there is only one thing to do. Write each piece even if you have to write it stupid the first time and maybe improve it later.
Update: Sometimes just writing it down makes it pretty easy. I’m not sure how fast this is but this seems to work with my test cases: (sorry for the formatting)
CommonPositions[L1_List, L2_List] := Module[{c = {}},
c = L1 \[Intersection] L2;
Return[
Flatten[Map[Position[L1, #] \[Intersection] Position[L2, #] &,
c]]];
];
