Skip to content

Rust version of IFS #755

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Dec 28, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions contents/IFS/IFS.md
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,8 @@ Here, instead of tracking children of children, we track a single individual tha
[import:5-14, lang:"lisp"](code/clisp/ifs.lisp)
{% sample lang="coco" %}
[import:4-16, lang:"coconut"](code/coconut/IFS.coco)
{% sample lang="rust" %}
[import:9-20, lang:"rust"](code/rust/IFS.rs)
{% sample lang="java" %}
[import:16-39, lang:"java"](code/java/IFS.java)
{% sample lang="ps1" %}
Expand Down Expand Up @@ -232,6 +234,8 @@ In addition, we have written the chaos game code to take in a set of points so t
[import, lang:"lisp"](code/clisp/ifs.lisp)
{%sample lang="coco" %}
[import, lang:"coconut"](code/coconut/IFS.coco)
{%sample lang="rust" %}
[import, lang:"rust"](code/rust/IFS.rs)
{%sample lang="java" %}
[import, lang:"java"](code/java/IFS.java)
{% sample lang="ps1" %}
Expand Down
13 changes: 13 additions & 0 deletions contents/IFS/code/rust/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
[package]
name = "rust"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
rand = "0.8.4"

[[bin]]
path = "./IFS.rs"
name = "main"
36 changes: 36 additions & 0 deletions contents/IFS/code/rust/IFS.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
use rand::*;

#[derive(Clone, Copy)]
struct Point {
x: f64,
y: f64,
}

fn chaos_game(iters: usize, shapes: Vec<Point>) -> Vec<Point> {
let mut rng = rand::thread_rng();
let mut p = Point{x: rng.gen(), y: rng.gen()};

(0..iters).into_iter().map(|_| {
let old_point = p;
let tmp = shapes[rng.gen_range(0..shapes.len())];
p.x = 0.5 * (p.x + tmp.x);
p.y = 0.5 * (p.y + tmp.y);
old_point
}).collect()
}

fn main() {
let shapes = vec![
Point{x: 0., y: 0.},
Point{x: 0.5, y: 0.75_f64.sqrt()},
Point{x: 1., y: 0.},
];

let mut out = String::new();

for point in chaos_game(10_000, shapes) {
out += format!("{}\t{}\n", point.x, point.y).as_str();
}

std::fs::write("./sierpinski.dat", out).unwrap();
}