Skip to content

Commit

Permalink
Rust version of IFS (algorithm-archivists#755)
Browse files Browse the repository at this point in the history
* add the rust version of the ifs

* Apply suggestions from code review

Co-authored-by: Dimitri Belopopsky <[email protected]>
Co-authored-by: stormofice <[email protected]>

* add a cargo toml

Co-authored-by: Dimitri Belopopsky <[email protected]>
Co-authored-by: stormofice <[email protected]>
  • Loading branch information
3 people authored Dec 28, 2021
1 parent fd6b7a6 commit 51936d7
Show file tree
Hide file tree
Showing 3 changed files with 53 additions and 0 deletions.
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();
}

0 comments on commit 51936d7

Please sign in to comment.