-
Notifications
You must be signed in to change notification settings - Fork 0
/
algorithm-exclusive-or-pairs-quantum.js
95 lines (74 loc) · 1.94 KB
/
algorithm-exclusive-or-pairs-quantum.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
90
91
92
93
94
95
const logger = require('../src/logger')()
const Bits = require('../src/bits')
// a quantum implementation of Simon's algorithm
repeat(5, function() {
run()
})
function run() {
let host = new Host()
let oracle = new Oracle({ length: 4 })
let result = host.test(oracle)
logger.log('')
logger.log(`The host has detected a result of ${result}`)
logger.log(`Does the oracle confirm? ${oracle.confirm(result)}`)
logger.log('')
}
function Host() {
Object.assign(this, {
test: function(oracle) {
let result = null
let length = oracle.length
repeat(Infinity, function(index) {
let circuit = Circuit(`a quantum circuit to discover an oracle's secret bitstring using xor`, length * 2)
let unit = circuit.unit(0, length)
unit.h()
oracle.apply(circuit)
unit.h()
circuit.run()
let bits = unit.measure()
if (bits.toNumber() !== 0) {
result = bits.toString()
return 'break'
}
})
return result
}
})
}
function Circuit(name, size) {
return require('../src/circuit.js')({
name: name,
size: size,
logger: logger,
engine: 'optimized',
order: ['targets', 'controls']
})
}
function Oracle(options) {
Object.assign(this, {
initialize: function() {
this.length = options && options.length ? options.length : 4
let random = Math.floor(Math.random() * (Math.pow(2, this.length) - 1)) + 1 // the secret cannot be zero
this.secret = Bits.fromNumber(random, this.length).toString()
},
apply: function(circuit) {
Bits.fromString(this.secret).iterate(function(bit, index) {
if (bit) {
repeat(this.length, function(index_) {
circuit.cx(this.length + index_, index)
}.bind(this))
}
}.bind(this))
},
confirm: function(value) {
return this.secret === value ? 'yes' : 'no'
}
})
this.initialize()
}
function repeat(number, fn) {
for (let i = 0; i < number; i++) {
let result = fn.apply(this, [i])
if (result === 'break') break
}
}