*TL;DR I wrote a quantum random number generator in Q# to play games. Run the code in your browser here:*

I have really been enjoying working on some of my open source projects on Twitch lately, and to try and drive more viewership I thought I would do a giveaway/sweepstakes on a stream. It came time to select the winner and I realized I simply could not do this with a boring old random number generator online. So I decided to write up a quick snippet in Q#, Microsoft’s new quantum programming language, on the stream and wanted to post a quick write up with the code here.

You can find the code for this post in this Gist, and run it all in your browser on myBinder.

There are two main files included in this gist, the first is a Jupyter Notebook that allows you to run the snippet and use it to select random integers yourself!

It currently is setup to select a random integer from 0 to 6 inclusive (7 total players), which index the list of viewers I had at the time. If you want to change the number of players you can just edit the argument in the first cell and re-run it by hitting shift and enter at the same time.

The Q# code here can be found in the `operations.qs`

file:

This file defines a namespace `Sweepstakes`

and one operation, `SelectWinner`

that takes an integer argument that defines the number of players.
The main steps to this pretty short operation are as follows:

- Figure out how many qubits you need to represent the number of players you have.
- Allocate your qubits with
`using`

, and put them all in superposition by applying the`H`

operation (short for Hadamard) to each qubit in the register. - Measure the register and interpret the bit string of measurement results as a binary value (
`MeasureInteger`

). I did have to also specify whether the register was to be interpreted as a little endian register so it knew how to parse it. - Lastly, if that measured integer was outside of the range of players (this will happen if the number of players is not a power of 2) then just repeat steps 2 and 3 until you get a valid player index.

And that’s pretty much it! A random integer generator written in the quantum programming language Q# that you can use to make all of the hard decisions in your life 😋 If you want to learn more about developing for quantum computers or how they work, you can check out these links:

Older
Newer