Wankan

Hamming Codes in CF

Sep 4th, 2020 (edited)
2,150
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import {log, floor, ceil} from "math.cf"
  2.  
  3.  
  4. # Prep
  5.  
  6. [Bit] ->> Num
  7. XOR_reduce = [] => 0
  8. XOR_reduce = bits >\> (^) 0    # reduce using XOR operator
  9.  
  10.  
  11. # Encoding
  12.  
  13. Num -> Bool
  14. is_power_of_two = x <= 0 => False
  15. is_power_of_two = x % 2 == 1 => False
  16. is_power_of_two = x => ceil <- log 2 x == floor <- log 2 x
  17.  
  18.  
  19. [Bit] ->> [Num]
  20. parity_spots = [] => 0
  21. parity_spots = {
  22.   bits => [0..2..length bits]''0,
  23.   indices \\> is_power_of_two indices,
  24. }
  25.  
  26. [Bit], [Num], Num ->> [Bit]
  27. create_message_without_ps = [], _, _ => []
  28. create_message_without_ps = _, [], _ => []
  29. create_message_without_ps = _, _, x < 0 => []
  30. create_message_without_ps = _, _, x % 1 != 0 => []
  31. create_message_without_ps = (b, ...bs), (n, ...ns), i =>
  32.   n == i
  33.     ? [0, ... create_message_without_ps [b, ...bs] ns i+1]    # Adds a 0 to the list, burns the index
  34.     : [b, ... create_message_without_ps bs [n, ...ns] i+1]    # Adds the current bit to the list, burns it
  35.  
  36.  
  37. Num, Num ->> [Num]
  38. get_bits_indices = _, 0 => []
  39. get_bits_indices = with input(idx, maxlen) do:
  40.   #! Bad solution, temporary
  41.   current = Mut idx
  42.   indices = Mut []
  43.   count = Mut 0
  44.   skipping = Mut False
  45.   while current < maxlen:
  46.     if not skipping:
  47.       indices = Mut [...indices, current]
  48.     if count == idx:
  49.       skipping = Mut not skipping
  50.       count = Mut 0
  51.     ++ current
  52.     ++ count
  53.   return Const indices
  54.  
  55.  
  56. [Bit], Num ->> [Bit]
  57. get_bits_to_check = [], _ => []
  58. get_bits_to_check = bits, idx => bits[get_bits_indices <- idx length bits]
  59.  
  60.  
  61. [Bit], [Num] ->> [Bit]
  62. ajust_sequence = [], _ => []
  63. ajust_sequence = bits, [] => bits
  64. ajust_sequence = (bits, parity_indices)
  65.   with (zip bits [0..])''0 as (bit, i) =>
  66.   i in parity_indices
  67.     ? XOR_reduce get_bits_to_check bits i
  68.     : bit
  69.  
  70.  
  71. [Bit] ->> [Bit]
  72. create_message = [] => []
  73. create_message = with input(bits) do:
  74.   spots = parity_spots bits
  75.   seq = create_message_without_ps bits spots 0
  76.   final = ajust_sequence seq spots
  77.   return @final
  78.  
  79.  
  80. # Decoding
  81.  
  82. [Bit] ->> Num
  83. find_error = {
  84.   bits => zip bits [0..],
  85.   bits ''> 0,     # normally a single quote, double here to not mess with the colors, creates a map from the list
  86.   (bit, index) \\> Bool bit,     # filter to have only the 1-bits
  87.   (bit, index) => index,
  88.   XOR_reduce,
  89.   location => @location,
  90. }
Add Comment
Please, Sign In to add comment