Created
September 21, 2011 04:42
-
-
Save eungju/1231267 to your computer and use it in GitHub Desktop.
Look-and-say sequence
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(defn look-and-say [input] | |
((fn [input acc] | |
(if (empty? input) | |
(reverse acc) | |
(let [[x & xs] input [i n & as] acc] | |
(if (= x i) | |
(recur xs (list* x (inc n) as)) | |
(recur xs (list* x 1 acc)))))) | |
(rest input) [(first input) 1])) | |
(println (look-and-say [1])) | |
(println (look-and-say [1 1])) | |
(println (look-and-say [2 1])) | |
(println (look-and-say [1 2 1 1])) | |
(println (look-and-say [1 1 1 2 2 1])) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-module(look_and_say). | |
-export([look_and_say/1, main/0]). | |
look_and_say(L) -> | |
look_and_say(L, []). | |
look_and_say([], Acc) -> | |
lists:reverse(Acc); | |
look_and_say([X|XS], []) -> | |
look_and_say(XS, [X,1]); | |
look_and_say([X|XS], [X,N|AS]) -> | |
look_and_say(XS, [X,N + 1|AS]); | |
look_and_say([X|XS], Acc) -> | |
look_and_say(XS, [X,1|Acc]). | |
main() -> | |
io:format("~p~n", [look_and_say([])]), | |
io:format("~p~n", [look_and_say([1])]), | |
io:format("~p~n", [look_and_say([1,1])]), | |
io:format("~p~n", [look_and_say([2,1])]), | |
io:format("~p~n", [look_and_say([1,2,1,1])]), | |
io:format("~p~n", [look_and_say([1,1,1,2,2,1])]). |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment