-
Notifications
You must be signed in to change notification settings - Fork 0
/
amplify.js
89 lines (69 loc) · 1.58 KB
/
amplify.js
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
const logger = require('../src/logger')()
const Bits = require('../src/bits')
amplify(3)
function amplify(value) {
const bits = Bits.fromNumber(value, 4) // todo: assert between 0 and circuit size ^ 2 - 1
circuit(`the input state to amplify has its phase flipped |${bits.toString(' x')}>`, 5)
.h(0).h(1).h(2).h(3)
.flip(bits)
.run()
circuit(`the probability of the input state has been amplified 15 times |${bits.toString(' x')}>`, 5)
.h(0).h(1).h(2).h(3)
.repeat(15, function(index) {
this.flip(bits).mirror()
}).run()
}
function circuit(name, size, options) {
let circuit = require('../src/circuit.js')({
name: name,
size: size,
logger: logger,
engine: 'optimized',
order: ['targets', 'controls']
})
return Object.assign(circuit, {
repeat: function(value, fn) {
for (let i = 0; i < value; i++) {
fn.apply(this, [i])
}
return this
},
flip: function(bits) {
return this
.toggle(bits)
.ccx(scratch(0), [0, 1])
.h(3)
.ccx(3, [scratch(0), 2])
.h(3)
.ccx(scratch(0), [0, 1])
.toggle(bits)
},
toggle: function(bits) {
bits.toArray().forEach(function(bit, index) {
if (bit) circuit.x(index)
})
return this
},
mirror: function() {
return this.grover()
},
grover: function() {
return this
.h(0).h(1).h(2).h(3)
.x(0).x(1).x(2).x(3)
.ccx(scratch(0), [0, 1])
.h(3)
.ccx(3, [scratch(0), 2])
.h(3)
.ccx(scratch(0), [0, 1])
.x(0).x(1).x(2).x(3)
.h(0).h(1).h(2).h(3)
}
})
}
function main(index) {
return index
}
function scratch(index) {
return 4 + index
}