-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKMPAlgorithm.qs
More file actions
43 lines (37 loc) · 1.44 KB
/
KMPAlgorithm.qs
File metadata and controls
43 lines (37 loc) · 1.44 KB
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
namespace KMPAlgorithm {
open Microsoft.Quantum.Diagnostics;
open Microsoft.Quantum.Math;
operation KMPAlgorithm(pattern : Qubit[], text : Qubit[]) : Unit {
mutable failureFunction = new Int[Length(pattern)];
set failureFunction = CalculateFailureFunction(pattern);
mutable i = 0;
mutable j = 0;
while (i < Length(text)) {
if (MeasureOne(text[i]) == One) {
set i = i + 1;
set j = j + 1;
} else {
set j = failureFunction[j];
}
if (j == Length(pattern)) {
Message("Pattern found at position " + ToString(i - Length(pattern)));
set j = failureFunction[j];
}
}
}
function CalculateFailureFunction(pattern : Qubit[]) : Int[] {
mutable failureFunction = new Int[Length(pattern) + 1];
set failureFunction = [0 | rest(CalculateFailureFunctionAux(pattern, 1, 0))];
return failureFunction;
}
function CalculateFailureFunctionAux(pattern : Qubit[], i : Int, j : Int) : Int[] {
if (i == Length(pattern)) {
return [];
} else {
mutable failureFunction = [0];
let nextJ = if (MeasureOne(pattern[i]) == One) then j + 1 else 0;
set failureFunction = failureFunction + [nextJ | CalculateFailureFunctionAux(pattern, i + 1, nextJ)];
return failureFunction;
}
}
}