-
-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #19 from sebastienrousseau/feature/mini-functions
Feature/mini functions
- Loading branch information
Showing
8 changed files
with
368 additions
and
19 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,87 @@ | ||
use mini_functions::random::Random; | ||
|
||
// Defining an example for a simple `A Three Card Draw Poker Game` that | ||
// shuffles a deck of cards and allows the user to draw cards from the | ||
// top of the deck, displaying the card name and suit as a string. | ||
|
||
// A struct that represents a deck of playing cards | ||
struct Deck { | ||
// A vector of cards | ||
cards: Vec<usize>, | ||
// A random number generator | ||
rng: Random, | ||
} | ||
|
||
// Implementation of the `Deck` struct | ||
impl Deck { | ||
// Creates a new `Deck` struct with a shuffled deck of cards | ||
fn new() -> Self { | ||
let mut deck = Self { | ||
cards: (0..52).collect(), | ||
rng: Random::new(), | ||
}; | ||
|
||
// Shuffle the deck using the Fisher-Yates algorithm | ||
for i in (1..52).rev() { | ||
let j = deck.rng.random() as usize % (i + 1); | ||
deck.cards.swap(i, j); | ||
} | ||
deck | ||
} | ||
|
||
// Draws a card from the top of the deck | ||
fn draw(&mut self) -> Option<String> { | ||
let card = self.cards.pop(); | ||
if let Some(card) = card { | ||
let suits = ["Spades (♠)", "Clubs (♣)", "Hearts (♥)", "Diamonds (♦)"]; | ||
let ranks = [ | ||
"2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King", "Ace", | ||
]; | ||
let suit = suits[card / 13]; | ||
let rank = ranks[card % 13]; | ||
Some(format!("{} of {}", rank, suit)) | ||
} else { | ||
None | ||
} | ||
} | ||
} | ||
|
||
fn main() { | ||
// Create a new random number generator | ||
let mut rng = Random::new(); | ||
println!("🦀 Random::new(): ✅ {}", rng); | ||
|
||
let default = Random::default(); | ||
println!("🦀 Random::default(): ✅ {}", default); | ||
|
||
let random = rng.random(); | ||
println!("🦀 Random::random(): ✅ {}", random); | ||
|
||
let pseudo = rng.pseudo(); | ||
println!("🦀 Random::pseudo(): ✅ {}", pseudo); | ||
|
||
let bytes = rng.bytes(10); | ||
println!("🦀 Random::bytes(): ✅ {:?}", bytes); | ||
|
||
let float = rng.random() as f32 / 0x7FFF as f32; | ||
println!("🦀 Random::float(): ✅ {}", float); | ||
|
||
let int = rng.random() as usize; | ||
println!("🦀 Random::int(): ✅ {}", int); | ||
|
||
// Create a new deck of cards and draw three cards | ||
let mut deck = Deck::new(); | ||
|
||
// Draw three cards from the top of the deck and print them to the console | ||
let card1 = deck.draw().unwrap(); | ||
let card2 = deck.draw().unwrap(); | ||
let card3 = deck.draw().unwrap(); | ||
|
||
// Print the cards to the console | ||
println!( | ||
"\n🦀 Let's play a mini game of `Three Card Draw Poker` to demonstrate the random number generator!\n" | ||
); | ||
println!("🎲 Deck::draw(): ✅ {}", card1); | ||
println!("🎲 Deck::draw(): ✅ {}", card2); | ||
println!("🎲 Deck::draw(): ✅ {}", card3); | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,91 @@ | ||
//! # Core random number generator | ||
//! | ||
//! This crate provides a random number generator based on the linear congruential generator algorithm with the golden ratio as the multiplier. | ||
//! | ||
//! | ||
// Copyright © 2022-2023 Mini Functions. All rights reserved. | ||
// SPDX-License-Identifier: Apache-2.0 | ||
// SPDX-License-Identifier: MIT | ||
|
||
use std::time::SystemTime; | ||
|
||
/// A random number generator based on the linear congruential generator | ||
/// algorithm with the golden ratio as the multiplier. | ||
#[derive(Clone, Copy, Debug, PartialEq, PartialOrd)] | ||
pub struct Random { | ||
// The seed for the random number generator | ||
seed: u32, | ||
} | ||
|
||
impl Random { | ||
/// Creates a new `Random` struct with a seed based on the current | ||
/// system time. | ||
pub fn new() -> Self { | ||
// Get the current system time in milliseconds | ||
let seed = SystemTime::now() | ||
.duration_since(SystemTime::UNIX_EPOCH) | ||
.unwrap() | ||
.as_millis() as u32; | ||
Self { seed } | ||
} | ||
|
||
/// Generates a random number using the linear congruential | ||
/// generator algorithm. The multiplier for the algorithm is the | ||
/// golden ratio. | ||
pub fn random(&mut self) -> u32 { | ||
// The multiplier for the linear congruential generator | ||
// algorithm | ||
let golden_ratio = 1140071478; | ||
// Update the seed with the next value in the sequence | ||
self.seed = self.seed.wrapping_mul(golden_ratio).wrapping_add(12345); | ||
// Return the upper 15 bits of the seed as the random number | ||
(self.seed >> 16) & 0x7FFF | ||
} | ||
|
||
/// Generates a pseudo-random number by XORing the last 31 random | ||
/// numbers together. | ||
pub fn pseudo(&mut self) -> u32 { | ||
let mut res = self.random(); | ||
let mut rng = Random::default(); | ||
// XOR the last 31 random numbers together to generate the | ||
// pseudo-random number | ||
for _ in 0..31 { | ||
res ^= rng.random(); | ||
} | ||
res | ||
} | ||
|
||
/// Generates a vector of random bytes of a given length. | ||
pub fn bytes(&mut self, len: usize) -> Vec<u8> { | ||
let mut res = Vec::with_capacity(len); | ||
let mut rng = Random::default(); | ||
for _ in 0..len { | ||
res.push(rng.random() as u8); | ||
} | ||
res | ||
} | ||
/// Generates a random floating point number between 0 and 1. | ||
pub fn float(&mut self) -> f32 { | ||
let mut rng = Random::default(); | ||
rng.random() as f32 / 0x7FFF as f32 | ||
} | ||
/// Generates a random integer between a minimum and maximum value. | ||
pub fn int(&mut self, min: i32, max: i32) -> i32 { | ||
let mut rng = Random::default(); | ||
(rng.random() as f32 / 0x7FFF as f32 * (max - min) as f32) as i32 + min | ||
} | ||
} | ||
|
||
impl std::fmt::Display for Random { | ||
/// Formats the `Random` struct as a string for display. | ||
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { | ||
write!(f, "Random {{ seed: {} }}", self.seed) | ||
} | ||
} | ||
|
||
impl Default for Random { | ||
fn default() -> Self { | ||
Self::new() | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,2 +1,5 @@ | ||
mod date; | ||
mod log; | ||
mod qrcode; | ||
mod random; | ||
mod uuid; |
Oops, something went wrong.