-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathalgorithm-bitstring-query-quantum.js
More file actions
76 lines (59 loc) · 1.58 KB
/
algorithm-bitstring-query-quantum.js
File metadata and controls
76 lines (59 loc) · 1.58 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
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
const logger = require('../src/logger')()
const Bits = require('../src/bits')
// the quantum implementation of the Bernstein-Vazirani algorithm
repeat(10, function() {
run()
})
function run() {
let length = 4
let circuit = Circuit('a random oracle for a bitwise probing', length)
let oracle = new Oracle({ length: length - 1 })
let all = circuit.unit('*')
let main = circuit.unit(0, length - 1)
let scratch = circuit.unit(length - 1)
all.h()
scratch.z()
oracle.query(circuit)
main.h()
circuit.run()
let result = circuit.evaluate(main)
logger.log('')
logger.log(`The host detected an oracle value of "${result}".`)
logger.log(`Does the oracle confirm this? ${oracle.confirm(result)}`)
logger.log('')
}
function Circuit(name, size) {
let circuit = require('../src/circuit.js')({
name: name,
size: size,
logger: logger,
engine: 'optimized',
order: ['targets', 'controls']
})
return Object.assign(circuit, {
evaluate: function(main) {
return main.measure()
}
})
}
function Oracle(options) {
this.length = options && options.length ? options.length : 4
let random = Math.floor(Math.random() * Math.pow(2, this.length))
this.secret = Bits.fromNumber(random, this.length).toString()
Object.assign(this, {
query: function(circuit) {
let scratch = circuit.unit(3)
Bits.fromString(this.secret).iterate(function(bit, index) {
if (bit) scratch.cx(index)
})
},
confirm: function(value) {
return this.secret == value ? 'yes' : 'no'
}
})
}
function repeat(number, fn) {
for (let i = 0; i < number; i++) {
fn.apply(this, [i])
}
}