Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The transformation you want to do is essentially a circular shift by <code>n</code> (or by <code>m</code>, depending on the direction of the shift).</p> <p>E.g., we have <code>1 2 3 4 5 6 7 a b c</code> (I use letters and numbers to separate two arrays) During this transformation, <code>1</code> will move to the position of <code>4</code>, <code>4</code> will move to <code>7</code>, <code>7</code> to <code>c</code>, <code>c</code> to <code>3</code>, <code>3</code> to <code>6</code>, etc. Eventually, we'll return to the position <code>1</code>, from which started.<br> So, moving one number at the time, we completed it.</p> <p>The only trick is that sometimes we'll return to <code>1</code> before completing whole transformation. Like in the case <code>1 2 a b c d</code>, the positions will be <code>1 -&gt; a -&gt; c -&gt; 1</code>. In this case, we'll need to start from <code>2</code> and repeat operation.</p> <p>You can notice that amount of repetitions we need is a greatest common divisor of <code>n</code> and <code>m</code>.</p> <p>So, the code could look like</p> <pre><code>int repetitions = GCD(n, m); int size = n + m; for (int i = 0; i &lt; repetitions; ++i) { int current_number = a[i]; int j = i; do { j = (j + n) % size; int tmp = current_number; current_number = a[j]; a[j] = tmp; } while (j != i); } </code></pre> <p>Greatest common divisor can be easily computed in <code>O(logn)</code> with <a href="http://en.wikipedia.org/wiki/Greatest_common_divisor#Using_Euclid.27s_algorithm" rel="nofollow">well-known recursive formula</a>.</p> <p><strong>edit</strong><br> It does work, I tried in Java. I only changed data type to string for ease of representation.</p> <pre><code> String[] a = {"1", "2", "3", "4", "5", "6", "a", "b", "c"}; int n = 3; int m = 6; // code from above... System.out.println(Arrays.toString(a)); </code></pre> <p>And Euclid's formula:</p> <pre><code>int GCD(int a, int b) { if (a == 0) { return b; } return GCD(b % a, a); } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload