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::Write;
- const WIDTH: i32 = 640;
- const HEIGHT: i32 = 640;
- const N_OF_POINTS: i32 = 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();
- return result;
- }
- #[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 mut file = File::create(filename).unwrap();
- let header = format!("P3\n{}\n{}\n255\n", WIDTH, HEIGHT);
- file.write_all(header.as_bytes()).unwrap();
- let mut points: HashMap<i32, Point> = HashMap::new();
- // Create random points
- for index 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.insert(index, 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 {
- let d = dist(x, y, point.x, point.y);
- if d < closest_distance {
- closest_distance = d;
- chosen_color = format!("{} {} {}\n", point.r, point.g, point.b).to_string();
- }
- }
- file.write_all(chosen_color.as_bytes()).unwrap();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement