find corresponding number in a range by index

$\begingroup$

There's a array:

array(1,2,3,...12,
1,2,3,...9,9,10,...12,
1,2,3,...12,
1,2,3,...12,
1,2,3,...6,6,7,8,...12,
1,2,3,3,4,...12,
...);

All numbers are in the range 1-12, one number maybe occur twice in the range,

The index of second number of the twice number will be such as array ( 22 => 9, 56 => 6, 66 => 3, ...);
If we get a number 16 we know the corresponding number is 4,
If we get a number 65 we know the corresponding number is 3,

How to do this in general?

The index is the when the duplicate number occur, 22 => 9 is the duplicate 9 is No. 22 ,1,2,3,...12,
1,2,3,...9,9 12+9 = 21 ,at NO.22 is the duplicate 9

$\endgroup$ 2

2 Answers

$\begingroup$

It appears that the first run through has 12 elements, as none are duplicated, and then each other has 13 as one element is duplicated. If this is correct, the cycle you are in is $\text{cycle}=\lfloor \frac {\text{index}}{13} \rfloor$ counting the first cycle as $0$ to simplify what comes later. The position in the cycle is then $\text{pos}=\text{index} - 13*\text{cycle}+1$ where you have to delete the $+1$ for $\text{cycle}=0$ (but we don't care as there is no duplicate) and the number duplicated is $\text{dup}=\text{index} - 13*\text{cycle}$

$\endgroup$ $\begingroup$

1,2,3,4,5,6,7,8,9,10,11,12,

1,2,3,4,5,6,7,8,9,9,10,11,12,

1,2,3,4,5,6,7,8,9,10,11,12,

1,2,3,4,5,6,7,8,9,10,11,12,

1,2,3,4,5,6,6,7,8,9,10,11,12,

1,2,3,3,4,5,6,7,8,9,10,11,12,

1,2,3,4,5,6,7,8,9,10,11,12,12,

1,2,3,4,5,6,7,8,9,10,11,12, ...

9 is duplicated at No. 22 in the array,that is we konw the duplicated number and it's order number,if we get order number 17 ,by calculate we know the corresponding number to the order number is 5

a = 22 a1 = 9 b = 17 b1 = ?

Calculation : x = (a - b -1) % 12 = 4

if a1 > x b1 = a1 - x = 9 - 4 = 5

if a1 < x b1 = 12 - ( x- a1 )

if a1 = x b1 = 12

This is my solution,but I think there' should has better olution

$\endgroup$

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like