Archive for the ‘Fun’ Category

E-99: 21-30

Sunday, January 7th, 2007

The next installment of the 99 Lisp problems. 27 and 28 are incomplete as I have not sat down to actually work through them yet. More research is needed to do multinomial coefficients. This batch of problems posed some challenge and required a bit of research and dusting off math skills, as well as getting familiar with Erlang’s List Comprehension syntax. For your viewing pleasure:

%% Insert an element at a given position into a list.
%% Example: (insert-at ‘alfa ‘(a b c d) 2) -> (A ALFA B C D)
p21(Elem, L, Pos) -> p21insert(Elem, L, Pos, []).

p21insert(Elem, L, 1, NewL) -> lists:reverse([Elem | NewL]) ++ L;
p21insert(Elem, [H | L], Pos, NewL) -> p21insert(Elem, L, Pos-1, [H | NewL]).

%% Create a list containing all integers within a given range.
%% If first argument is smaller than second, produce a list in decreasing order.
%% Example: (range 4 9) -> (4 5 6 7 8 9)
p22(Start, End) when Start < End -> p22range_asc(End-Start, [Start]);
p22(Start, End) -> p22range_desc(Start-End, [Start]).

p22range_asc(0, L) -> lists:reverse(L);
p22range_asc(Count, [H | L]) -> p22range_asc(Count-1, [H+1, H | L]).

p22range_desc(0, L) -> lists:reverse(L);
p22range_desc(Count, [H | L]) -> p22range_desc(Count-1, [H-1, H | L]).

%% Extract a given number of randomly selected elements from a list.
%% The selected items shall be returned in a list.
%% Example: (rnd-select ‘(a b c d e f g h) 3) -> (E D A)
%% Hint: Use the built-in random number generator and the result of problem P20.
p23(L, Count) when length(L) < Count -> p23rnd_select(L, length(L), []);
p23(L, Count) -> p23rnd_select(L, Count, []).

p23rnd_select(_L, 0, RandL) -> RandL;
p23rnd_select(L, Count, RandL) ->
Rnd = random:uniform(length(L)),
V = lists:nth(Rnd, L),
p23rnd_select(p20(L, Rnd), Count-1, [V | RandL]).

%% Lotto: Draw N different random numbers from the set 1..M.
%% The selected numbers shall be returned in a list.
%% Example: (lotto-select 6 49) -> (23 1 17 33 21 37)
%% Hint: Combine the solutions of problems P22 and P23.
p24(Num, High) -> p23(p22(1, High), Num).

%% Generate a random permutation of the elements of a list.
%% Example: (rnd-permu ‘(a b c d e f)) -> (B A D C E F)
%% Hint: Use the solution of problem P23.
p25(L) -> p23(L, length(L)).

%% Generate the combinations of K distinct objects chosen from the N elements of a list
%% In how many ways can a committee of 3 be chosen from a group of 12 people? We all know that there are C(12,3) = 220 possibilities (C(N,K) denotes the well-known binomial coefficients).
%% For pure mathematicians, this result may be great. But we want to really generate all the possibilities in a list.
%% Example: (combination 3 ‘(a b c d e f)) -> ((A B C) (A B D) (A B E) … )

% Not the most efficient way, but generate the power set for the list and remove all but the sub-lists of length K
powerset([]) ->
[[]];
powerset([H | T]) ->
SubPS = powerset(T),
lists:append(SubPS, lists:map(fun(E) -> [H | E] end, SubPS)).

p26(K, L) -> [X || X < - powerset(L), length(X) == K].

%% Group the elements of a set into disjoint subsets.
%% a) In how many ways can a group of 9 people work in 3 disjoint subgroups of 2, 3 and 4 persons? Write a function that generates all the possibilities and returns them in a list.
%% Example: (group3 ‘(aldo beat carla david evi flip gary hugo ida)) -> ( ( (ALDO BEAT) (CARLA DAVID EVI) (FLIP GARY HUGO IDA) ) … )
p27([]) -> [].

%% b) Generalize the above predicate in a way that we can specify a list of group sizes and the predicate will return a list of groups.
%% Example: (group ‘(aldo beat carla david evi flip gary hugo ida) ‘(2 2 5)) -> ( ( (ALDO BEAT) (CARLA DAVID) (EVI FLIP GARY HUGO IDA) ) … )
%% Note that we do not want permutations of the group members; i.e. ((ALDO BEAT) …) is the same solution as ((BEAT ALDO) …).
%% However, we make a difference between ((ALDO BEAT) (CARLA DAVID) …) and ((CARLA DAVID) (ALDO BEAT) …).
%% You may find more about this combinatorial problem in a good book on discrete mathematics under the term “multinomial coefficients”.
p28() -> [].

%% Sorting a list of lists according to length of sublists
%% a) We suppose that a list contains elements that are lists themselves. The objective is to sort the elements of this list according to their length. E.g. short lists first, longer lists later, or vice versa.
%% Example: (lsort ‘((a b c) (d e) (f g h) (d e) (i j k l) (m n) (o))) -> ((O) (D E) (D E) (M N) (A B C) (F G H) (I J K L))
p29(L) -> p29lsort(L).

%% code taken from Erlang Programming Examples -> List Comprehensions -> QuickSort and adapted
p29lsort([]) -> [];
p29lsort([Pivot | L]) ->
p29lsort([ X || X < - L, length(X) < length(Pivot)]) ++ [Pivot | p29lsort([ X || X <- L, length(X) >= length(Pivot)])].

%% b) Again, we suppose that a list contains elements that are lists themselves. But this time the objective is to sort the elements of this list according to their length frequency;
%% i.e., in the default, where sorting is done ascendingly, lists with rare lengths are placed first, others with a more frequent length come later.
%% Example: (lfsort ‘((a b c) (d e) (f g h) (d e) (i j k l) (m n) (o))) -> ((i j k l) (o) (a b c) (f g h) (d e) (d e) (m n))
%% Note that in the above example, the first two lists in the result have length 4 and 1, both lengths appear just once. The third and forth list have length 3 which appears twice (there are two list of this length).
%% And finally, the last three lists have length 2. This is the most frequent length.
p30(L) -> p30lfsort(L).

p30lfsort([]) -> [];
p30lfsort([H | L]) ->
Grouped = p30group(L, [[H]]),
Sorted = p29(Grouped),
p30ungroup(Sorted, []).

p30group([], Grouped) -> Grouped;
p30group([H | L], Grouped) -> p30group(L, p30insert(H, Grouped, [])).

%% insert Elem in to a group with the same length, or create a new group for the length of Elem
p30insert(Elem, [], PrevGroups) ->
lists:reverse([[Elem] | PrevGroups]);
p30insert(Elem, [ [GroupH | GroupT] | RestGrouped], PrevGroups) when length(GroupH) == length(Elem) ->
PrevGroups ++ [ [GroupH, Elem | GroupT] | RestGrouped];
p30insert(Elem, [ [GroupH | GroupT] | RestGrouped], PrevGroups) ->
p30insert(Elem, RestGrouped, [[GroupH | GroupT] | PrevGroups]).

%% remove length-specific groupings
p30ungroup([], Ungrouped) -> lists:reverse(Ungrouped);
p30ungroup([H | L], Ungrouped) when not is_list(H) -> [[H | L] | Ungrouped];
p30ungroup([Group | L], Ungrouped) -> p30ungroup(Group, []) ++ p30ungroup(L, Ungrouped).

E-99: 11-20

Friday, December 22nd, 2006

The second set of 10 problems are now in the bag. Feeling the Erlang-fu! The first set can be found here.

%% Modified run-length encoding.
%% Modify the result of problem P10 in such a way that if an element has no duplicates it is simply copied into the result list.
%% Only elements with duplicates are transferred as (N E) lists.
%% Example: (encode-modified ‘(a a a a b c c a a d e e e e)) -> ((4 A) B (2 C) (2 A) D (4 E))
p11([]) -> [];
p11(L) -> p11encode(p09(L), []).

p11encode([], Encoded) -> lists:reverse(Encoded);
p11encode([[Elem | SubL] | L], Encoded) ->
case length(SubL) of
0 -> p11encode(L, [Elem | Encoded]);
_Else -> p11encode(L, [[length(SubL)+1, Elem] | Encoded])
end.

%% Decode a run-length encoded list.
%% Given a run-length code list generated as specified in problem P11. Construct its uncompressed version.
p12([]) -> [];
p12(L) -> p12decode(L, []).

p12decode([], Decoded) -> lists:reverse(Decoded);
p12decode([[N, Elem] | L], Decoded) -> p12decode(L, lists:duplicate(N, Elem) ++ Decoded);
p12decode([Elem | L], Decoded) -> p12decode(L, [Elem | Decoded]).

%% Run-length encoding of a list (direct solution).
%% Implement the so-called run-length encoding data compression method directly.
%% I.e. don’t explicitly create the sublists containing the duplicates, as in problem P09, but only count them.
%% As in problem P11, simplify the result list by replacing the singleton lists (1 X) by X.
%% Example: (encode-direct ‘(a a a a b c c a a d e e e e)) -> ((4 A) B (2 C) (2 A) D (4 E))
p13([]) -> [];
p13([H | L]) -> p13encode(L, H, 1, []).

%% p13encode(The Remaining List,
%% The Current Element,
%% The Number Of Repetitions Thus Far,
%% The Encoded List Thus Far)
p13encode([], Curr, Rep, Encoded) ->
case Rep of
1 -> lists:reverse([Curr | Encoded]);
_Else -> lists:reverse([[Rep, Curr] | Encoded])
end;
p13encode([H | L], Curr, Rep, Encoded) ->
case H of
Curr -> p13encode(L, Curr, Rep+1, Encoded);
_Else ->
case Rep of
1 -> p13encode(L, H, 1, [Curr | Encoded]);
_Other -> p13encode(L, H, 1, [[Rep, Curr] | Encoded])
end
end.

%% Duplicate the elements of a list.
%% Example: (dupli ‘(a b c c d)) -> (A A B B C C C C D D)
p14([]) -> [];
p14([H | L]) -> p14duplicate(L, [H, H]).

p14duplicate([], Cloned) -> lists:reverse(Cloned);
p14duplicate([H | L], Cloned) -> p14duplicate(L, [H, H | Cloned]).

%% Replicate the elements of a list a given number of times.
%% Example: (repli ‘(a b c) 3) -> (A A A B B B C C C)
p15([], _Num) -> [];
p15([H | L], Reps) -> p15replicate(L, Reps, [lists:duplicate(Reps, H)]).

p15replicate([], _Reps, Replicated) -> lists:append(lists:reverse(Replicated));
p15replicate([H | L], Reps, Replicated) -> p15replicate(L, Reps, [lists:duplicate(Reps, H) | Replicated]).

%% Drop every N’th element from a list.
%% Example: (drop ‘(a b c d e f g h i k) 3) -> (A B D E G H K)
p16([], _Nth) -> [];
p16([H | L], Nth) -> p16drop(L, Nth, Nth-1, [H]).

p16drop([], _Nth, _Curr, Dropped) -> lists:reverse(Dropped);
p16drop([_H | L], Nth, Curr, Dropped) when Curr == 1 -> p16drop(L, Nth, Nth, Dropped);
p16drop([H | L], Nth, Curr, Dropped) -> p16drop(L, Nth, Curr-1, [H | Dropped]).

%% Split a list into two parts; the length of the first part is given.
%% Do not use any predefined predicates.
%% Example: (split ‘(a b c d e f g h i k) 3) -> ( (A B C) (D E F G H I K))
p17([], _SplitPoint) -> [];
p17(L, SplitPoint) -> p17split(L, SplitPoint, []).

p17split([], _SplitPoint, List) -> lists:reverse(List);
p17split(L, SplitPoint, Head) when SplitPoint == 0 -> [lists:reverse(Head) | [L]];
p17split([H | L], SplitPoint, Head) -> p17split(L, SplitPoint-1, [H | Head]).

%% Extract a slice from a list.
%% Given two indices, I and K, the slice is the list containing the elements
%% between the I’th and K’th element of the original list (both limits included).
%%Start counting the elements with 1.
%% Example: (slice ‘(a b c d e f g h i k) 3 7) -> (C D E F G)
p18([], _Start, _End) -> [];
p18(L, Start, End) -> p18slice(L, Start, End-Start, []).

p18slice([], _Start, _Count, Sliced) -> lists:reverse(Sliced);
p18slice([H | _L], 1, 0, Sliced) -> lists:reverse([H | Sliced]);
p18slice([H | L], 1, Count, Sliced) -> p18slice(L, 1, Count-1, [H | Sliced]);
p18slice([_H | L], Start, Count, Sliced) -> p18slice(L, Start-1, Count, Sliced).

%% Rotate a list N places to the left.
%% Examples: (rotate ‘(a b c d e f g h) 3) -> (D E F G H A B C)
%% (rotate ‘(a b c d e f g h) -2) -> (G H A B C D E F)
%% Hint: Use the predefined functions length and append, as well as the result of problem P17.
p19([], _Rotate) -> [];
p19(L, Rotate) ->
case Rotate of
Point when Rotate > 0 -> Point;
_LT0 -> Point = length(L) + Rotate
end,
[F, B] = lp:p17(L, Point),
B ++ F.

%% Remove the K’th element from a list.
%% Example: (remove-at ‘(a b c d) 2) -> (A C D)
p20([], _Point) -> [];
p20(L, Point) -> p20remove(L, Point, []).

p20remove([], _Point, BeforePoint) -> lists:reverse(BeforePoint);
p20remove([_H | L], 1, BeforePoint) -> lists:reverse(BeforePoint) ++ L;
p20remove([H | L], Point, BeforePoint) -> p20remove(L, Point-1, [H | BeforePoint]).

Living a joke

Thursday, December 21st, 2006

Mitch Hedberg has a bit about escalators that is hilarious. Today, while exiting the Metro station in DC, I lived that joke. First, the bit:

An escalator can never break. It can only become stairs. You would never see an “Escalator Temporarily Out Of Order” sign, just “Escalator Temporarily Stairs. Sorry for the convenience.”

Sure enough, on exiting the metro, the escalators were off. Sadly, no one in DC has either heard of Mitch Hedberg or had the stones to put up a sign like that. I think a little humor would go a long way in that city…

E-99: 1-10

Wednesday, December 13th, 2006

Using the 99 Lisp Problems as a guide, I have been writing the problems in Erlang to grow more comfortable with the non-concurrent aspects of the language. Once completed, the goal is then to add in some concurrency exercises to round out the Erlang experience. I have to say, to this point, I feel I’m beginning to grok the ole Erlang list-handling / pattern-matching capabilities.

<update date=”December 22nd, 2006″> Reading the Erlang efficiency guide I found out that appending lists is not the greatest way to do list creation, so I rewrote the applicable exercises with the suggestion of simply reversing the list at the end.</update>
Here, then, are my solutions to the first ten problems:

%% Find the last box of a list.

%% Example: (my-last ‘(a b c d)) -> (D)
p01(L) when length(L) =< 1 -> L;
p01([_ | L]) -> p01(L).

%% Find the last but one box of a list.
%% Example: (my-but-last ‘(a b c d)) -> (C D)
p02(L) when length(L) =< 2 -> L;
p02([_ | L]) -> p02(L).

%% Find the K’th element of a list. The first element in the list is number 1.
%% Example: (element-at ‘(a b c d e) 3) -> C
p03([], _) -> [];
p03(_, Pos) when Pos < 1 -> bad_pos;
p03([H | _], 1) -> H;
p03([_ | L], Pos) -> p03(L, Pos-1).

%% Find the number of elements of a list.
p04([]) -> 0;
p04(L) -> p04count(L, 0).

p04count([], C) -> C;
p04count([_ | L], C) -> p04count(L, C+1).

%% Reverse a list.
p05([]) -> [];
p05(L) -> p05reverse(L, []).

p05reverse([], RevL) -> RevL;
p05reverse([H | L], RevL) -> p05reverse(L, [H | RevL]).

%% Find out whether a list is a palindrome. A palindrome can be read forward or backward; e.g. (x a m a x).
p06([]) -> true;
p06(L) when length(L) == 1 -> true;
p06(L) -> L == p05(L).

%% Flatten a nested list structure. Transform a list, possibly holding lists as elements into a `flat’ list by replacing each list with its elements (recursively).
%% Example: (my-flatten ‘(a (b (c d) e))) -> (A B C D E)
%% Hint: Use the predefined functions list and append.
p07([]) -> [];
p07(L) when not is_list(L) -> [L];
p07([H | L]) ->
Head = p07(H),
Tail = p07(L),
Head ++ Tail.

%% Eliminate consecutive duplicates of list elements.
%% If a list contains repeated elements they should be replaced with a single copy of the element. The order of the elements should not be changed.
%% Example: (compress ‘(a a a a b c c a a d e e e e)) -> (A B C A D E)
p08([]) -> [];
p08([H | L]) -> p08compress(L, H, [H]).

p08compress([], _Curr, Compressed) -> lists:reverse(Compressed);
p08compress([H | L], Curr, Compressed) ->
case Curr of
H -> p08compress(L, Curr, Compressed);
_Else -> p08compress(L, H, [H | Compressed])
end.

%% Pack consecutive duplicates of list elements into sublists. If a list contains repeated elements they should be placed in separate sublists.
%% Example: (pack ‘(a a a a b c c a a d e e e e)) -> ((A A A A) (B) (C C) (A A) (D) (E E E E))
p09([]) -> [];
p09([H | L]) -> p09pack(L, H, [H], []).

p09pack([], _Curr, SubL, Packed) -> lists:reverse([SubL | Packed]);
p09pack([H | L], Curr, SubL, Packed) ->
case Curr of
H -> p09pack(L, Curr, [H | SubL], Packed);
_Else -> p09pack(L, H, [H], [SubL | Packed])
end.

%% Run-length encoding of a list.
%% Use the result of problem P09 to implement the so-called run-length encoding data compression method.
%% Consecutive duplicates of elements are encoded as lists (N E) where N is the number of duplicates of the element E.
%% Example: (encode ‘(a a a a b c c a a d e e e e)) -> ((4 A) (1 B) (2 C) (2 A) (1 D)(4 E))
p10([]) -> [];
p10(L) -> p10encode(p09(L), []).

p10encode([], Encoded) -> lists:reverse(Encoded);
p10encode([[Elem | SubL] | L], Encoded) -> p10encode(L, [[length(SubL)+1, Elem] | Encoded]).

Those who grok Erlang and happen to find this blog, please feel free to offer criticism of my implementations.

Get A Life

Wednesday, November 15th, 2006

Holy ballz this guy needs a job or something. Still cool what he does with dice.

Gatos

Tuesday, November 14th, 2006

Pictures of cats. What else needs be said?

Who Needs Free Time

Tuesday, November 7th, 2006

Simple, yet addictive games are my productivity kryptonite. I play Mahjongg, Minesweeper, and a host of other flash-based games on the web. The latest installment came to me via Reddit. Play Orbit and have fun doing it. I got up to twelve planets before finally pulling myself away.

Eat it Cingular

Thursday, October 26th, 2006

I don’t know why, but Cingular apparently does not want me paying my bill. When I log into my account to pay online, I was taken to an intermediate page where I was asked, in a mandatory fashion, for my email address. I’m not a big fan of giving that sucker out for no reason, so I simply clicked the ‘Continue’ button. Unfortunately, the button was a link whose href was the lovely octothorpe.

This of course meant I was going nowhere by means of that button. I was quite peeved at this point because, not only did I not get an explanation from the page telling my why my email was required, but I also had no explanation for why the continue button failed to do so. The age-old adage, “Fail to communicate with me properly once, you suck; fail twice, now I’m pissed” came to mind.

So what’s a web geek to do? Obviously search the page’s javascript for the form submission line and execute it directly through Firebug commandline! Should any Cingular users get frustrated as well, get Firebug (and Firefox, which I have to mention since Google Analytics tells me the internets are alive with IE users still - shame on you all), and execute this line of code:

document.updateRequiredRegisteredInfoActionForm.submit();

Not only did this forward me on to my account page, but it also bypassed the need to fill in my email for no good reason. I get enough spam as it is. So there it is my friends; simple, one-liner to defeat Cingular’s attempts to be poor communicators. A silver lining here, besides getting in, is the lesson learned from Cingular’s mistake: Don’t suck at communicating with your users!

So long, and thanks for all the fish.

A Day Of Sports

Monday, October 16th, 2006

Christina suprised me Sunday with Rams tickets! The game was crazy and lots of fun, though the Rams were not able to hold onto the victory. On our way back from the game, we were phoned by Josh Sprague who informed us of the availability of 4 Cardinals tickets for Sunday’s NLCS game 4. These seats were 8 rows back behind homeplate, with an all-you-can-eat buffet pre-game and all-you-can-eat ballpark food during the game - all for free. Throw in free parking across the street from the stadium and its hard to refuse. I certainly had quite the night eating; its estimated at over $50 worth of ballpark food went into my belly, plus the buffet beforehand. Cards lost, but there’s no better way to watch them lose…
What a fun day!

Yadier MolinaMe and CDJosh and EllenUs

Holidays are here

Wednesday, September 13th, 2006

Ah, its nice to be on holiday. What holiday is on September 13th you ask? Programmer’s Day, of course!!! Internationally recognized as ‘the’ holiday of choice, Programmer’s Day is all about celebrating the fun of being a geek. So come on everybody, live it up!