Skip to content

Instantly share code, notes, and snippets.

@crazy4pi314
Last active February 25, 2022 16:49
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save crazy4pi314/90c74fd23f084de8e78b150ba1987c1c to your computer and use it in GitHub Desktop.
Save crazy4pi314/90c74fd23f084de8e78b150ba1987c1c to your computer and use it in GitHub Desktop.
Quantum Random Sweepstakes
FROM mcr.microsoft.com/quantum/iqsharp-base:0.11.2004.2825
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 mybinder.org.
USER root
COPY . ${HOME}
RUN chown -R ${USER} ${HOME}
RUN pip install rise
# Finish by dropping back to the notebook user.
USER ${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;
}
}
Display the source blob
Display the rendered blob
Raw
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