Best practice for shifting a sequence in a circular manner - arrays

I have to implement a kind of an array or sequence or list, which supports the cheapest way of circulated forwarding and back winding of elements. See this example:
Original sequence: 1 2 3 4 5
Forwarded once: 5 1 2 3 4
Forwarded twice: 4 5 1 2 3
Same but opposite is for the back winding. What would be the cheapest and most Scala-style way of implementing this? In Java I could use LinkedList and it would do great... However, I could not find any definite answer for Scala.
Also, it also has to be easy to replace any given element by index, as in LinkedList.
UPDATE:
For the fastest, but not-so-idiomatic variant of algorithm (you know when you need it), refer to the answer of Petr Pudlák!!!

Immutable implementation
A ring buffer is a pair of an IndexedSeq and an Int pointer into this sequence. I provide code for a immutable version. Note that not all methods that might be useful are implemented; like the mutators that change the content of the IndexedSeq.
With this implementation, shifting is just creating one new object. So it's pretty efficient.
Example code
class RingBuffer[A](val index: Int, val data: IndexedSeq[A]) extends IndexedSeq[A] {
def shiftLeft = new RingBuffer((index + 1) % data.size, data)
def shiftRight = new RingBuffer((index + data.size - 1) % data.size, data)
def length = data.length
def apply(i: Int) = data((index + i) % data.size)
}
val rb = new RingBuffer(0, IndexedSeq(2,3,5,7,11))
println("plain: " + rb)
println("sl: " + rb.shiftLeft)
println("sr: " + rb.shiftRight)
Output
plain: Main(2, 3, 5, 7, 11)
sl: Main(3, 5, 7, 11, 2)
sr: Main(11, 2, 3, 5, 7)
Performance comparison to mutable implementations
The OP mentions that you should look at the mutable implementations (e.g. this answer), if you need performance. This is not true in general. As always: It depends.
Immutable
update: O(log n), which is basically the update complexity of the underlying IndexedSeq;
shifting: O(1), also involves creating a new object which may cost some cycles
Mutable
update: O(1), array update, as fast as it gets
shifting: O(n), you have to touch every element once; fast implementations on primitive arrays might still win against the immutable version for small arrays, because of constant factor

scala> val l = List(1,2,3,4,5)
l: List[Int] = List(1, 2, 3, 4, 5)
scala> val reorderings = Stream.continually(l.reverse).flatten.sliding(l.size).map(_.reverse)
reorderings: Iterator[scala.collection.immutable.Stream[Int]] = non-empty iterator
scala> reorderings.take(5).foreach(x => println(x.toList))
List(1, 2, 3, 4, 5)
List(5, 1, 2, 3, 4)
List(4, 5, 1, 2, 3)
List(3, 4, 5, 1, 2)
List(2, 3, 4, 5, 1)

I needed such an operation myself, here it is. Method rotate rotates the given indexed sequence (array) to the right (negative values shift to the left). The process is in-place, so no additional memory is required and the original array is modified.
It's not Scala-specific or functional at all, it's meant to be very fast.
import annotation.tailrec;
import scala.collection.mutable.IndexedSeq
// ...
#tailrec
def gcd(a: Int, b: Int): Int =
if (b == 0) a
else gcd(b, a % b);
#inline
def swap[A](a: IndexedSeq[A], idx: Int, value: A): A = {
val x = a(idx);
a(idx) = value;
return x;
}
/**
* Time complexity: O(a.size).
* Memory complexity: O(1).
*/
def rotate[A](a: IndexedSeq[A], shift: Int): Unit =
rotate(a, 0, a.size, shift);
def rotate[A](a: IndexedSeq[A], start: Int, end: Int, shift: Int): Unit = {
val len = end - start;
if (len == 0)
return;
var s = shift % len;
if (shift == 0)
return;
if (s < 0)
s = len + s;
val c = gcd(len, s);
var i = 0;
while (i < c) {
var k = i;
var x = a(start + len - s + k);
do {
x = swap(a, start + k, x);
k = (k + s) % len;
} while (k != i);
i = i + 1;
}
return;
}

