- Translate each rule into one explicit state update.
- Maintain the invariant after every processed item.
- Return the accumulated state once all relevant input has been handled.
Code notes
- 143 lines of Turing from the credited upstream file ccc96s4.t.
- The implementation keeps its working state in language-native values and containers.
- No explicit loop blocks detected.
Complexity
Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
123 456 78910 11function toDecimal (s : string) : int12 var t, v : int13 var old : int := 10000014 t := 015 for i : 1 .. length (s)16 if s (i) = "I" then17 v := 118 elsif s (i) = "V" then19 v := 520 elsif s (i) = "X" then21 v := 1022 elsif s (i) = "L" then23 v := 5024 elsif s (i) = "C" then25 v := 10026 elsif s (i) = "D" then27 v := 50028 elsif s (i) = "M" then29 v := 100030 end if31 if v > old then32 t := t + v - 2 * old33 else34 t := t + v35 end if36 old := v37 end for38 result t39end toDecimal40 4142function toRoman (xx : int) : string43 var x : int := xx44 var d : int45 var s : string46 s := ""47 d := x div 10048 x := x mod 10049 if d = 1 then50 s := s + "C"51 elsif d = 2 then52 s := s + "CC"53 elsif d = 3 then54 s := s + "CCC"55 elsif d = 4 then56 s := s + "CD"57 elsif d = 5 then58 s := s + "D"59 elsif d = 6 then60 s := s + "DC"61 elsif d = 7 then62 s := s + "DCC"63 elsif d = 8 then64 s := s + "DCCC"65 elsif d = 9 then66 s := s + "CM"67 end if68 d := x div 1069 x := x mod 1070 if d = 1 then71 s := s + "X"72 elsif d = 2 then73 s := s + "XX"74 elsif d = 3 then75 s := s + "XXX"76 elsif d = 4 then77 s := s + "XL"78 elsif d = 5 then79 s := s + "L"80 elsif d = 6 then81 s := s + "LX"82 elsif d = 7 then83 s := s + "LXX"84 elsif d = 8 then85 s := s + "LXXX"86 elsif d = 9 then87 s := s + "XC"88 end if89 d := x90 if d = 1 then91 s := s + "I"92 elsif d = 2 then93 s := s + "II"94 elsif d = 3 then95 s := s + "III"96 elsif d = 4 then97 s := s + "IV"98 elsif d = 5 then99 s := s + "V"100 elsif d = 6 then101 s := s + "VI"102 elsif d = 7 then103 s := s + "VII"104 elsif d = 8 then105 s := s + "VIII"106 elsif d = 9 then107 s := s + "IX"108 end if109 result s110end toRoman111 112 113var infile : string := "rom.in"114var outfile : string := "rom.out"115var fi, fo : int116var n : int117var line : string118var plus, answer : int119 120open : fi, infile, get121open : fo, outfile, put122 123get : fi, n124for i : 1 .. n125 get : fi, line126 plus := index (line, "+")127 answer := toDecimal (line (1 .. plus - 1)) + toDecimal (line (plus +128 1 .. length (line) - 1))129 if answer > 1000 then130 put : fo, line, "CONCORDIA CUM VERITATE"131 put line, "CONCORDIA CUM VERITATE"132 else133 put : fo, line, toRoman (answer)134 put line, toRoman (answer)135 end if136 put : fo, ""137 put ""138end for139 140close : fi141close : fo142 143