Execute a Markov algorithm: Difference between revisions
Content added Content deleted
No edit summary |
m (tidy up description of task a little) |
||
Line 1: | Line 1: | ||
{{Wikipedia|Markov_algorithm|en}} |
{{Wikipedia|Markov_algorithm|en}} |
||
{{task|Compilers and Interpreters}}Create an interpreter for a Markov Algorithm. Rules have the syntax: |
{{task|Compilers and Interpreters}}Create an interpreter for a Markov Algorithm. Rules have the syntax: |
||
<comment> ::= # {<any character>} |
<comment> ::= # {<any character>} |
||
<rule> ::= <pattern> <whitespace> -> <whitespace> [.] <replacement |
<rule> ::= <pattern> <whitespace> -> <whitespace> [.] <replacement> |
||
<whitespace> ::= (<tab> | <space>) [<whitespace>] |
<whitespace> ::= (<tab> | <space>) [<whitespace>] |
||
There is one rule per line. If there is a . present before the <replacement>, then this is a terminating rule in which case the interpreter must halt execution. |
There is one rule per line. If there is a . present before the <replacement>, then this is a terminating rule in which case the interpreter must halt execution. |
||
Revision as of 13:41, 15 December 2009
This page uses content from Wikipedia. The original article was at Markov_algorithm. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) |
Execute a Markov algorithm
You are encouraged to solve this task according to the task description, using any language you may know.
You are encouraged to solve this task according to the task description, using any language you may know.
Create an interpreter for a Markov Algorithm. Rules have the syntax:
<comment> ::= # {<any character>} <rule> ::= <pattern> <whitespace> -> <whitespace> [.] <replacement> <whitespace> ::= (<tab> | <space>) [<whitespace>]
There is one rule per line. If there is a . present before the <replacement>, then this is a terminating rule in which case the interpreter must halt execution.
Ruby
<lang Ruby>raise "Please input an input code file, an input data file, and an output file." if ARGV.size < 3
rules = File.readlines(ARGV[0]).inject([]) do |rules, line|
if line =~ /^\s*#/ rules elsif line =~ /^(.+)\s+->\s+(\.?)(.*)$/ rules << [$1, $3, $2 != ""] else raise "Syntax error: #{line}" end
end
File.open(ARGV[2], "w") do |file|
file.write(File.read(ARGV[1]).tap { |input_data| while (matched = rules.find { |match, replace, term| input_data[match] and input_data.sub!(match, replace) }) and !matched[2] end })
end</lang>