Created
March 14, 2018 00:21
-
-
Save rust-play/ec7f4e870d5bb3d742c7c52a55fc5e3b to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
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
extern crate chrono; | |
extern crate rand; | |
use std::rc::Rc; | |
use std::mem; | |
use List::{Cons, Nil}; | |
use chrono::*; | |
use std::collections::HashMap; | |
use std::fmt::Display; | |
use rand::Rng; | |
// Ownership, borrowing and lifetimes - https://medium.com/@bugaevc/understanding-rust-ownership-borrowing-lifetimes-ff9ee9f79a9c | |
//use std::error::Error; | |
const THRESHOLD: usize = 2; | |
pub fn nth(n: i32) -> Result<usize, &'static str> { | |
let limit = 1_000_000; | |
if n == 0 { | |
return Err("Input parameter is 0"); | |
} | |
let mut arr = [true; 1_000_000]; | |
let mut count = 0; | |
for i in 2..limit { | |
if arr[i] == true { | |
println!("{}", i); | |
count = count + 1; | |
if count == n { | |
return Ok(i); | |
} | |
let mut j = 1; | |
while i * j < limit { | |
arr[i * j] = false; | |
j = j + 1; | |
} | |
} | |
} | |
Err("n is too big") | |
} | |
//mod np { | |
//} | |
fn main() { | |
#[allow(dead_code)] | |
#[derive(Debug)] | |
struct Structure(i32); | |
let x = 123i32; | |
println!("Hello, world!"); | |
println!("Hello, {}!", x); | |
println!("This struct `{:?}` will print!", Structure(3)); | |
let a = [0, 1, 2, 3, 4]; | |
// let middle = &a[1..4]; | |
// a[1] = 5; | |
// middle[2] = 5; | |
println!("{:?}", a); | |
let tuple = (1, 2, 3); | |
println!("{}", tuple.0); | |
// fn foo(x: i32) -> i32 { x + 1 } | |
// | |
// let x = foo(5); | |
// let y = foo; | |
// println!("{}", x); | |
// println!("{}", y(6)); | |
let x = 5; | |
let y = if x == 5 { 10 } else { 15 }; | |
println!("{}", y); | |
let _z = x; | |
println!("{}", x); | |
// fn take(v: Vec<i32>) { | |
// // doesn't matter | |
// } | |
let v = vec![1, 2, 3]; | |
// let mut array: [i32; 3] = [0; 3]; | |
// array[0] = 4; | |
// array[1] = 1; | |
// array[2] = 2; | |
// take(v); | |
println!("{:?}", foo(&v)); | |
println!("{:?}", v); | |
// println!("v[0] = {}", v[0]); | |
let x1 = 5; | |
let mut y1: &i32; | |
y1 = &x1; | |
println!("{}", y1); | |
println!("{}", x1); | |
// let a1 = [1, 2, 3]; // with array it's okay | |
let a1 = String::from("hello"); | |
let a2 = a1.clone(); | |
println!("{:?}", a1); | |
println!("{:?}", a2); | |
let mut book = Book { | |
name: String::from("Animal's Farm"), | |
author: String::from("John Orwell"), | |
price: 270, | |
}; | |
println!("{:?}", book); | |
println!("{}", book.name); | |
book.price = 370; | |
println!("{}", book.price); | |
// struct Color(i32, i32, i32); | |
// struct Point(i32, i32, i32); | |
// let black = Color(0, 0, 0); | |
// let origin = Point(0, 0, 0); | |
let a = Rc::new(Cons(String::from("5"), Rc::new(Cons(String::from("10"), Rc::new(Nil))))); | |
let b = Cons(String::from("3"), Rc::clone(&a)); | |
let c = Cons(String::from("4"), Rc::clone(&a)); | |
traverse(&a); | |
println!("4 - 2 = {}", 4u32 - 2); | |
let mut matrix = Matrix(1.1, 2.2, 3.3, 4.4); | |
println!("{:?}", transpose(&mut matrix)); | |
let arr = [1, 2, 3]; | |
let val1 = 4; | |
let val2 = 4i64; | |
println!("array occupies {} bytes", mem::size_of_val(&arr)); | |
println!("i32 occupies {} bytes", mem::size_of_val(&val1)); | |
println!("i64 occupies {} bytes", mem::size_of_val(&val2)); | |
let mut foo_val: Vec<i32> = vec![1, 2, 3]; | |
foo_val = vec![4, 5, 6]; | |
some_foo(&mut foo_val); | |
println!("{:?}", foo_val); | |
let rect = Rectangle { | |
p1: Point {x: 1.0, y: 1.0}, | |
p2: Point {x: 2.0, y: 2.0} | |
}; | |
println!("{:?}", rect_area(&rect)); | |
// let new_rect = square(Point {x: 1.0, y: 1.0}, 1.0); | |
// | |
// println!("{:?}", new_rect); | |
let mut p1 = Point {x: 1.0, y: 1.0}; | |
{ | |
let mut pointer = &p1; | |
let p2 = *pointer; | |
println!("{:?}", pointer); | |
println!("{:?}", p2); | |
} | |
let a1 = Point {x: 1.0, y: 1.0}; | |
let a2 = &a1; | |
let a3 = &a1; | |
println!("{:?}", a2); | |
println!("{:?}", a3); | |
p1.x = 2.0; | |
println!("{:?}", p1); | |
let match_val = 4u32; | |
match match_val { | |
0...1 => println!("HERE"), | |
4 => println!("HELLO"), | |
_ => println!("MORE") | |
} | |
// Returns a Utc DateTime one billion seconds after start. | |
pub fn after(start: DateTime<Utc>) -> DateTime<Utc> { | |
start + Duration::seconds(1000000000) | |
} | |
pub fn is_leap_year(year: i32) -> bool { | |
(year % 4 == 0) && (!(year % 100 == 0) || (year % 400 == 0)) | |
} | |
pub fn raindrops(n: usize) -> String { | |
let mut answer = String::from(""); | |
if n % 3 == 0 { | |
answer.push_str("Pling"); | |
} | |
if n % 5 == 0 { | |
answer.push_str("Plang"); | |
} | |
if n % 7 == 0 { | |
answer.push_str("Plong"); | |
} | |
if answer.is_empty() { | |
n.to_string() | |
} else { | |
answer | |
} | |
} | |
let utc: DateTime<Utc> = Utc::now(); | |
println!("{:?}", after(utc)); | |
println!("{}", is_leap_year(1900)); | |
println!("{}", is_leap_year(1996)); | |
println!("{}", is_leap_year(1997)); | |
println!("{}", is_leap_year(2000)); | |
println!("{}", raindrops(10)); | |
println!("{}", raindrops(28)); | |
println!("{}", raindrops(30)); | |
println!("{}", raindrops(34)); | |
// let mut str = String::from("cool"); | |
// for i in 0..str.len() { | |
// println!("{}", str[i]); | |
// } | |
// for (i, c) in str.chars().enumerate() { | |
// println!("{}", c); | |
// str[i] = str[str.len() - i]; | |
// } | |
pub fn reverse(str: &str) -> String { | |
str.chars().rev().collect::<String>() | |
} | |
println!("{}", reverse("")); | |
println!("{}", reverse("cool")); | |
// println!("{:?}", a); | |
println!("{:?}", nth(4)); | |
// println!("{:?}", nth(0)); | |
reply("hello"); | |
let arr = [true; THRESHOLD]; | |
for a in arr.iter() { | |
println!("{:?}", a); | |
} | |
println!("{}", difference(10)); | |
// println!("{}", verse(0)); | |
// println!("{}", verse(1)); | |
// println!("{}", verse(2)); | |
println!("{}", sing(8, 6)); | |
let mut scores = HashMap::new(); | |
scores.insert(String::from("Blue"), 10); | |
scores.insert(String::from("Yellow"), 50); | |
for (i, j) in &scores { | |
println!("{}: {}", i, j); | |
} | |
let v = vec![1, 2, 3, 4]; | |
// v.iter().fold(); | |
// let temp = "".parse().unwrap(); | |
println!("Sum: {}", sum_of_multiples(4, &vec![3, 5])); | |
println!("Sum: {}", sum_of_multiples(10, &vec![3, 5])); | |
let input = vec!["nail", "shoe", "horse", "rider", "message", "battle", "kingdom"]; | |
println!("{:?}", build_proverb(&input)); | |
// Doesn't work because of borrow checker: | |
// let mut r; | |
// let x = 5; | |
// r = &x; | |
// println!("r: {}", r); | |
let string1 = String::from("long string is long"); | |
{ | |
let string2 = String::from("xyz"); | |
let result; | |
result = longest(string1.as_str(), string2.as_str()); | |
println!("The longest string is {}", result); | |
} | |
{ | |
let string2 = String::from("short one"); | |
let announcement = String::from("HELLO THERE"); | |
let result = longest_with_an_announcement(&string1, &string2, announcement); | |
println!("The longest string with announcement is {}", result); | |
} | |
println!("{}", total()); | |
println!("{:?}", factors(60)); | |
// let expected = vec![ | |
// "92".to_string(), | |
// "20".to_string(), | |
// "01".to_string(), | |
// "17".to_string(), | |
// ]; | |
println!("{:?}", collatz(1000000)); | |
println!("{}", private_key(2)); | |
println!("{}", public_key(10, 2, 4)); | |
let p: u64 = 11; | |
let private_key_a = 7; | |
let public_key_b = 8; | |
let secret = secret(p, public_key_b, private_key_a); | |
println!("{}", u64::pow(2, 4)); | |
println!("{}", secret); | |
let slice = &"Golden Eagle"[1..6]; | |
println!("{}", slice); | |
println!("{:?}", series("92017", 2)); | |
} | |
pub fn find() -> u32 { | |
// let mut a = 1; | |
// let mut b = 1; | |
// let mut c = 1; | |
// for a in 1..998 { | |
// for b in 1..998 { | |
// let c = u32::sqrt(u32::pow(a, 2) + u32::pow(b, 2)); | |
// if a + b + c == 1000 { | |
// a * b * c | |
// } | |
// } | |
// } | |
42 | |
} | |
pub fn series(_digits: &str, _len: usize) -> Vec<String> { | |
let mut pointer = 0; | |
let mut ans = vec![]; | |
while _digits.len() >= pointer + _len { | |
ans.push(_digits[pointer..pointer + _len].to_string()); | |
pointer += 1; | |
} | |
ans | |
} | |
pub fn private_key(_p: u64) -> u64 { | |
rand::thread_rng().gen_range(1, _p) | |
} | |
pub fn public_key(_p: u64, _g: u64, _a: u64) -> u64 { | |
(u64::pow(_g, _a as u32)) % _p | |
} | |
pub fn secret(_p: u64, _b_pub: u64, _a: u64) -> u64 { | |
(u64::pow(_b_pub, _a as u32)) % _p | |
} | |
pub fn collatz(mut n: u64) -> Result<u64, &'static str> { | |
if n == 0 { | |
return Err("n is not positive"); | |
} | |
let mut counter = 0; | |
while n > 1 { | |
if n % 2 == 0 { | |
n /= 2; | |
} else { | |
n = 3 * n + 1; | |
} | |
counter += 1; | |
} | |
Ok(counter) | |
} | |
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str { | |
if x.len() > y.len() { | |
x | |
} else { | |
y | |
} | |
} | |
fn longest_with_an_announcement<'a, T>(x: &'a str, y: &'a str, ann: T) -> &'a str | |
where T: Display | |
{ | |
println!("Announcement! {}", ann); | |
if x.len() > y.len() { | |
x | |
} else { | |
y | |
} | |
} | |
pub fn build_proverb(input: &Vec<&str>) -> Vec<String> { | |
let mut answer: Vec<String> = vec![]; | |
for i in 0..input.len() - 1 { | |
answer.push(String::from(format!("For want of a {} the {} was lost.", input.get(i).unwrap(), input.get(i + 1).unwrap()))); | |
} | |
answer.push(String::from(format!("And all for the want of a {}.", input.get(0).unwrap()))); | |
// answer.join("\n"); | |
answer | |
} | |
// Lifetimes | |
struct Person<'a> { | |
name: &'a str, | |
} | |
impl<'a> Person<'a> { | |
fn greet(&self) { | |
println!("Hello, my name is {}", self.name); | |
} | |
} | |
//fn main() { | |
// let person = Person { name: "Herman" }; | |
// person.greet(); | |
//} | |
pub fn reply(message: &str) -> &str { | |
// let slice = message[..message.len()]; | |
// let all_capitals = true; | |
// for c in slice.chars() { | |
// println!("{}", c); | |
// } | |
"" | |
} | |
fn pow(base: u64, power: u64) -> u64 { | |
let mut ans = 1; | |
for i in 1..power { | |
ans *= base; | |
} | |
ans | |
} | |
pub fn square(s: u32) -> u64 { | |
if s < 1 || s > 64 { | |
panic!("Square must be between 1 and 64"); | |
} | |
let mut ans = 1; | |
for i in 1..s { | |
ans *= 2; | |
} | |
ans | |
} | |
pub fn total() -> u64 { | |
(2..66).fold(0, |sum, x| sum + square(x - 1)) | |
} | |
pub fn factors(n: u64) -> Vec<u64> { | |
let mut x = n; | |
let mut prime = 2; | |
let mut ans = vec![]; | |
while x > 1 { | |
if x % prime == 0 { | |
ans.push(prime); | |
x /= prime; | |
} else { | |
prime += 1; | |
} | |
} | |
ans | |
} | |
//pub fn sum_of_multiples(n: i32, v: &Vec<i32>) -> i32 { | |
// (1..n) | |
// .filter(|&x| is_divisible(&x, &v)) | |
// .fold(0, |sum, x| sum + x) | |
//} | |
pub fn sum_of_multiples(limit: u32, factors: &[u32]) -> u32 { | |
(1..limit) | |
.filter(|&x| is_divisible(&x, &factors)) | |
.fold(0, |sum, x| sum + x) | |
} | |
fn is_divisible(i: &u32, v: &[u32]) -> bool { | |
v.iter().any(|&x| i % x == 0) | |
} | |
pub fn square_of_sum(n: usize) -> usize { | |
let mut sum = 0; | |
for i in 0..n { | |
sum += i; | |
} | |
sum * sum | |
} | |
pub fn sum_of_squares(n: usize) -> usize { | |
let mut sum = 0; | |
for i in 0..n { | |
sum += i * i; | |
} | |
sum | |
} | |
pub fn difference(n: usize) -> usize { | |
square_of_sum(n + 1) - sum_of_squares(n + 1) | |
} | |
pub fn verse(n: i32) -> String { | |
match n { | |
0 => String::from("No more bottles of beer on the wall, no more bottles of beer.\nGo to the store and buy some more, 99 bottles of beer on the wall.\n"), | |
1 => String::from("1 bottle of beer on the wall, 1 bottle of beer.\nTake it down and pass it around, no more bottles of beer on the wall.\n"), | |
2 => String::from("2 bottles of beer on the wall, 2 bottles of beer.\nTake one down and pass it around, 1 bottle of beer on the wall.\n"), | |
3...99 => String::from(format!("{old} bottles of beer on the wall, {old} bottles of beer.\nTake one down and pass it around, {new} bottles of beer on the wall.\n", old = n, new = n - 1)), | |
_ => String::from("No song for you") | |
} | |
} | |
pub fn sing(start: i32, end: i32) -> String { | |
let mut answer = String::new(); | |
for i in (end + 1..start + 1).rev() { | |
answer.push_str(&verse(i)); | |
answer.push_str("\n"); | |
} | |
answer.push_str(&verse(end)); | |
answer | |
} | |
#[test] | |
fn test_zeroth_prime() { | |
assert!(nth(0).is_err()); | |
} | |
fn some_foo(v: &mut Vec<i32>) { | |
// v = 6; | |
// let mut v2 = v; | |
v.push(7); | |
// v2 = 6; | |
} | |
#[derive(Debug, Copy, Clone)] | |
struct Point { | |
x: f32, | |
y: f32, | |
} | |
#[derive(Debug)] | |
struct Rectangle { | |
p1: Point, | |
p2: Point, | |
} | |
fn rect_area(rect: &Rectangle) -> f32 { | |
let Point { x: x1, y: y1 } = rect.p1; | |
let Point { x: x2, y: y2 } = rect.p2; | |
(x1 - x2).abs() * (y1 - y2).abs() | |
} | |
//fn square(p1: Point, side: f32) -> Rectangle { | |
// Rectangle { | |
// p1, | |
// p2: Point { | |
// x: p1.x + side, | |
// y: p1.y + side | |
// } | |
// } | |
//} | |
#[derive(Debug)] | |
struct Matrix(f32, f32, f32, f32); | |
fn transpose(matrix: &mut Matrix) -> &mut Matrix { | |
let temp = matrix.1; | |
matrix.1 = matrix.2; | |
matrix.2 = temp; | |
matrix | |
} | |
fn traverse(head: &List) { | |
// let mut node = head; | |
// while node { | |
// println!("{:?}", node); | |
// } | |
} | |
fn foo(v: &Vec<i32>) -> Vec<i32> { | |
// let mut answer: [i32; 3] = [0; 3]; | |
let mut answer = vec![4, 4, 4]; | |
answer[0] = v[0]; | |
answer | |
} | |
#[derive(Debug)] | |
struct Book { | |
name: String, | |
author: String, | |
price: u32, | |
} | |
#[derive(Debug)] | |
enum List { | |
Cons(String, Rc<List>), | |
Nil, | |
} | |
//struct ListNode<T> { | |
// value: T, | |
// next: Rc<ListNode<T>>, | |
//} | |
// | |
//fn add<T>(tail: &ListNode<T>, value: T) -> ListNode<T> { | |
// let mut new_tail = ListNode { | |
// value, | |
// next: Rc::new(std::ptr::null()), | |
// }; | |
// tail.next = Rc::clone(&new_tail); | |
// new_tail | |
//} | |
// | |
//fn traverse(head: &ListNode<String>) { | |
// let mut node = head; | |
// while node != std::ptr::null() { | |
// println!("{}", node); | |
// node = node.next; | |
// } | |
//} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment