简体   繁体   中英

Sequence following percentage

Problem statement: A person has to go to set of locations in a sequence: Seq: L1 L2 L3 L4 L5 L6 (assume L1, L2 are locations)

But he followed went to locations in different sequence: ActualSeq: L3 L1 L2 L4 L5 L6

Now I need to find out what is the % sequence followed. Remember, the algo should consider that L4, L5, L6 still were after L3. So it is not a simple % question.

Anyhelp is highly appreciated

This is a problem known as Longest Increasing Subsequence and there are O(n log n) algorithms for it.

To find the percentage, you just have to find LIS(V)/length(V) .

Here's an example implementation ( O(n^2) ) in Python

EDIT: changed the code to clearly point where an O(n) step can be turned into O(log n)

def LIS(V):
    n = len(V)
    T = [0]*(n+1)

    L = 0
    for i in xrange(n):
        #this step can be a binary search
        j = max(j for j in xrange(L+1) if j==0 or V[T[j]] < V[i])

        T[j+1] = i
        L = max(L, j+1)

    return L/float(n)*100

print '{:.2f}%'.format(LIS([3, 1, 2, 4, 5, 6])) #83.33%
print '{:.2f}%'.format(LIS([1, 2, 3, 4, 5, 6])) #100.00%
print '{:.2f}%'.format(LIS([6, 1, 2, 5, 4, 3])) #50.00%

You should consider the Longest common Subsequence of the two inputs (Initial Sequence and Actual Sequence)

Divide the longest common subsequence by the number of Locations to get the % sequence followed.

In your case it is 5/6 = .8333 = 83.33%

I would try testing the distance between each successive location in the array of locations, like this, using your example:

distance from L1 to L2 = 1
distance from L2 to L3 = 2
distance from L3 to L4 = 3
distance from L4 to L5 = 1
distance from L5 to L6 = 1

then add them up...TTL = 8

A perfect, 100% score is 5
Our score is 8

The difference between our score and a perfect score is 8-5 = 3
The percentage is subtracted from 100% like so: 1.00 - 3/5 = 0.40 = 40%

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM