diff --git a/03_euler_gen_alg.py b/03_euler_gen_alg.py index 04ccc08..8ab78e8 100644 --- a/03_euler_gen_alg.py +++ b/03_euler_gen_alg.py @@ -10,49 +10,20 @@ def generate_random_individuals(): return val -# Function to flip a bit -# represented as character. -def flip(c): - return '1' if c == '0' else '0' - -# accepts string binary array def grey_to_bin(gray): - binary = "" + """Convert Gray code to binary, operating on the integer value directly""" + num = int(gray, 2) # Convert string to integer + mask = num + while mask != 0: + mask >>= 1 + num ^= mask + return format(num, f'0{len(gray)}b') # Convert back to binary string with same length - # MSB of binary code is same as gray code - binary += gray[0] - - # Compute remaining bits - for i in range(1, len(gray)): - - # If current bit is 0, concatenate - # previous bit - if gray[i] == '0': - binary += binary[i - 1] - - # Else, concatenate invert of - # previous bit - else: - binary += flip(binary[i - 1]) - - return binary - -# accepts string binary array def bin_to_grey(binary): - gray = "" - - # MSB of gray code is same as binary code - gray += binary[0] - - # Compute remaining bits, next bit is computed by - # doing XOR of previous and current in Binary - for i in range(1, len(binary)): - - # Concatenate XOR of previous bit - # with current bit - gray += xorChar(binary[i - 1], binary[i]) - - return gray + """Convert binary to Gray code using XOR with right shift""" + num = int(binary, 2) # Convert string to integer + gray = num ^ (num >> 1) # Gray code formula: G = B ^ (B >> 1) + return format(gray, f'0{len(binary)}b') # Convert back to binary string with same length def quadratic_error(original_fn, approx_fn, n): error = 0.0