Array Permutation and Insertion

Building new arrays from arrays.

Rotate Right

This example shows how to permute all elements of an array to the right. For example, if A is of size 4, the rotation of A to the right is:


Let B be the rotated array of A, B is defined by:

\left\{ \begin{array}{l} B[0] = A[N-1]\\ B[i] = A[i-1] \text{ for } 0<i <N \end{array} \right.

In Swan, this example is designed as follows:


In this model,
  • A[N-1] is the direct access to the last element of A.
  • The operator pre operates on A seen as a flow, then returns the value of A[i] at the previous iteration, that is, at cell index i-1 at iteration i.
  • The resulting array is built by the successive values of bi.
This example illustrates that in a forward, an input array is considered as a finite flow (the pre operator refers to the previous value in the array).

Insertion in an Array

A similar idea of shifting array cells can be used to insert an element in an ordered array. The insertion consists in finding where to insert, then shift the part of the array that is after this insertion index. The resulting array being of the same size as the input one, the last value of the input array is lost:


As explained above, the input array is seen as a finite flow of values (see An Iteration on Flows).

Then, this algorithm can be designed with an automaton in a forward construct. The automaton has two states:
  1. Before: the state before the insertion point. In Before, the values are lower than x to be inserted, then the elements in the output array are the same as in the input.
  2. After: the state after the insertion point. In After, the values are shifted to the right, and initialized with x.
If x is greater than all elements in the array, the transition to leave Before is never triggered, x is not inserted and the output array is the same as the input. The obtained design of the Insert function in Swan is the following: