Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- use rand::Rng;
- use std::collections::HashMap;
- use std::fs::File;
- use std::io::{BufWriter, Write};
- const WIDTH: i32 = 640;
- const HEIGHT: i32 = 640;
- const N_OF_POINTS: usize = 10;
- fn dist(x1: i32, y1: i32, x2: i32, y2: i32) -> f64 {
- let result: f64 = ((x1 - x2).pow(2) as f64 + (y1 - y2).pow(2) as f64); // sqrt is not necessary
- result // fun fact, the last statement of a function just returns
- }
- #[derive(Debug)]
- struct Point {
- x: i32,
- y: i32,
- r: i32,
- g: i32,
- b: i32,
- }
- pub fn main(filename: &str) {
- let mut rng = rand::rng();
- let f = File::create(filename).unwrap();
- // a BufWriter keeps the file contents in memory, this is much faster than
- // syscalls from writing directly to a file.
- // The best part? BufWriter will write to the file for you when it calls
- // Drop
- let mut file = BufWriter::new(f);
- let header = format!("P3\n{}\n{}\n255\n", WIDTH, HEIGHT);
- file.write_all(header.as_bytes()).unwrap();
- // HashMap was unnessecary, Vec is fine
- // creating with capacity can decrease memory allocation
- let mut points: Vec<Point> = Vec::with_capacity(N_OF_POINTS);
- // Create random points
- for _ in 0..N_OF_POINTS {
- let x = rng.random_range(0..WIDTH);
- let y = rng.random_range(0..HEIGHT);
- let r = rng.random_range(0..=255);
- let g = rng.random_range(0..=255);
- let b = rng.random_range(0..=255);
- let point = Point { x, y, r, g, b };
- points.push(point);
- }
- for y in 0..HEIGHT {
- for x in 0..WIDTH {
- let mut chosen_color = String::new();
- let mut closest_distance: f64 = f64::MAX;
- for point in points.iter() {
- let d = dist(x, y, point.x, point.y);
- if d < closest_distance {
- closest_distance = d;
- // .to_string was unnessecary
- chosen_color = format!("{} {} {}\n", point.r, point.g, point.b);
- }
- }
- file.write_all(chosen_color.as_bytes()).unwrap();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement