Count Bits
Problem Description
Given a sequence of distinct numbers a1, a2, ….. an, an inversion occurs if there are indices i<j such that ai > aj .
For example, in the sequence 2 1 4 3 there are 2 inversions (2 1) and (4 3).
The input will be a main sequence of N positive integers. From this sequence, a Derived derived sequence will be obtained using the following rule. The output is the number of inversions in the derived sequence.
Rule for forming derived sequence
The derived sequence is formed by counting the number of 1s bits in the binary representation of the corresponding number in the input sequence.
Thus, if the input is 3,4,8, the binary representation of the numbers are 11,100 and 1000. The derived sequence is the number of 1sin the binary representation of the numbers in the input sequence, and is 2,1,1
Solution
Problem Description
Given a sequence of distinct numbers a1, a2, ….. an, an inversion occurs if there are indices i<j such that ai > aj .
For example, in the sequence 2 1 4 3 there are 2 inversions (2 1) and (4 3).
The input will be a main sequence of N positive integers. From this sequence, a Derived derived sequence will be obtained using the following rule. The output is the number of inversions in the derived sequence.
Rule for forming derived sequence
The derived sequence is formed by counting the number of 1s bits in the binary representation of the corresponding number in the input sequence.
Thus, if the input is 3,4,8, the binary representation of the numbers are 11,100 and 1000. The derived sequence is the number of 1sin the binary representation of the numbers in the input sequence, and is 2,1,1
Solution
def
getInvCount(arr, n):
inv_count
=
0
for
i
in
range
(n):
for
j
in
range
(i
+
1
, n):
if
(arr[i] > arr[j]):
inv_count
+
=
1
return
inv_count
# Driver Code
arr
=
[
1
,
20
,
6
,
4
,
5
]
n
=
len
(arr)
print
(
"Number of inversions are"
,
getInvCount(arr, n))
Comments
Post a Comment