The way I solve Scala problems is solving them in Haskell first, and then translating. :)
reorderings xs = take len . map (take len) . tails . cycle $ xs
where len = length xs
This is the easiest way I could think of, which produces the list of all possible shifts, by "shifting left" repeatedly.
ghci> reorderings [1..5]
[[1,2,3,4,5],[2,3,4,5,1],[3,4,5,1,2],[4,5,1,2,3],[5,1,2,3,4]]
The concept is relatively simple (for those comfortable with functional programming, that is). First, cycle the original list, producing an infinite stream from which to draw from. Next, break that stream into a stream of streams, where each subsequent stream has dropped the first element of the previous stream (tails). Next, limit each substream to the length of the original list (map (take len)). Finally, limit the stream of streams to the length of the original list, since there are only len possible reorderings (take len).
So let's do that in Scala now.
def reorderings[A](xs: List[A]):List[List[A]] = {
val len = xs.length
Stream.continually(xs).flatten // cycle
.tails
.map(_.take(len).toList)
.take(len)
.toList
}
We just had to use a small workaround for cycle (not sure if Scala standard libs provide cycle, though I was pleasantly surprised to find they provide tails), and a few toLists (Haskell lists are lazy streams, while Scala's are strict), but other than that, it's exactly the same as the Haskell, and as far as I can tell, behaves exactly the same. You can almost think of Scala's . as behaving like Haskell's, except flowing the opposite way.
Also note this is very nearly the same as dhg's solution, except without the reverses, which (on the upside) makes it more efficient, but (on the downside) provides the cycles in "backwinding" order, rather than "forward" order.

Nice combination of #dhg and #Roman Zykov versions:
scala> val l = List(1,2,3,4,5)
l: List[Int] = List(1, 2, 3, 4, 5)
scala> val re = Stream continually (l ++ l.init sliding l.length) flatten
re: scala.collection.immutable.Stream[List[Int]] = Stream(List(1, 2, 3, 4, 5), ?)
scala> re take 10 foreach println
List(1, 2, 3, 4, 5)
List(2, 3, 4, 5, 1)
List(3, 4, 5, 1, 2)
List(4, 5, 1, 2, 3)
List(5, 1, 2, 3, 4)
List(1, 2, 3, 4, 5)
List(2, 3, 4, 5, 1)
List(3, 4, 5, 1, 2)
List(4, 5, 1, 2, 3)
List(5, 1, 2, 3, 4)

There is a very simple solution:
val orderings = List(1,2,3,4,5)
(orderings ++ orderings.dropRight(1)).sliding(orderings.length).toList
List(List(1, 2, 3, 4, 5), List(2, 3, 4, 5, 1), List(3, 4, 5, 1, 2), List(4, 5, 1, 2, 3), List(5, 1, 2, 3, 4))

My take on it:
#tailrec
def shift(times:Int, data:Array[Int]):Array[Int] = times match {
case t:Int if(t <= 0) => data;
case t:Int if(t <= data.length) => shift(0, (data++data.take(times)).drop(times))
case _ => shift(times % data.length, data);
}

Here's another simple scala solution for shifting a Stream right or left by arbitrary amounts. "Cycle" repeats the stream infintely, then "shift" finds the correct slice. "posMod" allows you to shift by an index larger than xs.length but without actually straying more than xs.length elements in the infinite Stream:
scala> def posMod(a:Int, b:Int) = (a % b + b) % b
scala> def cycle[T](xs : Stream[T]) : Stream[T] = xs #::: cycle(xs)
scala> def shift[T](xs:Stream[T], x: Int) = cycle(xs)
.drop(posMod(x, xs.length))
.take(xs.length)
Then:
scala> shift(Stream(1,2,3,4), 3).toList
--> List[Int] = List(4, 1, 2, 3)
scala> shift(Stream(1,2,3,4), -3).toList
--> List[Int] = List(2, 3, 4, 1)
scala> shift(Stream(1,2,3,4), 30000001).toList
--> List[Int] = List(2, 3, 4, 1)

My proposition:
def circ[A]( L: List[A], times: Int ): List[A] = {
if ( times == 0 || L.size < 2 ) L
else circ(L.drop(1) :+ L.head , times-1)
}
val G = (1 to 10).toList
println( circ(G,1) ) //List(2, 3, 4, 5, 6, 7, 8, 9, 10, 1)
println( circ(G,2) ) //List(3, 4, 5, 6, 7, 8, 9, 10, 1, 2)
println( circ(G,3) ) //List(4, 5, 6, 7, 8, 9, 10, 1, 2, 3)
println( circ(G,4) ) //List(5, 6, 7, 8, 9, 10, 1, 2, 3, 4)

You can instantiate a function that will include the Array(A) and the number of rotation steps that you need(S):
def rotate(A: Array[Int], S: Int): Int = { (A drop A.size - (S % A.size)) ++ (A take A.size - (S % A.size)) }
rotate(Array(1, 2, 3, 4, 5), 1)

Here is one possible solution for sequences
// imports required for: `Scala 2.13.10 (OpenJDK 64-Bit Server VM, Java 1.8.0_292)`
import scala.language.implicitConversions
import scala.language.postfixOps
class ShiftWarper( seq: Seq[ Int ] ) {
def shiftLeft: Seq[ Int ] = if ( seq.isEmpty ) {
seq
} else {
seq.tail :+ seq.head
}
def shiftRight: Seq[ Int ] = if ( seq.isEmpty ) {
seq
} else {
seq.last +: seq.init
}
}
implicit def createShiftWarper( seq: Seq[ Int ] ) =
new ShiftWarper( seq )
def shift_n_Times(
times: Int,
seq: Seq[ Int ],
operation: Seq[ Int ] => Seq[ Int ] ): Seq[ Int ] = if ( times > 0 ) {
shift_n_Times(
times - 1,
operation( seq ),
operation )
} else {
seq
}
// main: unit test
val initialSeq = ( 0 to 9 )
// > val initialSeq: scala.collection.immutable.Range.Inclusive = Range 0 to 9
( initialSeq shiftLeft ) shiftRight
// > val res1: Seq[Int] = Vector(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
shift_n_Times(
5,
initialSeq,
initialSeq => new ShiftWarper( initialSeq ).shiftRight )
// > val res2: Seq[Int] = Vector(5, 6, 7, 8, 9, 0, 1, 2, 3, 4)

Related

modify a different index of list inside loop

For modifying same index we can do
mylist = [1,2,3]
Enum.map(mylist, fn x-> -x end) // [-1,-2,-3]
How would we modify a different index like
for (i = 0; i < mylist.length; i++) {
mylist[i+1] = -mylist[i];
}
The most important thing is to remember you have to create an entirely new list, so you should think about how best to get what you're looking for, not how to replicate how you would tackle it in another language.
If, for example, you're wanting to compare items with nearby items, you could zip a list with its offset:
iex> enum = 1..5
1..5
iex> stream = Stream.drop(enum, 1) # Enum.drop/2 would also work
#Stream<[enum: 1..5, funs: [#Function<48.15162342/1 in Stream.drop/2>]]>
iex> Enum.zip(enum, stream) # Stream.zip/2 works if you're going to iterate
[{1, 2}, {2, 3}, {3, 4}, {4, 5}]
For your specific example, where the next value is the previous value negated, you could create an infinite stream and take what you need:
iex> 1 |> Stream.iterate(&-/1) |> Enum.take(3)
[1, -1, 1]
If you're only looking to modify one value, you'll have to create a new list with only the new value changed (NOTE this is not the way you want to do several updates):
iex> {previous, [current | next]} = Enum.split(1..5, 3)
{[1, 2, 3], [4, 5]}
iex> Enum.concat([previous, [current * 12], next])
[1, 2, 3, 48, 5]
Both answers here so far are using Elixir core library helpers like Enum.with_index/2, or Stream.iterate/2, or Enum.map/2.
I am to show the barebone functional approach for modifying the neighbour index as in your pseudocode example. I will be replicating the snippet that does not crash the VM.
> mylist = [ 1, 2, 3 ]
> for (i = 1; i < mylist.length; i++) { mylist[i-1] = -mylist[i] }
> mylist
//⇒ [ -2, -3, 3 ]
In Elixir, using recursion, that would be:
defmodule Neighbour do
def map(list, acc \\ [])
def map([_, next | rest], acc), do: map(rest, [-next | acc])
def map([next], acc), do: Enum.reverse([next, -next | acc])
end
Neighbour.map([1, 2, 3])
#⇒ [-2, -3, 3]
Remembering that data is immutable in Erlang and barring that it's not a good idea to map imperative programming to functional programming, we could do something like the following:
new_list = Enum.map(Enum.with_index(list), fn {v,i} ->
((Enum.at(list, i + 1) || 0) - v)
end)
Which is would result in [1, 1, -3] or in other words:
2 - 1 = 1
3 - 2 = 1
0 - 3 = -3
As others have pointed this would be an inefficient way to do such a thing per the O(n) complexity of Enum.at/2.
A more performant and idiomatic solution would be:
iex(1)> list0 = [1,2,3]
[1, 2, 3]
iex(2)> sliced = Enum.slice(list, 1, 2)
[2,3]
iex(3) list2 = List.duplicate(0, length(list0) - length(sliced))
[2, 3, 0]
iex(21)> Enum.map(Enum.zip(list, list2), fn({v1, v2}) -> v2 - v1 end)
[1, 1, -3]

Removing elements from an array

Problem:
I have two arrays A and B:
A = [0, 1, 2, 3]; %A will always be from 0 to N where N in this case is 3.
B = [0, 1, 3, 1, 9, 4, 6, 2, 5, 9, 10, 11, 3, 8, 1, 5, 9, 10];
weights_B = [3, 4, 5, 6];
I want to compare the first element of A to the first 3 elements of B and the second element of A to the next 4 elements of B. If the elements of A are equal I remove it from B. So in example:
if (A(1) == B(1:3))
remove A(1) from B
Similarly,
I want to compare A(2) to the next 4 elements of B i.e. to B(4:7):
if (A(2) == B(4:7))
remove A(2) from B
I want to compare A(3) to the next 5 elements of B i.e. to B(8:12)
if (A(3) == B(8:12))
remove A(3) from B
I want to compare A(4) to the next 6 elements of B i.e. to B(13:18)
if (A(4) == B(13:18))
remove A(4) from B
Note: The array weights_B determines the number of elements in B that should be respectively compared to A(1), A(2), .. , A(4)
So in the end B should have the following elements:
B = [1, 3, 9, 4, 6, 5, 9, 10, 11, 8, 1, 5, 9, 10];
Needed Solution:
Is there any way I can do this without having to hard-code the indices?
Here's a way without hard-coding:
Bw = mat2cell(B, 1, weights_B); % split into chunks
result = cell(size(Bw)); % initiallize result
for k = 1: numel(A)
result{k} = Bw{k}(Bw{k}~=A(k)); % fill each chunk of the result
end
result = [result{:}]; % concatenate into a row vector
For the sake of diversity, here's a way to do this using splitapply:
function out = q50982235
A = 0:3;
B = [0, 1, 3, 1, 9, 4, 6, 2, 5, 9, 10, 11, 3, 8, 1, 5, 9, 10];
weights_B = [3, 4, 5, 6];
a_ind = 0; % acts as a "global" variable for the inner function
G = repelem( 1:numel(weights_B), weights_B ); % this creates a vector of groups
out = cell2mat( splitapply(#movdif, B, G) );
function out = movdif(B)
a_ind = a_ind + 1;
out = {B(B ~= A(a_ind))};
end
end
The above works because the order of processed groups is predictable.
This solution requires R2015b.
Try this
A = [0, 1, 2, 3];
B = [0, 1, 3, 1, 9, 4, 6, 2, 5, 9, 10, 11, 3, 8, 1, 5, 9, 10];
weights_B = A + A(end);
border_0 = zeros(size(A));
border_1 = zeros(size(A));
border_0(1) = 1;
border_1(end) = length(B);
for i= 2:length(A)
border_0(i) = border_0(i-1) + weights_B(i-1);
border_1(i-1) = border_0(i)-1;
end
C = [];
for i= 1:length(border_0)
shift = 0;
if (i > 1)
shift = border_1(i-1);
end
C = [C B( find(B(border_0(i):border_1(i))~=A(i)) + shift )]
end
A = [0, 1];
B = [0, 1, 3, 1, 4, 5, 6];
% Split B into cells
C{1} = B(1:3) ; % this can be coded if more splits are required
C{2} = B(4:end) ;
% removing the lements
for i = 1:2
C{i}(C{i}==A(i))=[] ; % remove the elements in C{i} present in A(i)
end
cell2mat(C)
Since you want to compare the elements of A with first 3 and then 4 elements of B respectively, you would need to involve indexes.
You could simply use loop for it.
for(int i=0;i<B.length;i++){
if((A[0]==B[i])&&i<3){
B[i]=B[i+1];
}
else if((A[0]==B[i])&&i>3){}
B[i]=B[i+1];
}
Then adjust the updated size of array B.

Get sum of combinations of array values in scala

I know that there have been a few similar questions to this but there still doesn't seem to be a definitive answer to this so I will ask it..
I have an array of values and am trying to find the correct values that will sum to a limit value or the closest it can get (without exceeding it) from any given combination.
Using this answer https://stackoverflow.com/questions/23168934/calculating-minimal-subset-with-given-sum I have this:
def getLimitArr(arr: Array[Int], limit: Int): Unit = {
scala.util.Sorting.quickSort(arr) // Array(2, 3, 4, 5, 11, 34)
var sum = 0L
var i = arr.length-1
val arr2 = ArrayBuffer[Integer]()
while (i >= 0 && sum < limit) {
if(sum + arr(i)<=limit) {
sum += arr(i)
arr2 += arr(i)
}
i -= 1 // 6, 5, 4, 3, 2, 1
}
println(arr2.mkString(", ") + " = " + sum)
}
And calling it using this in the main method:
val arr = Array(3, 34, 4, 11, 5, 2)
getLimitArr(arr, 9)
Which returns:
println(arr2.mkString(", ") + " = " + sum) // 5, 4 = 9
This is good but only if the values (that make up the sum) can be made from the highest value that is lower than the limit; in this example 5 - which works with this array as we can see. But if the limit value was 12 (getLimitArr(arr, 12)) with this array then it would return 11 = 11 rather than using 5 + 4 + 3.
I have done this using subsets but when the array is more than 10 I get the memory heap error as it is formulating all of the combinations before being able to obtain the answer.
So how would we do this by being memory efficient, using the current format or taking advantage of Scala's functional programming capabilities?
Recursion is often useful when we want to terminate as soon as the first correct answer is found.
def getLimit(nums: Array[Int], limit: Int): Array[Int] = {
val subset = nums.filter(limit.>=)
if (subset.isEmpty) Array()
else (1 to subset.length).flatMap(subset.combinations)
.find(_.sum == limit)
.fold(getLimit(subset, limit-1))(identity)
}
getLimit(Array(3, 34, 4, 11, 5, 2), 5) // res0: Array[Int] = Array(5)
getLimit(Array(3, 34, 4, 11, 5, 2), 9) // res1: Array[Int] = Array(4, 5)
getLimit(Array(3, 34, 4, 11, 5, 2), 12) // res2: Array[Int] = Array(3, 4, 5)
getLimit(Array(3, 34, 4, 11, 5, 2), 24) // res3: Array[Int] = Array(3, 4, 11, 5)
Note that the last one sums to 23 because there is no combination that sums to 24.
update
A better shortcut added and the method is now tail recursive.
def getLimit(nums: Array[Int], limit: Int): Array[Int] = {
val subset = nums.filter(limit.>=)
if (subset.sum <= limit) subset
else {
val res = (1 to subset.length).view
.flatMap(subset.combinations)
.find(_.sum == limit)
if (res.isEmpty) getLimit(subset, limit-1)
else res.get
}
}

Iterate through array forwards then backwards

[1,2,3,4,5]
=>1,2,3,4,5,4,3,2,1
=>1,2,3,2,3,4,5,4,3 #I need to be able to reverse the iteration at certain points
I first tried something like:
a = [1,2,3,4,5]
a.each {|i|
if i % 9 == 0
a.reverse!
}
but that just reverses the entire array and starts counting from the index it left off on. I need to to shift the direction of each, so to speak.
i, counter = 0, 1 # initialize index to 0, counter to 1
while(i < a.length && i >= 0) do
puts a[i]
i+= counter # increment counter
counter*= -1 if(condition) # Multiply counter with -1 to reverse it
end
Well, here's a moving "cursor" for your array:
module Cursor
def current_index
#current_index ||= 0
end
def step
#current_index = current_index + direction
handle_boundary
end
def step_back
#current_index = current_index + (direction * -1)
handle_boundary
end
def handle_boundary
if current_index == length || current_index == 0
turn_around
end
end
def direction
#direction ||= 1
end
def turn_around
#direction = direction * -1
end
def current
self[current_index]
end
end
And here's how you use it:
array = [1,2,3,4,5]
arary.extend Cursor
array.current # returns the item in current position
array.step # moves a step forward, turns around when it reaches either end of the array
array.step_back # moves a step backward without switching the direction
array.turn_around # switch the direction
Now you can travel around as you want :D
You can make use of Enumerator class to create custom enumerable that can providing custom iteration through the array. In below code, I am monkey-patching Array class for convenience (also due to resemblance of the method to Array#cycle), though solution can be done without monkey-patching as well.
class Array
def reversible_cycle
Enumerator.new do |y|
index = 0
direction = :forward
loop do
direction = :backward if index + 1 >= size
direction = :forward if index <= 0
y << self[index]
index += (direction == :forward ? +1 : -1)
end
end
end
end
p [1,2,3,4,5].reversible_cycle.take(9)
#=> [1, 2, 3, 4, 5, 4, 3, 2, 1]
p [1,2,3,4,5].reversible_cycle.take(13)
#=> [1, 2, 3, 4, 5, 4, 3, 2, 1, 2, 3, 4, 5]
p [1,2,3,4,5].reversible_cycle.take(17)
#> [1, 2, 3, 4, 5, 4, 3, 2, 1, 2, 3, 4, 5, 4, 3, 2, 1]
p [1,2,3,4,5].reversible_cycle.take(21)
#=> [1, 2, 3, 4, 5, 4, 3, 2, 1, 2, 3, 4, 5, 4, 3, 2, 1, 2, 3, 4, 5]
For scenarios where you are changing direction without iterating the array fully in one direction, you will have to give some examples so that one can see how to modify the above code to accommodate that
You could use Ruby's under-appreciated flip-flop operator.
arr = [1,2,3,4,5]
sz = arr.size
(2*sz-1).times { |i| puts i==0..i==arr.size-1 ? arr[i] : arr[sz-i-2] }
1
2
3
4
5
4
3
2
1

z3py: how to represent an array of integers or characters in z3py

I am new to z3py and SMT and I haven't found a good tutorial about z3py.
Here is my problem setting:
Given an input integer array I=[1,2,3,4,5], and an output integer array O=[1,2,4,5].
I want to infer k for the operator Delete, which deletes the element at position k in an array, where
Delete(I,O) =  (ForAll 0<=x<k, O[x] = I[x] ) and (ForAll k<=x<length(I)-1, O[x] = I[x+1]) is true
Should I use Array or IntVector, or anything else to represent the input/output array?
Edit:
My code is as follows:
from z3 import *
k=Int('k')
s=Solver()
x = Int('x')
y = Int('y')
s.add(k >= 0)
s.add(k < 4)
s.add(x >= 0)
s.add(x < k)
s.add(y >= k)
s.add(y < 4)
I = Array('I',IntSort(),IntSort())
O = Array('O',IntSort(),IntSort())
Store(I, 0, 1)
Store(I, 1, 2)
Store(I, 2, 3)
Store(I, 3, 4)
Store(I, 4, 5)
Store(O, 0, 1)
Store(O, 1, 2)
Store(O, 2, 4)
Store(O, 3, 5)
s.add(And(ForAll(x,Select(O,x) == Select(I,x)),ForAll(y,Select(O,y) == Select(I,y+1))))
print s.check()
print s.model()
It returns
sat
[I = [2 -> 2, else -> 2],
O = [2 -> 2, else -> 2],
y = 1,
k = 1,
x = 0,
elem!0 = 2,
elem!1 = 2,
k!4 = [2 -> 2, else -> 2]]
I don't understand what I, O, elem!0, elem!1 and k!4 mean and this is clearly not what I expected.
Disclaimer: I've hardly ever used Z3py before, but I've used Z3 quite a bit.
I have the feeling that you are somewhat new to encoding logical problems as well - could that be? There are several (odd) things going on in your problem.
You put constraints on x and y, but you actually never use them - instead, you bind different x and y in your quantified assertions. The latter two may have the same names, but they are totally unrelated to the x and y that you constrained (since each forall binds its own variable, you could also use x in both). Hence, your quantified x and y range over all Int, whereas you probably want to limit them to the interval [0..4). Use an implication inside the forall for this.
According to the docs, Store(a, i, v) returns a new array a' that is identical to a, except that x[i] == v. That is, you need to call I = Store(I, 0, 1) etc. in order to finally get an array I that stores your desired values.
Since you don't do this, Z3 is free to pick a model that satisfies your constraints. As you can see from the output, the model for I is [2 -> 2, else -> 2], which says that I[2] == 2, and I[i] == 2 for any i != 2. I don't know why Z3 chose that particular model, but it (together with the model for O) satisfies your foralls.
You can probably ignore elem!0, elem!1 and k!4, they are internally generated symbols.
Here is a reduced version of your example that doesn't verify:
x = Int('x')  
I = Array('O',IntSort(),IntSort())
O = Array('O',IntSort(),IntSort())
I = Store(I, 0, 1)
I = Store(I, 1, 2)
s.add(
And(
ForAll(x, Select(O,x) == Select(I,x)),
ForAll(x, Select(O,x) == Select(I,x+1))))
print s.check() # UNSAT
The reason why it is unsatisfiable is that I[0] == 1 && I[1] == 2, which contradicts your foralls. If you instantiate both quantified x with 0, the you get O[0] == I[0] && O[0] == I[1] - a constrain that cannot be fulfilled, i.e. there is no model for O that satisfies it.
Edit (to address a comment):
If you are puzzled why, given a snippet such as
I = Array('O',IntSort(),IntSort())
I = Store(I, 0, 1)
I = Store(I, 1, 2)
# print(I)
s.check()
s.model()
Z3 reports sat and returns a model where I = [], then recall that each Store(...) returns a fresh Z3 expression that represents a store operation, each of which in turn returns a fresh array (which is equal to the initial one, modulo the update). As the print shows, the final value of I is the expression Store(Store(I, 0, 1), 1, 2). It therefore suffices to let I itself be the empty array, i.e. I - the updates (the Stores) will each yield a fresh array (think I1 and I2 in this case), but since they are nameless, they won't (or at least don't have to) show up in the model.
If you want to explicitly see the "final" values of your array in the model, you can achieve this by giving a name to the array that is created by the last Store, e.g
I = Array('I',IntSort(),IntSort())
I = Store(I, 0, 1)
I = Store(I, 1, 2)
II = Array('II',IntSort(),IntSort())
s.add(I == II)
s.check()
s.model() # includes II = [1 -> 2, 0 -> 1, else -> 3]
This is the correct answer to my question:
from z3 import *
x = Int('x')
y = Int('y')
k = Int('k')
s = Solver()
I = Array('I',IntSort(),IntSort())
O = Array('O',IntSort(),IntSort())
I = Store(I, 0, 1)
I = Store(I, 1, 2)
I = Store(I, 2, 3)
I = Store(I, 3, 4)
I = Store(I, 4, 5)
O = Store(O, 0, 1)
O = Store(O, 1, 2)
O = Store(O, 2, 4)
O = Store(O, 3, 5)
s.add(k >= 0)
s.add(k < 4)
s.add(And(ForAll([x],Implies(And(x>=0,x<k),Select(O,x) == Select(I,x))),ForAll([y],Implies(And(y>=k,y<4),Select(O,y) == Select(I,y+1)))))
print s.check()
if s.check() == z3.sat:
print s.model()
The answer is
sat
[I = [2 -> 2, else -> 2],
k = 2,
O = [2 -> 2, else -> 2],
k!17 = [2 -> 2, else -> 2]]

Resources