Skip to content

Instantly share code, notes, and snippets.



Last active May 15, 2020
What would you like to do?
Quantum Random Sweepstakes
ENV IQSHARP_HOSTING_ENV=sckaiser-azure-community-live
# Make sure the contents of our repo are in ${HOME}.
# These steps are required for use on
USER root
RUN chown -R ${USER} ${HOME}
RUN pip install rise
# Finish by dropping back to the notebook user.
// Copyright (c) Sarah Kaiser. All rights reserved.
// Licensed under the MIT License.
namespace Sweepstakes {
open Microsoft.Quantum.Intrinsic;
open Microsoft.Quantum.Canon;
open Microsoft.Quantum.Measurement;
open Microsoft.Quantum.Arithmetic;
open Microsoft.Quantum.Math;
/// # Summary
/// This operation uses a register of qubits in superposition to select
/// a random integer in a range {0, numPlayers-1}.
/// # Input
/// ## numPlayers
/// The number of participants in the random drawing.
/// # Output
/// An `Int` that represents the index of the player that has won the
/// sweepstakes.
/// # Remarks
/// ## Example
/// ```Q#
/// // You need to pick one of 7 viewers of your stream to send them
/// // a present! 🎁
/// let winnerIndex = SelectWinner(7);
/// ```
operation SelectWinner(numPlayers : Int) : Int {
// Calculate number of qubits needed to store the number of players.
let numQubits = BitSizeI(numPlayers);
// Setup the variable that will track the result.
mutable result = 0;
// This repeat block is needed because unless the number of players is
// a power of two, you could get a result that does not index a player.
// Since there is no fair way to reuse those spare values, we just try
// again until we get a random index that does represent a player.
repeat {
// Prepare a register of qubits
using (register = Qubit[numQubits]) {
// Put all of the qubits in superposition with the `H` operation.
ApplyToEach(H, register);
// Measure and interpret as an integer.
set result = MeasureInteger(LittleEndian(register));
// Make sure the result corresponds to the index of a player.
} until(result < numPlayers);
// Return the winning player!
return result;
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment