Sort the Binary Values

 Coding Problem Keys 

 Sort the Binary Values 

 Problem Statement 

Given N pairs consisting of an integer X representing the number of bits to consider and B representing a binary value as input, the program must find the decimal values based on the following conditions:

    - If X is positive then consider the first X bits in the binary value.
    - If X is negative then consider the last X bits in the binary value.
    - If X is zero then consider all the bits in the binary value.

Finally, the program must sort (in ascending order) based on the considered binary values converted to their decimal equivalent.

Then the program must print the original binary values in the sorted order.

 Boundary Condition(s) 

1 <= N <= 100
-20 <= X <= 20
1 <= Number of bits in B <= 20

 Input Format 

The first line contains the value of N.
The next M lines contain pair of integers X and B separated by space(s).

 Output Format 

The first line contains N binary values separated by a space.

 Example Input/Output 1 

 Input 

4
2 10101101
-3 100010111
4 1111001010
-2 1010101011

 Output 

10101101 1010101011 100010111 1111001010

 Explanation 

The decimal value of the first 2 bits in 10101101 is 2.
The decimal value of the last 3 bits in 100010111 is 7.
The decimal value of the first 4 bits in 1111001010 is 15.
The decimal value of the last 2 bits in 1010101011 is 3.
Sort the binary values in the ascending order based on the decimal values and we get 2 3 7 15.
Hence the output is 10101101 1010101011 100010111 1111001010.

 Example Input/Output 2 

 Input 

5
10 101001100111010
-4 11100100101011
0 1010101110111
5 1011001101101
-2 10000100010100

 Output 

10000100010100 11100100101011 1011001101101 101001100111010 1010101110111

 Max Execution Time Limit: 5000 millisecs 

 Solution 

 Programming Language: Python 3 Language 

n=int(input())
l=[]
for i in range(n):
    a,b=input().split()
    a=int(a)
    if(a<0):
        c=int(b[a:],2)
    elif a>0:
        c=int(b[:a],2)
    else:
        c=int(b,2)
    l.append([c,b])
for i in sorted(l,key=lambda x:x[0]):
    print(i[-1],end=" ")

# Published By PKJCODERS

 (Note: Incase If the code doesn't Pass the output kindly comment us with your feedback to help us improvise.) 

Comments

Popular Posts

Difference between a number and it's reverse

Snakes and Ladders

Reverse Column - First and Last

Sum of N Integers - Even Reversed

Matrix Diagonal Pattern

Equidistant Characters from Start & End

Array Frequency Equals Value