Spaces:
Runtime error
Runtime error
import argparse | |
from typing import Optional | |
def get_next_bit(left: str, center: str, right: str) -> str: | |
"""Rule 30 implementation: | |
111 -> 0 | |
110 -> 0 | |
101 -> 0 | |
100 -> 1 | |
011 -> 1 | |
010 -> 1 | |
001 -> 1 | |
000 -> 0 | |
""" | |
pattern = left + center + right | |
rule30_map = { | |
"111": "0", "110": "0", "101": "0", "100": "1", | |
"011": "1", "010": "1", "001": "1", "000": "0" | |
} | |
return rule30_map[pattern] | |
def validate_sequence(bits: str) -> tuple[bool, Optional[int]]: | |
"""Validate if a sequence follows Rule 30. | |
Returns (is_valid, first_error_position) | |
""" | |
if not all(bit in '01' for bit in bits): | |
return False, 0 | |
# Pad with zeros for edge cases | |
padded = '0' + bits + '0' | |
for i in range(1, len(bits) + 1): | |
expected = get_next_bit( | |
padded[i-1], | |
padded[i], | |
padded[i+1] | |
) | |
if i < len(bits) and bits[i] != expected: | |
return False, i | |
return True, None | |
def main(): | |
parser = argparse.ArgumentParser(description='Validate a binary sequence against Rule 30') | |
parser.add_argument('file', help='Path to file containing binary sequence') | |
args = parser.parse_args() | |
try: | |
with open(args.file, 'r') as f: | |
bits = f.read().strip() | |
is_valid, error_pos = validate_sequence(bits) | |
if is_valid: | |
print("β Sequence follows Rule 30") | |
return 0 | |
else: | |
print(f"β Sequence violates Rule 30 at position {error_pos}") | |
return 1 | |
except FileNotFoundError: | |
print(f"Error: File {args.file} not found") | |
return 2 | |
except Exception as e: | |
print(f"Error: {str(e)}") | |
return 3 | |
if __name__ == "__main__": | |
exit(main()) |