forked from microsoft/Quantum
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathIterateThroughCartesianProduct.qs
57 lines (52 loc) · 1.74 KB
/
IterateThroughCartesianProduct.qs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
namespace Microsoft.Quantum.Canon {
/// # Summary
/// Iterates a variable, say `arr`, through a Cartesian product
/// [ 0, bounds[0]-1 ] × [ 0, bounds[1]-1 ] × [ 0, bounds[Length(bounds)-1]-1 ]
/// and calls op(arr) for every element of the Cartesian product
operation IterateThroughCartesianProduct( bounds : Int[], op : ((Int[]) => ()) ) : ()
{
body
{
mutable arr = new Int[Length(bounds)];
mutable finished = false;
repeat
{
if( !finished )
{
op(arr);
}
}
until(finished)
fixup
{
//computes the next element in the Cartesian product
set arr[0] = arr[0] + 1;
for( i in 0 .. Length(arr) -2 )
{
if( arr[i] == bounds[i] )
{
set arr[i+1] = arr[i+1] + 1;
set arr[i] = 0;
}
}
if( arr[Length(arr) -1] == bounds[Length(arr) -1] )
{
set finished = true;
}
}
}
}
/// # Summary
/// Iterates a variable, say arr, through Cartesian product
/// [ 0, bound - 1 ] × [ 0, bound - 1 ] × [ 0, bound - 1 ]
/// and calls op(arr) for every element of the Cartesian product
operation IterateThroughCartesianPower( power : Int, bound : Int, op : ((Int[]) => ()) ) : ()
{
body
{
IterateThroughCartesianProduct(ConstantArray(power, bound), op);
}
}
}