Spaces:
Runtime error
Runtime error
File size: 1,853 Bytes
c16ebf6 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 |
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()) |