Advertisement
Guest User

Untitled

a guest
May 25th, 2025
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rust 2.11 KB | Source Code | 0 0
  1. use rand::Rng;
  2. use std::collections::HashMap;
  3. use std::fs::File;
  4. use std::io::{BufWriter, Write};
  5.  
  6. const WIDTH: i32 = 640;
  7. const HEIGHT: i32 = 640;
  8. const N_OF_POINTS: usize = 10;
  9.  
  10. fn dist(x1: i32, y1: i32, x2: i32, y2: i32) -> f64 {
  11.     let result: f64 = ((x1 - x2).pow(2) as f64 + (y1 - y2).pow(2) as f64); // sqrt is not necessary
  12.     result // fun fact, the last statement of a function just returns
  13. }
  14.  
  15. #[derive(Debug)]
  16. struct Point {
  17.     x: i32,
  18.     y: i32,
  19.     r: i32,
  20.     g: i32,
  21.     b: i32,
  22. }
  23.  
  24. pub fn main(filename: &str) {
  25.     let mut rng = rand::rng();
  26.     let f = File::create(filename).unwrap();
  27.     // a BufWriter keeps the file contents in memory, this is much faster than
  28.     // syscalls from writing directly to a file.
  29.     // The best part? BufWriter will write to the file for you when it calls
  30.     // Drop
  31.     let mut file = BufWriter::new(f);
  32.     let header = format!("P3\n{}\n{}\n255\n", WIDTH, HEIGHT);
  33.     file.write_all(header.as_bytes()).unwrap();
  34.  
  35.     // HashMap was unnessecary, Vec is fine
  36.     // creating with capacity can decrease memory allocation
  37.     let mut points: Vec<Point> = Vec::with_capacity(N_OF_POINTS);
  38.  
  39.     // Create random points
  40.     for _ in 0..N_OF_POINTS {
  41.         let x = rng.random_range(0..WIDTH);
  42.         let y = rng.random_range(0..HEIGHT);
  43.         let r = rng.random_range(0..=255);
  44.         let g = rng.random_range(0..=255);
  45.         let b = rng.random_range(0..=255);
  46.  
  47.         let point = Point { x, y, r, g, b };
  48.  
  49.         points.push(point);
  50.     }
  51.  
  52.     for y in 0..HEIGHT {
  53.         for x in 0..WIDTH {
  54.             let mut chosen_color = String::new();
  55.             let mut closest_distance: f64 = f64::MAX;
  56.  
  57.             for point in points.iter() {
  58.                 let d = dist(x, y, point.x, point.y);
  59.                 if d < closest_distance {
  60.                     closest_distance = d;
  61.                     // .to_string was unnessecary
  62.                     chosen_color = format!("{} {} {}\n", point.r, point.g, point.b);
  63.                 }
  64.             }
  65.             file.write_all(chosen_color.as_bytes()).unwrap();
  66.         }
  67.     }
  68. }
  69.  
Tags: rust
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement