0

I'm looking for some regex/automata help. I'm limited to + or the Kleene Star. Parsing through a string representing a ternary number (like binary, just 3), I need to be able to know if the result is 1-less than a multiple of 4.

So, for example 120 = 0*1+2*3+1*9 = 9+6 = 15 = 16-1 = 4(n)-1.

Even a pointer to the pattern would be really helpful!

torrential coding
  • 1,755
  • 2
  • 24
  • 34
K-man
  • 353
  • 1
  • 13
  • 3
    My answer to a coding contest here: http://codegolf.stackexchange.com/questions/3503/hard-code-golf-regex-for-divisibility-by-7/3505#3505 gives you an example for testing divisibility with different number bases. That would be a good pointer. – Griffin Apr 06 '12 at 01:03
  • Thank you. So far I have a few rules, but nothing definitive yet – K-man Apr 06 '12 at 01:12
  • 1
    My advice is generate a FSM/regex which tests for tenary divisibility with 4. Which shouldn't be too hard if you modify the rules from my NFAs. Once you have that it is trivial to adjust your solution for the "-1" bit. – Griffin Apr 06 '12 at 01:16

2 Answers2

0

You can generate a series of values to do some observation with bc in bash:

for n in {1..40}; do v=$((4*n-1)); echo -en $v"\t"; echo "ibase=10;obase=3;$v" | bc ; done 

3   10
7   21
11  102
15  120
19  201
23  212
27  1000
31  1011
...
user unknown
  • 35,537
  • 11
  • 75
  • 121
0

Notice that each digit's value (in decimal) is either 1 more or 1 less than something divisible by 4, alternately. So the 1 (lsb) digit is one more than 0, the 3 (2nd) digit is one less than 4, the 9 (3rd) digit is 1 more than 8, the 27 (4th) digit is one less than 28, etc.
If you sum up all the even-placed digits and all the odd-placed digits, then add 1 to the odd-placed ones (if counting from 1), you should get equality.

In your example: odd: (0+1)+1, even: (2). So they are equal, and so the number is of the form 4n-1.

Eran Zimmerman Gonen
  • 4,375
  • 1
  • 19
  • 31