Converting ASCII to Unary

51 Views Asked by At

This is a puzzle from CodinGame called Unary: https://www.codingame.com/ide/puzzle/unary

Rules:

  1. The input message consists of ASCII characters (7-bit)
  2. The encoded output message consists of blocks of 0
  3. A block is separated from another block by a space
  4. Two consecutive blocks are used to produce a series of same value bits (only 1 or 0 values):
    • First block: it is always 0 or 00. If it is 0, then the series contains 1, if not, it contains 0
    • Second block: the number of 0 in this block is the number of bits in the series

Example

Let’s take a simple example with a message which consists of only one character: Capital C. C in binary is represented as 1000011, so with this method, this gives:

  • 0 0 (the first series consists of only a single 1)
  • 00 0000 (the second series consists of four 0)
  • 0 00 (the third consists of two 1)

So C is coded as: 0 0 00 0000 0 00

# Input message
message = input()

# Binary string to store the binary representation of the ASCII characters
binary = ""

# Convert each character in the message to binary
for i in message:
    #fetches the ascii decimal value of the character
    ascii_value = ord(i)
    # Convert ASCII value to binary and pad with leading zeroes to ensure 7 bits
    binary_str = bin(ascii_value)[2:].zfill(7)
    #Adds the character to the total binary series
    binary += binary_str

unary = ""
current_value = "2"

#Unary encoding
for i in range(len(binary)):
    #Changes the current value at the beginning of the loop  
    if current_value != binary[i]:
        
        current_value = binary[i]
        
        #If the first bit is 0
        if str(binary)[i] == "0":
            unary += "00 "
        #If the first bit is 1
        else:
            unary += "0 0 " 
        continue
    #Adds a zero for every bit
    unary += "0"
    
# Print the encoded message
print(unary)

My code is very close to getting the right answer (0 0 00 0000 0 00). However, the last 0 in the final block is not printed (0 0 00 0000 0 0). Why is this? (message is equal to C, just like in the example) (also also, the rules state that the binary is supposed to be 7-bit. I don't know what that means or why that is significant, but I'm bringing that up before you ask about it.)

0

There are 0 best solutions below