use std::io;
use std::io::BufRead;

fn parse_entry(l: &str) -> (i32, String) {
    let params: Vec<&str> = l.split(' ').collect();

    let divisor = params[0].parse::<i32>().unwrap();
    let word = params[1].to_string();
    (divisor, word)
}

fn main() {
    let stdin = io::stdin();
    let mut lines = stdin.lock().lines().map(|l| l.unwrap());

    let l = lines.next().unwrap();
    let high = l.parse::<i32>().unwrap();

    let mut entries = Vec::new();
    for l in lines {
        if &l == "" { break }
        let entry = parse_entry(&l);
        entries.push(entry);
    }

    for i in 1..(high + 1) {
        let mut line = String::new();
        for &(divisor, ref word) in &entries {
            if i % divisor == 0 {
                line = line + &word;
            }
        }
        if line == "" {
            println!("{}", i);
        } else {
            println!("{}", line);
        }
    }
}

use std::collections::BTreeMap;
use std::fmt::{self, Write};
use std::io::{self, Stdin};

#[derive(Debug, PartialEq)]
pub struct FizzBuzz {
    end: usize,
    factors: Factors,
}

impl FizzBuzz {
    fn from_reader(rdr: &Stdin) -> Result<FizzBuzz, Box<dyn std::error::Error>> {
        let mut line = String::new();
        rdr.read_line(&mut line)?;

        let end = line.trim().parse::<usize>()?;

        let mut factors = Factors::new();

        loop {
            let mut line = String::new();
            rdr.read_line(&mut line)?;

            if line.trim().is_empty() { break; }

            let mut split = line.trim().splitn(2, ' ');

            let factor = match split.next() {
                Some(f) => f.parse::<usize>()?,
                None => break,
            };

            let phrase = match split.next() {
                Some(p) => p,
                None => break,
            };

            factors.insert(factor, phrase.to_string());
        }

        Ok(FizzBuzz { end, factors })
    }
}

impl fmt::Display for FizzBuzz {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        for n in 1..=self.end {
            let mut had_factor = false;

            // check for factors
            for (factor, phrase) in self.factors.iter() {
                if n % factor == 0 {
                    f.write_str(&phrase)?;
                    had_factor = true;
                }
            }

            if !had_factor {
                f.write_str(n.to_string().as_str())?;
            }
            f.write_char('\n')?;
        }
        Ok(())
    }
}

type Factors = BTreeMap<usize, String>;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let input = io::stdin();

    let fizz_buzz = FizzBuzz::from_reader(&input)?;

    println!("{}", fizz_buzz);

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn fizz_buzz_prints_expected_format() {
        let expected_factors = {
            let mut map = Factors::new();
            map.insert(3, "Fizz".to_string());
            map.insert(5, "Buzz".to_string());
            map.insert(7, "Baxx".to_string());
            map
        };

        let expected_end = 20;

        let fizz_buzz = FizzBuzz {
            end: expected_end,
            factors: expected_factors,
        };

        let expected = r#"1
2
Fizz
4
Buzz
Fizz
Baxx
8
Fizz
Buzz
11
Fizz
13
Baxx
FizzBuzz
16
17
Fizz
19
Buzz
"#;
        let printed = format!("{}", fizz_buzz);

        assert_eq!(expected, &printed);
    }
}

The code takes a maximum number and three factors with their corresponding words as input from the user. It prints numbers from 1 to the maximum number, replacing multiples of the factors with their corresponding words. If a number is a multiple of more than one factor, it prints all corresponding words in the order of the factors. The FizzBuzz state is stored in a struct for a more generalized solution.


let mut s = "World".to_string();
s.insert_str(0, "Hello ");
println!("{}", s);

Creates a string variable with a specific text value, prepends another string literal to it, and displays the content of the variable. If possible, the operation is performed without referring to the variable twice in one expression.


use ggez::{
    conf::{WindowMode, WindowSetup},
    error::GameResult,
    event,
    graphics::{clear, draw, present, Color, MeshBuilder},
    nalgebra::Point2,
    Context,
};
use std::time::Duration;

// L-System to create the sequence needed for a Dragon Curve.
// This function creates the next generation given the current one
// L-System from https://www.cs.unm.edu/~joel/PaperFoldingFractal/L-system-rules.html
//
fn l_system_next_generation(current_generation: &str) -> String {
    let f_rule = "f-h";
    let h_rule = "f+h";
    let mut next_gen = String::new();
    for char in current_generation.chars() {
        match char {
            'f' => next_gen.push_str(f_rule),
            'h' => next_gen.push_str(h_rule),
            '-' | '+' => next_gen.push(char),
            _ => panic!("Unknown char {}", char),
        }
    }
    next_gen
}

// The rest of the code is for drawing the output and is specific to using the
// ggez 2d game library: https://ggez.rs/

const WINDOW_WIDTH: f32 = 700.0;
const WINDOW_HEIGHT: f32 = 700.0;
const START_X: f32 = WINDOW_WIDTH / 6.0;
const START_Y: f32 = WINDOW_HEIGHT / 6.0;
const MAX_DEPTH: i32 = 15;
const LINE_LENGTH: f32 = 20.0;

struct MainState {
    start_gen: String,
    next_gen: String,
    line_length: f32,
    max_depth: i32,
    current_depth: i32,
}

impl MainState {
    fn new() -> GameResult<MainState> {
        let start_gen = "f";
        let next_gen = String::new();
        let line_length = LINE_LENGTH;
        let max_depth = MAX_DEPTH;
        let current_depth = 0;
        Ok(MainState {
            start_gen: start_gen.to_string(),
            next_gen,
            line_length,
            max_depth,
            current_depth,
        })
    }
}

impl event::EventHandler for MainState {
    // In each repetition of the event loop a new generation of the L-System
    // is generated and drawn, until the maximum depth is reached.
    // Each time the line length is reduced so that the overall dragon curve
    // can be seen in the window as it spirals and gets bigger.
    // The update sleeps for 0.5 seconds just so that its pogression can be watched.
    //
    fn update(&mut self, _ctx: &mut Context) -> GameResult {
        if self.current_depth < self.max_depth {
            self.next_gen = l_system_next_generation(&self.start_gen);
            self.start_gen = self.next_gen.clone();
            self.line_length -= (self.line_length / self.max_depth as f32) * 1.9;
            self.current_depth += 1;
        }
        ggez::timer::sleep(Duration::from_millis(500));
        Ok(())
    }

    fn draw(&mut self, ctx: &mut Context) -> GameResult {
        let grey = Color::from_rgb(77, 77, 77);
        let blue = Color::from_rgb(51, 153, 255);
        let initial_point_blue = Point2::new(START_X, START_Y);
        clear(ctx, grey);
        draw_lines(
            &self.next_gen,
            ctx,
            self.line_length,
            blue,
            initial_point_blue,
        )?;
        present(ctx)?;
        Ok(())
    }
}

fn next_point(current_point: Point2<f32>, heading: f32, line_length: f32) -> Point2<f32> {
    let next_point = (
        (current_point.x + (line_length * heading.to_radians().cos().trunc() as f32)),
        (current_point.y + (line_length * heading.to_radians().sin().trunc() as f32)),
    );
    Point2::new(next_point.0, next_point.1)
}

fn draw_lines(
    instructions: &str,
    ctx: &mut Context,
    line_length: f32,
    colour: Color,
    initial_point: Point2<f32>,
) -> GameResult {
    let line_width = 2.0;
    let mut heading = 0.0;
    let turn_angle = 90.0;
    let mut start_point = initial_point;
    let mut line_builder = MeshBuilder::new();
    for char in instructions.chars() {
        let end_point = next_point(start_point, heading, line_length);
        match char {
            'f' | 'h' => {
                line_builder.line(&[start_point, end_point], line_width, colour)?;
                start_point = end_point;
            }
            '+' => heading += turn_angle,
            '-' => heading -= turn_angle,
            _ => panic!("Unknown char {}", char),
        }
    }
    let lines = line_builder.build(ctx)?;
    draw(ctx, &lines, (initial_point,))?;
    Ok(())
}

fn main() -> GameResult {
    let cb = ggez::ContextBuilder::new("dragon curve", "huw")
        .window_setup(WindowSetup::default().title("Dragon curve"))
        .window_mode(WindowMode::default().dimensions(WINDOW_WIDTH, WINDOW_HEIGHT));
    let (ctx, event_loop) = &mut cb.build()?;
    let state = &mut MainState::new()?;
    event::run(ctx, event_loop, state)
}

File:Dragon curve rust.gif

generate a dragon curve fractal either directly or by writing it to an image file. The fractal is created using various algorithms such as recursive, successive approximation, iterative, and Lindenmayer system of expansions. The algorithms consider curl direction, bit transitions, and absolute X, Y coordinates. The code also includes functionality to test whether a given X,Y point or segment is on the curve. The code is adaptable to different programming languages and drawing methods.


Library: rand
extern crate rand;

fn main() {
    println!("Type in an integer between 1 and 10 and press enter.");

    let n = rand::random::<u32>() % 10 + 1;
    loop {
        let mut line = String::new();
        std::io::stdin().read_line(&mut line).unwrap();
        let option: Result<u32,_> = line.trim().parse();
        match option {
            Ok(guess) => {
                if guess < 1 || guess > 10 {
                    println!("Guess is out of bounds; try again.");
                } else if guess == n {
                    println!("Well guessed!");
                    break;
                } else {
                    println!("Wrong! Try again.");
                }
            },
            Err(_) => println!("Invalid input; try again.")
        }
    }
}

"Implement a number guessing game where the computer selects a number between 1 and 10. The player is repeatedly prompted to guess the number until the correct number is guessed, upon which a 'Well guessed!' message is displayed and the program terminates. A conditional loop is used to facilitate repeated guessing."


fn main() {
    // An iterator over the lowercase alpha's
    let ascii_iter = (0..26)
        .map(|x| (x + b'a') as char);

    println!("{:?}", ascii_iter.collect::<Vec<char>>());
}

generate a sequence of all lower case ASCII characters from a to z. This is done in a reliable coding style suitable for large programs, using strong typing if available. The code avoids manual enumeration of characters to prevent bugs. It also demonstrates how to access a similar sequence from the standard library if it exists.


The code takes a non-negative integer as input and converts it into a binary sequence. It uses built-in radix functions or a user-defined function to perform the conversion. The output is a sequence of binary digits followed by a newline, with no additional whitespace, radix, sign markers, or leading zeros.


Library: piston_window
Library: image

Output Image: RustOut

extern crate piston_window;
extern crate image;

use piston_window::*;

fn main() {
    let (width, height) = (320, 240);

    let mut window: PistonWindow =
        WindowSettings::new("Red Pixel", [width, height])
        .exit_on_esc(true).build().unwrap();

    // Since we cant manipulate pixels directly, we need to manipulate the pixels on a canvas.
    // Only issue is that sub-pixels exist (which is probably why the red pixel looks like a smear on the output image)
    let mut canvas = image::ImageBuffer::new(width, height);
    canvas.put_pixel(100, 100, image::Rgba([0xff, 0, 0, 0xff]));

    // Transform into a texture so piston can use it.
    let texture: G2dTexture = Texture::from_image(
        &mut window.factory,
        &canvas,
        &TextureSettings::new()
    ).unwrap();

    // The window event loop.
    while let Some(event) = window.next() {
        window.draw_2d(&event, |context, graphics| {
            clear([1.0; 4], graphics);
            image(&texture,
            context.transform,
            graphics);
        });
    }
}

create a 320x240 window and draw a red pixel at position (100, 100).


use std::fs::File;
use std::io::BufRead;
use std::io::BufReader;
use std::iter::FromIterator;
use std::path::Path;

fn main() {
    let path = String::from("file.conf");
    let cfg = config_from_file(path);
    println!("{:?}", cfg);
}

fn config_from_file(path: String) -> Config {
    let path = Path::new(&path);
    let file = File::open(path).expect("File not found or cannot be opened");
    let content = BufReader::new(&file);
    let mut cfg = Config::new();

    for line in content.lines() {
        let line = line.expect("Could not read the line");
        // Remove whitespaces at the beginning and end
        let line = line.trim();

        // Ignore comments and empty lines
        if line.starts_with("#") || line.starts_with(";") || line.is_empty() {
            continue;
        }

        // Split line into parameter name and rest tokens
        let tokens = Vec::from_iter(line.split_whitespace());
        let name = tokens.first().unwrap();
        let tokens = tokens.get(1..).unwrap();

        // Remove the equal signs
        let tokens = tokens.iter().filter(|t| !t.starts_with("="));
        // Remove comment after the parameters
        let tokens = tokens.take_while(|t| !t.starts_with("#") && !t.starts_with(";"));

        // Concat back the parameters into one string to split for separated parameters
        let mut parameters = String::new();
        tokens.for_each(|t| { parameters.push_str(t); parameters.push(' '); });
        // Splits the parameters and trims
        let parameters = parameters.split(',').map(|s| s.trim());
        // Converts them from Vec<&str> into Vec<String>
        let parameters: Vec<String> = parameters.map(|s| s.to_string()).collect();

        // Setting the config parameters
        match name.to_lowercase().as_str() {
            "fullname" => cfg.full_name = parameters.get(0).cloned(),
            "favouritefruit" => cfg.favourite_fruit = parameters.get(0).cloned(),
            "needspeeling" => cfg.needs_peeling = true,
            "seedsremoved" => cfg.seeds_removed = true,
            "otherfamily" => cfg.other_family = Some(parameters),
            _ => (),
        }
    }

    cfg
}

#[derive(Clone, Debug)]
struct Config {
    full_name: Option<String>,
    favourite_fruit: Option<String>,
    needs_peeling: bool,
    seeds_removed: bool,
    other_family: Option<Vec<String>>,
}

impl Config {
    fn new() -> Config {
        Config {
            full_name: None,
            favourite_fruit: None,
            needs_peeling: false,
            seeds_removed: false,
            other_family: None,
        }
    }
}

read a configuration file and set variables based on the contents. It ignores lines starting with a hash or semicolon and blank lines. It sets variables 'fullname', 'favouritefruit', 'needspeeling', and 'seedsremoved' based on the file entries. It also stores multiple parameters from the 'otherfamily' entry into an array.


struct Point {
    lat: f64,
    lon: f64,
}

fn haversine(origin: Point, destination: Point) -> f64 {
    const R: f64 = 6372.8;

    let lat1 = origin.lat.to_radians();
    let lat2 = destination.lat.to_radians();
    let d_lat = lat2 - lat1;
    let d_lon = (destination.lon - origin.lon).to_radians();

    let a = (d_lat / 2.0).sin().powi(2) + (d_lon / 2.0).sin().powi(2) * lat1.cos() * lat2.cos();
    let c = 2.0 * a.sqrt().asin();
    R * c
}

#[cfg(test)]
mod test {
    use super::{Point, haversine};

    #[test]
    fn test_haversine() {
        let origin: Point = Point {
            lat: 36.12,
            lon: -86.67
        };
        let destination: Point = Point {
            lat: 33.94,
            lon: -118.4
        };
        let d: f64 = haversine(origin, destination);
        println!("Distance: {} km ({} mi)", d, d / 1.609344);
        assert_eq!(d, 2887.2599506071106);
    }

}
Output Distance: 2887.2599506071106 km (1794.060157807846 mi)

Implement a function to calculate the great-circle distance between two points on a sphere using the Haversine formula. The function takes the coordinates of Nashville International Airport (BNA) and Los Angeles International Airport (LAX) as input and returns the distance between them. The calculation uses the recommended earth radius of 6372.8 km or 6371 km, depending on the level of precision required.


[dependencies]
hyper = "0.6"

//cargo-deps: hyper="0.6"
// The above line can be used with cargo-script which makes cargo's dependency handling more convenient for small programs
extern crate hyper;

use std::io::Read;
use hyper::client::Client;

fn main() {
    let client = Client::new();
    let mut resp = client.get("http://rosettacode.org").send().unwrap();
    let mut body = String::new();
    resp.read_to_string(&mut body).unwrap();
    println!("{}", body);
}

The code accesses a specified URL's content and prints it to the console using HTTP requests. Note that handling HTTPS requests is not included in this code.


extern crate luhn_test_of_credit_card_numbers;

use luhn_test_of_credit_card_numbers::luhn_test;

fn validate_isin(isin: &str) -> bool {
    if !isin.chars().all(|x| x.is_alphanumeric()) || isin.len() != 12 {
        return false;
    }
    if !isin[..2].chars().all(|x| x.is_alphabetic())
        || !isin[2..12].chars().all(|x| x.is_alphanumeric())
        || !isin.chars().last().unwrap().is_numeric()
    {
        return false;
    }

    let bytes = isin.as_bytes();

    let s2 = bytes
        .iter()
        .flat_map(|&c| {
            if c.is_ascii_digit() {
                vec![c]
            } else {
                (c + 10 - ('A' as u8)).to_string().into_bytes()
            }
        })
        .collect::<Vec<u8>>();

    let string = std::str::from_utf8(&s2).unwrap();
    let number = string.parse::<u64>().unwrap();

    return luhn_test(number as u64);
}

#[cfg(test)]
mod tests {
    use super::validate_isin;

    #[test]
    fn test_validate_isin() {
        assert_eq!(validate_isin("US0378331005"), true);
        assert_eq!(validate_isin("US0373831005"), false);
        assert_eq!(validate_isin("U50378331005"), false);
        assert_eq!(validate_isin("US03378331005"), false);
        assert_eq!(validate_isin("AU0000XVGZA3"), true);
        assert_eq!(validate_isin("AU0000VXGZA3"), true);
        assert_eq!(validate_isin("FR0000988040"), true);
    }
}

The code validates credit card numbers using the Luhn test. It reverses the input number, calculates the sum of odd and even positioned digits (with even digits being doubled and if the result is greater than nine, the digits of the result are summed). If the total sum ends in zero, the number is deemed valid. The code tests this functionality on four given numbers.


const N: usize = 41;
const K: usize = 3;
const M: usize = 3;
const POSITION: usize = 5;

fn main() {
    let mut prisoners: Vec<usize> = Vec::new();
    let mut executed: Vec<usize> = Vec::new();
    for pos in 0..N {
        prisoners.push(pos);
    }

    let mut to_kill: usize = 0;
    let mut len: usize = prisoners.len();

    while len > M {
        to_kill = (to_kill + K - 1) % len;
        executed.push(prisoners.remove(to_kill));
        len -= 1;
    }

    println!("JOSEPHUS n={}, k={}, m={}", N, K, M);
    println!("Executed: {:?}", executed);
    println!("Executed position number {}: {}", POSITION, executed[POSITION - 1]);
    println!("Survivors: {:?}", prisoners);
}

- Determine the final survivor in the Josephus problem given any number of prisoners (n) and a step count (k).
- Calculate the position of any prisoner in the killing sequence.
- Provide an option to save a certain number of prisoners (m).
- The numbering of prisoners can start from either 0 or 1.
- The complexity of the solution is O(kn) for the complete killing sequence and O(m) for finding the m-th prisoner to die.


std::iter::repeat("ha").take(5).collect::<String>(); // ==> "hahahahaha"

"ha".repeat(5); // ==> "hahahahaha"

Code summarization: The code repeats a given string or a single character a specified number of times. For example, it can turn "ha" into "hahahahaha" when repeated 5 times, or "*" into "*****" when repeated 5 times.


use regex::Regex;

fn main() {
    let s = "I am a string";

    if Regex::new("string$").unwrap().is_match(s) {
        println!("Ends with string.");
    }

    println!("{}", Regex::new(" a ").unwrap().replace(s, " another "));
}

The code matches a string against a regular expression and substitutes part of the string using the same regular expression. It also checks for a valid regex using Regex::new, returning a Result<Regex, Error>.


use std::env;

fn main() {
    let args: Vec<_> = env::args().collect();
    let a = args[1].parse::<i32>().unwrap();
    let b = args[2].parse::<i32>().unwrap();

    println!("sum:              {}", a + b);
    println!("difference:       {}", a - b);
    println!("product:          {}", a * b);
    println!("integer quotient: {}", a / b); // truncates towards zero
    println!("remainder:        {}", a % b); // same sign as first operand
}

take two integers as input from the user and calculate their sum, difference, product, integer quotient, remainder, and exponentiation. The code also indicates the rounding method for the quotient and the sign of the remainder. It does not include error handling. Additionally, it provides an example of the 'divmod' operator. However, this code cannot be executed in the Rust playpen due to its lack of console input support.


fn main() {
    println!("{}","the three truths".matches("th").count());
    println!("{}","ababababab".matches("abab").count());
}

The code defines a function to count the number of non-overlapping occurrences of a given substring within a larger string. The function takes two arguments: the main string and the substring to search for. It returns an integer representing the count of non-overlapping occurrences. The function prioritizes the highest number of non-overlapping matches, typically matching from left-to-right or right-to-left.


fn move_(n: i32, from: i32, to: i32, via: i32) {
    if n > 0 {
        move_(n - 1, from, via, to);
        println!("Move disk from pole {} to pole {}", from, to);
        move_(n - 1, via, to, from);
    }
}

fn main() {
    move_(4, 1,2,3);
}

"Implement a recursive solution to solve the Towers of Hanoi problem."


fn fact(n:u32) -> u64 {
  let mut f:u64 = n as u64;
  for i in 2..n {
    f *= i as u64;
  }
  return f;
}

fn choose(n: u32, k: u32)  -> u64 {
   let mut num:u64 = n as u64;
   for i in 1..k {
     num *= (n-i) as u64;
   }
   return num / fact(k);
}

fn main() {
  println!("{}", choose(5,3));
}

The code calculates any binomial coefficient using the provided formula. It is capable of outputting the binomial coefficient of 5 choose 3, which is 10. The code also includes tasks related to combinations and permutations, both with and without replacement. An alternative version of the code uses a functional style.


fn shell_sort<T: Ord + Copy>(v: &mut [T]) {
    let mut gap = v.len() / 2;
    let len = v.len();
    while gap > 0 {
        for i in gap..len {
            let temp = v[i];
            let mut j = i;
            while j >= gap && v[j - gap] > temp {
                v[j] = v[j - gap];
                j -= gap;
            }
            v[j] = temp;
        }
        gap /= 2;
    }
}

fn main() {
    let mut numbers = [4i32, 65, 2, -31, 0, 99, 2, 83, 782, 1];
    println!("Before: {:?}", numbers);
    shell_sort(&mut numbers);
    println!("After: {:?}", numbers);
}

implement the Shell sort algorithm to sort an array of elements. This algorithm, invented by Donald Shell, uses a diminishing increment sort and interleaved insertion sorts based on an increment sequence. The increment size reduces after each pass until it reaches 1, turning the sort into a basic insertion sort. The data is almost sorted at this point, providing the best case for insertion sort. The increment sequence can vary but should always end in 1. Sequences with a geometric increment ratio of about 2.2 have been found to work well.


#[cfg(feature = "gtk")]
mod graphical {
    extern crate gtk;

    use self::gtk::traits::*;
    use self::gtk::{Inhibit, Window, WindowType};
    use std::ops::Not;
    use std::sync::{Arc, RwLock};

    pub fn create_window() {
        gtk::init().expect("Failed to initialize GTK");

        let window = Window::new(WindowType::Toplevel);
        window.connect_delete_event(|_, _| {
            gtk::main_quit();
            Inhibit(false)
        });
        let button = gtk::Button::new_with_label("Hello World! ");
        window.add(&button);

        let lock = Arc::new(RwLock::new(false));

        let lock_button = lock.clone();
        button.connect_clicked(move |_| {
            let mut reverse = lock_button.write().unwrap();
            *reverse = reverse.not();
        });

        let lock_thread = lock.clone();
        gtk::timeout_add(100, move || {
            let reverse = lock_thread.read().unwrap();
            let mut text = button.get_label().unwrap();
            let len = &text.len();

            if *reverse {
                let begin = &text.split_off(1);
                text.insert_str(0, begin);
            } else {
                let end = &text.split_off(len - 1);
                text.insert_str(0, end);
            }

            button.set_label(&text);

            gtk::Continue(true)
        });

        window.show_all();
        gtk::main();
    }
}

#[cfg(feature = "gtk")]
fn main() {
    graphical::create_window();
}

#[cfg(not(feature = "gtk"))]
fn main() {}

Create a GUI animation where the string "Hello World! " appears to rotate right by periodically moving the last letter to the front. The direction of rotation reverses when the user clicks on the text.


let mut x = 0;

loop {
    x += 1;
    println!("{}", x);

    if x % 6 == 0 { break; }
}

The code initializes a value to 0 and enters a loop, which continues until the value modulo 6 is not 0. In each iteration, the value is incremented by 1 and then printed. The loop is guaranteed to run at least once. This is implemented in Rust using the 'loop' keyword with a termination condition.


fn main() {
    let s = "文字化け";  // UTF-8
    println!("Byte Length: {}", s.len());
}
fn main() {
    let s = "文字化け";  // UTF-8
    println!("Character length: {}", s.chars().count());
}

calculate the character and byte length of a string, considering UTF-8 and UTF-16 encodings. They handle non-BMP code points correctly, providing actual character counts in code points, not in code unit counts. The codes also have the ability to provide the string length in graphemes if the language supports it.


extern crate rand;

use rand::{OsRng, Rng};

fn main() {
    // because `OsRng` opens files, it may fail
    let mut rng = match OsRng::new() {
        Ok(v) => v,
        Err(e) => panic!("Failed to obtain OS RNG: {}", e)
    };

    let rand_num: u32 = rng.gen();
    println!("{}", rand_num);
}

demonstrate how to generate a random 32-bit number using the system's built-in mechanism, not just a software algorithm. It utilizes the 'rand' crate, previously part of the Rust standard library, which supports various platforms including Unix, Windows, BSD, and iOS. Other methods like RDRAND can be found in other crates.


fn main() {
    let s = String::from("žluťoučký kůň");

    let mut modified = s.clone();
    modified.remove(0);
    println!("{}", modified);

    let mut modified = s.clone();
    modified.pop();
    println!("{}", modified);

    let mut modified = s;
    modified.remove(0);
    modified.pop();
    println!("{}", modified);
}

fn main() {
    let s = "žluťoučký kůň";

    println!(
        "{}",
        s.char_indices()
            .nth(1)
            .map(|(i, _)| &s[i..])
            .unwrap_or_default()
    );

    println!(
        "{}",
        s.char_indices()
            .nth_back(0)
            .map(|(i, _)| &s[..i])
            .unwrap_or_default()
    );

    println!(
        "{}",
        s.char_indices()
            .nth(1)
            .and_then(|(i, _)| s.char_indices().nth_back(0).map(|(j, _)| i..j))
            .map(|range| &s[range])
            .unwrap_or_default()
    );
}

demonstrate how to remove the first and/or last characters from a string, supporting any valid Unicode code point in UTF-8 or UTF-16 encoding. The program handles logical characters, not code units. It provides two methods: modifying the owned string representation or cutting a string slice without assuming the string length. Handling of other encodings like 8-bit ASCII or EUC-JP is not required.


use std::net::TcpListener;

fn create_app_lock(port: u16) -> TcpListener {
    match TcpListener::bind(("0.0.0.0", port)) {
        Ok(socket) => {
            socket
        },
        Err(_) => {
            panic!("Couldn't lock port {}: another instance already running?", port);
        }
    }
}

fn remove_app_lock(socket: TcpListener) {
    drop(socket);
}

fn main() {
    let lock_socket = create_app_lock(12345);
    // ...
    // your code here
    // ...
    remove_app_lock(lock_socket);
}

"Check if a single instance of an application is running using TCP socket, display a message and exit if another instance is found."


type Sudoku = [u8; 81];

fn is_valid(val: u8, x: usize, y: usize, sudoku_ar: &mut Sudoku) -> bool {
    (0..9).all(|i| sudoku_ar[y * 9 + i] != val && sudoku_ar[i * 9 + x] != val) && {
        let (start_x, start_y) = ((x / 3) * 3, (y / 3) * 3);
        (start_y..start_y + 3).all(|i| (start_x..start_x + 3).all(|j| sudoku_ar[i * 9 + j] != val))
    }
}

fn place_number(pos: usize, sudoku_ar: &mut Sudoku) -> bool {
    (pos..81).find(|&p| sudoku_ar[p] == 0).map_or(true, |pos| {
        let (x, y) = (pos % 9, pos / 9);
        for n in 1..10 {
            if is_valid(n, x, y, sudoku_ar) {
                sudoku_ar[pos] = n;
                if place_number(pos + 1, sudoku_ar) {
                    return true;
                }
                sudoku_ar[pos] = 0;
            }
        }
        false
    })
}

fn pretty_print(sudoku_ar: Sudoku) {
    let line_sep = "------+-------+------";
    println!("{}", line_sep);
    for (i, e) in sudoku_ar.iter().enumerate() {
        print!("{} ", e);
        if (i + 1) % 3 == 0 && (i + 1) % 9 != 0 {
            print!("| ");
        }
        if (i + 1) % 9 == 0 {
            println!(" ");
        }
        if (i + 1) % 27 == 0 {
            println!("{}", line_sep);
        }
    }
}

fn solve(sudoku_ar: &mut Sudoku) -> bool {
    place_number(0, sudoku_ar)
}

fn main() {
    let mut sudoku_ar: Sudoku = [
        8, 5, 0, 0, 0, 2, 4, 0, 0,
        7, 2, 0, 0, 0, 0, 0, 0, 9,
        0, 0, 4, 0, 0, 0, 0, 0, 0,
        0, 0, 0, 1, 0, 7, 0, 0, 2,
        3, 0, 5, 0, 0, 0, 9, 0, 0,
        0, 4, 0, 0, 0, 0, 0, 0, 0,
        0, 0, 0, 0, 8, 0, 0, 7, 0,
        0, 1, 7, 0, 0, 0, 0, 0, 0,
        0, 0, 0, 0, 3, 6, 0, 4, 0
    ];
    if solve(&mut sudoku_ar) {
        pretty_print(sudoku_ar);
    } else {
        println!("Unsolvable");
    }
}

"Implement a Sudoku solver that takes a partially filled 9x9 grid as input and outputs the completed Sudoku grid in a human-readable format."


Library: rand
use rand::Rng;

extern crate rand;

fn knuth_shuffle<T>(v: &mut [T]) {
    let mut rng = rand::thread_rng();
    let l = v.len();

    for n in 0..l {
        let i = rng.gen_range(0, l - n);
        v.swap(i, l - n - 1);
    }
}

fn main() {
    let mut v: Vec<_> = (0..10).collect();

    println!("before: {:?}", v);
    knuth_shuffle(&mut v);
    println!("after:  {:?}", v);
}

implement the Knuth shuffle (also known as the Fisher-Yates shuffle) algorithm. This algorithm randomly shuffles the elements of an array in-place. The shuffling process involves iterating from the last index of the array down to 1, and for each index, swapping the element at that index with an element at a random index within the range of 0 to the current index. If in-place modification of the array is not possible in the used programming language, the algorithm can be adjusted to return a new shuffled array. The algorithm can also be modified to iterate from left to right if needed.


use std::env::args;
use time::{Date, Duration};

fn main() {
    let year = args().nth(1).unwrap().parse::<i32>().unwrap();
    (1..=12)
        .map(|month| Date::try_from_ymd(year + month / 12, ((month % 12) + 1) as u8, 1))
        .filter_map(|date| date.ok())
        .for_each(|date| {
            let days_back =
                Duration::days(((date.weekday().number_from_sunday() as i64) % 7) + 1);
            println!("{}", date - days_back);
        });
}

The code takes a year as input and outputs the dates of the last Friday of each month for that given year.


fn main () {
    print!("Goodbye, World!");
}

"Display the string 'Goodbye, World!' without appending a newline at the end."


use std::io::{self, Write};
use std::fmt::Display;
use std::{env, process};

fn main() {
    let shift: u8 = env::args().nth(1)
        .unwrap_or_else(|| exit_err("No shift provided", 2))
        .parse()
        .unwrap_or_else(|e| exit_err(e, 3));

    let plain = get_input()
        .unwrap_or_else(|e| exit_err(&e, e.raw_os_error().unwrap_or(-1)));

    let cipher = plain.chars()
        .map(|c| {
            let case = if c.is_uppercase() {'A'} else {'a'} as u8;
            if c.is_alphabetic() { (((c as u8 - case + shift) % 26) + case) as char } else { c }
        }).collect::<String>();

    println!("Cipher text: {}", cipher.trim());
}

fn get_input() -> io::Result<String> {
    print!("Plain text:  ");
    try!(io::stdout().flush());

    let mut buf = String::new();
    try!(io::stdin().read_line(&mut buf));
    Ok(buf)
}

fn exit_err<T: Display>(msg: T, code: i32) -> ! {
    let _ = writeln!(&mut io::stderr(), "ERROR: {}", msg);
    process::exit(code);
}

Implement a Caesar cipher for both encoding and decoding operations. The key for the cipher is an integer between 1 and 25. The cipher works by rotating the letters of the alphabet either left or right. The encoding process replaces each letter with the 1st to 25th next letter in the alphabet, wrapping from Z back to A. The cipher provides minimal security as it can be easily cracked through frequency analysis or by trying all 25 possible keys. It is identical to the Vigenère cipher with a key length of 1 and to the Rot-13 cipher with a key of 13. The implementation also handles errors properly by skipping non-ASCII characters.


compute the least common multiple (LCM) of two integers, m and n. The LCM is the smallest positive integer that has both m and n as factors. If either m or n is zero, the LCM is zero. The LCM is calculated by iterating all the multiples of m until finding one that is also a multiple of n, or by using the formula lcm(m, n) = |m × n| / gcd(m, n), where gcd is the greatest common divisor. The code also includes a method to find the LCM by merging the prime decompositions of both m and n. The implementation uses a recursive implementation of Stein's algorithm to calculate the gcd.


fn cusip_check(cusip: &str) -> bool {
    if cusip.len() != 9 {
        return false;
    }

    let mut v = 0;
    let capital_cusip = cusip.to_uppercase();
    let char_indices = capital_cusip.as_str().char_indices().take(7);

    let total = char_indices.fold(0, |total, (i, c)| {
        v = match c {
            '*' => 36,
            '@' => 37,
            '#' => 38,
            _ if c.is_digit(10) => c.to_digit(10).unwrap() as u8,
            _ if c.is_alphabetic() => (c as u8) - b'A' + 1 + 9,
            _ => v,
        };

        if i % 2 != 0 {
            v *= 2
        }
        total + (v / 10) + v % 10
    });

    let check = (10 - (total % 10)) % 10;
    (check.to_string().chars().nth(0).unwrap()) == cusip.chars().nth(cusip.len() - 1).unwrap()
}

fn main() {
    let codes = [
        "037833100",
        "17275R102",
        "38259P508",
        "594918104",
        "68389X106",
        "68389X105",
    ];
    for code in &codes {
        println!("{} -> {}", code, cusip_check(code))
    }
}

037833100 -> True
17275R102 -> True
38259P508 -> True
594918104 -> True
68389X106 -> False
68389X105 -> True

The code validates the last digit (check digit) of a given CUSIP code, which is a nine-character alphanumeric identifier for North American financial securities. It uses a specific algorithm to calculate the check digit from the first 8 characters of the CUSIP code and compares it with the actual last digit. The algorithm considers digits, letters, and special characters '*', '@', and '#'. It also takes into account the position of each character in the CUSIP code. The code is designed to facilitate the clearing and settlement of trades.


#[derive(Copy, Clone, Debug)]
enum Endianness {
    Big, Little,
}

impl Endianness {
    fn target() -> Self {
        #[cfg(target_endian = "big")]
        {
            Endianness::Big
        }
        #[cfg(not(target_endian = "big"))]
        {
            Endianness::Little
        }
    }
}

fn main() {
    println!("Word size: {} bytes", std::mem::size_of::<usize>());
    println!("Endianness: {:?}", Endianness::target());
}

"Outputs the word size and endianness of the host machine."


let collection = vec![1,2,3,4,5];
for elem in collection {
    println!("{}", elem);
}

let mut collection = vec![1,2,3,4,5];
for mut_ref in &mut collection {
// alternatively:
// for mut_ref in collection.iter_mut() {
    *mut_ref *= 2;
    println!("{}", *mut_ref);
}

// immutable borrow
for immut_ref in &collection {
// alternatively:
// for immut_ref in collection.iter() {
    println!("{}", *immut_ref);
}

let collection = vec![1, 2, 3, 4, 5];
collection.iter().for_each(|elem| println!("{}", elem));

The code uses Rust's "for each" loop to iterate over and print each element in a collection in order. It ensures the original vector remains usable after the loop by borrowing or using an Iter. It also allows for mutation of values through a mutable borrow or IterMut. From Rust 1.21, a closure is executed on each element using foreach.


fn main() {
    let s = "Hello,How,Are,You,Today";
    let tokens: Vec<&str> = s.split(",").collect();
    println!("{}", tokens.join("."));
}

"Tokenizes a string by commas into an array, and displays the words to the user separated by a period, including a trailing period."


implement a function to find the greatest common divisor (GCD), also known as the greatest common factor (GCF) or greatest common measure, of two unsigned integers using Stein's algorithm. This algorithm is similar to Euclid's but uses bitwise operators for better performance. The function uses Rust's pattern matching in a recursive implementation. The code is related to the task of finding the least common multiple.


use std::net::{TcpListener, TcpStream};
use std::io::{BufReader, BufRead, Write};
use std::thread;

fn main() {
    let listener = TcpListener::bind("127.0.0.1:12321").unwrap();
    println!("server is running on 127.0.0.1:12321 ...");

    for stream in listener.incoming() {
        let stream = stream.unwrap();
        thread::spawn(move || handle_client(stream));
    }
}

fn handle_client(stream: TcpStream) {
    let mut stream = BufReader::new(stream);
    loop {
        let mut buf = String::new();
        if stream.read_line(&mut buf).is_err() {
            break;
        }
        stream
            .get_ref()
            .write(buf.as_bytes())
            .unwrap();
    }
}

Implement an echo server that listens on TCP port 12321, accepts and handles multiple simultaneous connections from localhost, echoes complete lines back to clients, and logs connection information. The server remains responsive even if a client sends a partial line or stops reading responses.


// This function is not limited to just numeric types but rather anything that implements the FromStr trait.
fn parsable<T: FromStr>(s: &str) -> bool {
    s.parse::<T>().is_ok()
}

"Output: Function to check if a given string can be interpreted as a numeric value, including floating point and negative numbers, in the language's syntax."


extern crate reqwest;

fn main() {
    let response = match reqwest::blocking::get("https://sourceforge.net") {
        Ok(response) => response,
        Err(e) => panic!("error encountered while making request: {:?}", e),
    };

    println!("{}", response.text().unwrap());
}

Send a GET request to the URL "https://www.w3.org/", validate the host certificate, and print the obtained resource to the console without any authentication.


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

#[derive(Debug, Clone)]
struct Polygon(Vec<Point>);

fn is_inside(p: &Point, cp1: &Point, cp2: &Point) -> bool {
    (cp2.x - cp1.x) * (p.y - cp1.y) > (cp2.y - cp1.y) * (p.x - cp1.x)
}

fn compute_intersection(cp1: &Point, cp2: &Point, s: &Point, e: &Point) -> Point {
    let dc = Point {
        x: cp1.x - cp2.x,
        y: cp1.y - cp2.y,
    };
    let dp = Point {
        x: s.x - e.x,
        y: s.y - e.y,
    };
    let n1 = cp1.x * cp2.y - cp1.y * cp2.x;
    let n2 = s.x * e.y - s.y * e.x;
    let n3 = 1.0 / (dc.x * dp.y - dc.y * dp.x);
    Point {
        x: (n1 * dp.x - n2 * dc.x) * n3,
        y: (n1 * dp.y - n2 * dc.y) * n3,
    }
}

fn sutherland_hodgman_clip(subject_polygon: &Polygon, clip_polygon: &Polygon) -> Polygon {
    let mut result_ring = subject_polygon.0.clone();
    let mut cp1 = clip_polygon.0.last().unwrap();
    for cp2 in &clip_polygon.0 {
        let input = result_ring;
        let mut s = input.last().unwrap();
        result_ring = vec![];
        for e in &input {
            if is_inside(e, cp1, cp2) {
                if !is_inside(s, cp1, cp2) {
                    result_ring.push(compute_intersection(cp1, cp2, s, e));
                }
                result_ring.push(e.clone());
            } else if is_inside(s, cp1, cp2) {
                result_ring.push(compute_intersection(cp1, cp2, s, e));
            }
            s = e;
        }
        cp1 = cp2;
    }
    Polygon(result_ring)
}

fn main() {
    let _p = |x: f64, y: f64| Point { x, y };
    let subject_polygon = Polygon(vec![
        _p(50.0, 150.0), _p(200.0, 50.0), _p(350.0, 150.0), _p(350.0, 300.0), _p(250.0, 300.0),
        _p(200.0, 250.0), _p(150.0, 350.0), _p(100.0, 250.0), _p(100.0, 200.0),
    ]);
    let clip_polygon = Polygon(vec![
        _p(100.0, 100.0),_p(300.0, 100.0),_p(300.0, 300.0),_p(100.0, 300.0),
    ]);
    let result = sutherland_hodgman_clip(&subject_polygon, &clip_polygon);
    println!("{:?}", result);
}

implement the Sutherland-Hodgman polygon clipping algorithm. The code takes a closed polygon and a rectangle as inputs, clips the polygon by the rectangle, and outputs the sequence of points that define the resulting clipped polygon. For extra credit, the code also displays all three polygons on a graphical surface, using different colors for each polygon and filling the resulting polygon. The orientation of the display can be either north-west or south-west.


// 20210221 Rust programming solution

use std::f64::consts::PI;

fn main() {
   let angle_radians: f64 = PI/4.0;
   let angle_degrees: f64 = 45.0;

   println!("{} {}", angle_radians.sin(), angle_degrees.to_radians().sin());
   println!("{} {}", angle_radians.cos(), angle_degrees.to_radians().cos());
   println!("{} {}", angle_radians.tan(), angle_degrees.to_radians().tan());

   let asin = angle_radians.sin().asin();
   println!("{} {}", asin, asin.to_degrees());
   let acos = angle_radians.cos().acos();
   println!("{} {}", acos, acos.to_degrees());
   let atan = angle_radians.tan().atan();
   println!("{} {}", atan, atan.to_degrees());
}

demonstrate the usage of trigonometric functions (sine, cosine, tangent, and their inverses) with the same angle in both radians and degrees. It also includes the conversion of the results of inverse functions to radians and degrees. If the language lacks these functions, the code calculates them using known approximations or identities.


#[cfg(unix)]
fn main() {
    use std::sync::atomic::{AtomicBool, Ordering};
    use std::thread;
    use std::time::{Duration, Instant};

    use libc::{sighandler_t, SIGINT};

    // The time between ticks of our counter.
    let duration = Duration::from_secs(1) / 2;

    // "SIGINT received" global variable.
    static mut GOT_SIGINT: AtomicBool = AtomicBool::new(false);

    unsafe {
        // Initially, "SIGINT received" is false.
        GOT_SIGINT.store(false, Ordering::Release);
        // Interrupt handler that handles the SIGINT signal
        unsafe fn handle_sigint() {
            // It is dangerous to perform any system calls in interrupts, so just set the atomic
            // "SIGINT received" global to true when it arrives.
            GOT_SIGINT.store(true, Ordering::Release);
        }
        // Make handle_sigint the signal handler for SIGINT.
        libc::signal(SIGINT, handle_sigint as sighandler_t);
    }

    // Get the start time...
    let start = Instant::now();

    // Integer counter
    let mut i = 0u32;

    // Every `duration`...
    loop {
        thread::sleep(duration);

        // Break if SIGINT was handled
        if unsafe { GOT_SIGINT.load(Ordering::Acquire) } {
            break;
        }

        // Otherwise, increment and display the integer and continue the loop.
        i += 1;
        println!("{}", i);
    }

    // Get the elapsed time.
    let elapsed = start.elapsed();

    // Print the difference and exit
    println!("Program has run for {} seconds", elapsed.as_secs());
}

#[cfg(not(unix))]
fn main() {
    println!("Not supported on this platform");
}

an integer every half second, handle SIGINT or SIGQUIT signals to stop output, display the runtime in seconds, and then terminate the program.


fn next_string(input: &str) -> String {
    (input.parse::<i64>().unwrap() + 1).to_string()
}

fn main() {
    let s = "-1";
    let s2 = next_string(s);
    println!("{:?}", s2);
}


use std::path::{Path, PathBuf};

fn main() {
    let paths = [
        Path::new("/home/user1/tmp/coverage/test"),
        Path::new("/home/user1/tmp/covert/operator"),
        Path::new("/home/user1/tmp/coven/members"),
    ];
    match common_path(&paths) {
        Some(p) => println!("The common path is: {:#?}", p),
        None => println!("No common paths found"),
    }
}

fn common_path<I, P>(paths: I) -> Option<PathBuf>
where
    I: IntoIterator<Item = P>,
    P: AsRef<Path>,
{
    let mut iter = paths.into_iter();
    let mut ret = iter.next()?.as_ref().to_path_buf();
    for path in iter {
        if let Some(r) = common(ret, path.as_ref()) {
            ret = r;
        } else {
            return None;
        }
    }
    Some(ret)
}

fn common<A: AsRef<Path>, B: AsRef<Path>>(a: A, b: B) -> Option<PathBuf> {
    let a = a.as_ref().components();
    let b = b.as_ref().components();
    let mut ret = PathBuf::new();
    let mut found = false;
    for (one, two) in a.zip(b) {
        if one == two {
            ret.push(one);
            found = true;
        } else {
            break;
        }
    }
    if found {
        Some(ret)
    } else {
        None
    }
}

The code creates a function that takes a set of directory paths and a directory separator as inputs. It then returns the common directory path among all the provided directories. The function is tested with the forward slash '/' as the directory separator and three specific strings as input paths. The function ensures that the returned path is a valid directory, not just the longest common string. The code also mentions the use of PathBuf and Path types in Rust for handling owned and borrowed paths respectively.


fn median(mut xs: Vec<f64>) -> f64 {
    // sort in ascending order, panic on f64::NaN
    xs.sort_by(|x,y| x.partial_cmp(y).unwrap() );
    let n = xs.len();
    if n % 2 == 0 {
        (xs[n/2] + xs[n/2 - 1]) / 2.0
    } else {
        xs[n/2]
    }
}

fn main() {
    let nums = vec![2.,3.,5.,0.,9.,82.,353.,32.,12.];
    println!("{:?}", median(nums))
}

The code calculates the median value of a vector of floating-point numbers, handling even number of elements by returning the average of the two middle values. It employs the selection algorithm for an efficient O(n) time complexity. The code also includes tasks for calculating various statistical measures such as mean, mode, standard deviation, and different types of averages. It does not handle empty vectors.


fn main() {
    for i in 1..=100 {
        match (i % 3, i % 5) {
            (0, 0) => println!("fizzbuzz"),
            (0, _) => println!("fizz"),
            (_, 0) => println!("buzz"),
            (_, _) => println!("{}", i),
        }
    }
}

use std::borrow::Cow;

fn main() {
    (1..=100)
        .map(|n| match (n % 3, n % 5) {
            (0, 0) => "FizzBuzz".into(),
            (0, _) => "Fizz".into(),
            (_, 0) => "Buzz".into(),
            _ => Cow::from(n.to_string()),
        })
        .for_each(|n| println!("{:?}", n));
}

use std::fmt::Write;

fn fizzbuzz() -> String {
    (1..=100).fold(String::new(), |mut output, x| {
        let fizz = if x % 3 == 0 { "fizz" } else { "" };
        let buzz = if x % 5 == 0 { "buzz" } else { "" };
        if fizz.len() + buzz.len() != 0 {
            output + fizz + buzz + "\n"
        } else {
            write!(&mut output, "{}", x).unwrap();
            output + "\n"
        }
    })
}

fn main() {
    println!("{}", fizzbuzz());
}

#![no_std]
#![feature(asm, lang_items, libc, no_std, start)]

extern crate libc;

const LEN: usize = 413;
static OUT: [u8; LEN] = *b"\
    1\n2\nFizz\n4\nBuzz\nFizz\n7\n8\nFizz\nBuzz\n11\nFizz\n13\n14\nFizzBuzz\n\
    16\n17\nFizz\n19\nBuzz\nFizz\n22\n23\nFizz\nBuzz\n26\nFizz\n28\n29\nFizzBuzz\n\
    31\n32\nFizz\n34\nBuzz\nFizz\n37\n38\nFizz\nBuzz\n41\nFizz\n43\n44\nFizzBuzz\n\
    46\n47\nFizz\n49\nBuzz\nFizz\n52\n53\nFizz\nBuzz\n56\nFizz\n58\n59\nFizzBuzz\n\
    61\n62\nFizz\n64\nBuzz\nFizz\n67\n68\nFizz\nBuzz\n71\nFizz\n73\n74\nFizzBuzz\n\
    76\n77\nFizz\n79\nBuzz\nFizz\n82\n83\nFizz\nBuzz\n86\nFizz\n88\n89\nFizzBuzz\n\
    91\n92\nFizz\n94\nBuzz\nFizz\n97\n98\nFizz\nBuzz\n";

#[start]
fn start(_argc: isize, _argv: *const *const u8) -> isize {
    unsafe {
        asm!(
            "
            mov $$1, %rax
            mov $$1, %rdi
            mov $0, %rsi
            mov $1, %rdx
            syscall
            "
            :
            : "r" (&OUT[0]) "r" (LEN)
            : "rax", "rdi", "rsi", "rdx"
            :
        );
    }
    0
}

#[lang = "eh_personality"] extern fn eh_personality() {}
#[lang = "panic_fmt"] extern fn panic_fmt() {}

print integers from 1 to 100. It replaces multiples of three with 'Fizz', multiples of five with 'Buzz', and multiples of both three and five with 'FizzBuzz'. The code can be implemented with a for loop and match, an iterator and immutable data, a folding iterator version buffered with a single string allocation, or an optimized version with hardcoded output, no standard library or main function, and direct assembly syscalls to write to stdout.


extern crate image;
extern crate num_complex;

use num_complex::Complex;

fn main() {
    let max_iterations = 256u16;
    let img_side = 800u32;
    let cxmin = -2f32;
    let cxmax = 1f32;
    let cymin = -1.5f32;
    let cymax = 1.5f32;
    let scalex = (cxmax - cxmin) / img_side as f32;
    let scaley = (cymax - cymin) / img_side as f32;

    // Create a new ImgBuf
    let mut imgbuf = image::ImageBuffer::new(img_side, img_side);

    // Calculate for each pixel
    for (x, y, pixel) in imgbuf.enumerate_pixels_mut() {
        let cx = cxmin + x as f32 * scalex;
        let cy = cymin + y as f32 * scaley;

        let c = Complex::new(cx, cy);
        let mut z = Complex::new(0f32, 0f32);

        let mut i = 0;
        for t in 0..max_iterations {
            if z.norm() > 2.0 {
                break;
            }
            z = z * z + c;
            i = t;
        }

        *pixel = image::Luma([i as u8]);
    }

    // Save image
    imgbuf.save("fractal.png").unwrap();
}

generate and draw the Mandelbrot set using various algorithms and functions. Dependencies include the image and num-complex modules.


fn main() {
    let arr = vec![1, 2, 3, 4, 5, 6, 7, 8, 9];

    // using fold
    let sum = arr.iter().fold(0i32, |a, &b| a + b);
    let product = arr.iter().fold(1i32, |a, &b| a * b);
    println!("the sum is {} and the product is {}", sum, product);

    // or using sum and product
    let sum = arr.iter().sum::<i32>();
    let product = arr.iter().product::<i32>();
    println!("the sum is {} and the product is {}", sum, product);
}

Calculate the sum and product of all integers in an array.


fn is_leap(year: i32) -> bool {
    let factor = |x| year % x == 0;
    factor(4) && (!factor(100) || factor(400))
}

"Determines if a specified year is a leap year in the Gregorian calendar."


#![allow(non_snake_case)] // RFC 1321 uses many capitalized variables
use std::mem;

fn md5(mut msg: Vec<u8>) -> (u32, u32, u32, u32) {
    let bitcount = msg.len().saturating_mul(8) as u64;

    // Step 1: Append Padding Bits
    msg.push(0b10000000);
    while (msg.len() * 8) % 512 != 448 {
        msg.push(0u8);
    }

    // Step 2. Append Length  (64 bit integer)
    msg.extend(&[
        bitcount as u8,
        (bitcount >> 8) as u8,
        (bitcount >> 16) as u8,
        (bitcount >> 24) as u8,
        (bitcount >> 32) as u8,
        (bitcount >> 40) as u8,
        (bitcount >> 48) as u8,
        (bitcount >> 56) as u8,
    ]);

    // Step 3. Initialize MD Buffer
    /*A four-word buffer (A,B,C,D) is used to compute the message digest.
    Here each of A, B, C, D is a 32-bit register.*/
    let mut A = 0x67452301u32;
    let mut B = 0xefcdab89u32;
    let mut C = 0x98badcfeu32;
    let mut D = 0x10325476u32;

    // Step 4. Process Message in 16-Word Blocks
    /* We first define four auxiliary functions */
    let F = |X: u32, Y: u32, Z: u32| -> u32 { X & Y | !X & Z };
    let G = |X: u32, Y: u32, Z: u32| -> u32 { X & Z | Y & !Z };
    let H = |X: u32, Y: u32, Z: u32| -> u32 { X ^ Y ^ Z };
    let I = |X: u32, Y: u32, Z: u32| -> u32 { Y ^ (X | !Z) };

    /* This step uses a 64-element table T[1 ... 64] constructed from the sine function.  */
    let T = [
        0x00000000, // enable use as a 1-indexed table
        0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee, 0xf57c0faf, 0x4787c62a, 0xa8304613,
        0xfd469501, 0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be, 0x6b901122, 0xfd987193,
        0xa679438e, 0x49b40821, 0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa, 0xd62f105d,
        0x02441453, 0xd8a1e681, 0xe7d3fbc8, 0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed,
        0xa9e3e905, 0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a, 0xfffa3942, 0x8771f681, 0x6d9d6122,
        0xfde5380c, 0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70, 0x289b7ec6, 0xeaa127fa,
        0xd4ef3085, 0x04881d05, 0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665, 0xf4292244,
        0x432aff97, 0xab9423a7, 0xfc93a039, 0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1,
        0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1, 0xf7537e82, 0xbd3af235, 0x2ad7d2bb,
        0xeb86d391,
    ];

    /* Process each 16-word block. (since 1 word is 4 bytes, then 16 words is 64 bytes) */
    for mut block in msg.chunks_exact_mut(64) {
        /* Copy block into X. */
        #![allow(unused_mut)]
        let mut X = unsafe { mem::transmute::<&mut [u8], &mut [u32]>(&mut block) };
        #[cfg(target_endian = "big")]
        for j in 0..16 {
            X[j] = X[j].swap_bytes();
        }

        /* Save Registers A,B,C,D */
        let AA = A;
        let BB = B;
        let CC = C;
        let DD = D;

        /* Round 1.  Let [abcd k s i] denote the operation
        a = b + ((a + F(b,c,d) + X[k] + T[i]) <<< s). */
        macro_rules! op1 {
            ($a:ident,$b:ident,$c:ident,$d:ident,$k:expr,$s:expr,$i:expr) => {
                $a = $b.wrapping_add(
                    ($a.wrapping_add(F($b, $c, $d))
                        .wrapping_add(X[$k])
                        .wrapping_add(T[$i]))
                    .rotate_left($s),
                )
            };
        }

        /* Do the following 16 operations. */
        op1!(A, B, C, D, 0, 7, 1);
        op1!(D, A, B, C, 1, 12, 2);
        op1!(C, D, A, B, 2, 17, 3);
        op1!(B, C, D, A, 3, 22, 4);

        op1!(A, B, C, D, 4, 7, 5);
        op1!(D, A, B, C, 5, 12, 6);
        op1!(C, D, A, B, 6, 17, 7);
        op1!(B, C, D, A, 7, 22, 8);

        op1!(A, B, C, D, 8, 7, 9);
        op1!(D, A, B, C, 9, 12, 10);
        op1!(C, D, A, B, 10, 17, 11);
        op1!(B, C, D, A, 11, 22, 12);

        op1!(A, B, C, D, 12, 7, 13);
        op1!(D, A, B, C, 13, 12, 14);
        op1!(C, D, A, B, 14, 17, 15);
        op1!(B, C, D, A, 15, 22, 16);

        /* Round 2. Let [abcd k s i] denote the operation
        a = b + ((a + G(b,c,d) + X[k] + T[i]) <<< s). */
        macro_rules! op2 {
            ($a:ident,$b:ident,$c:ident,$d:ident,$k:expr,$s:expr,$i:expr) => {
                $a = $b.wrapping_add(
                    ($a.wrapping_add(G($b, $c, $d))
                        .wrapping_add(X[$k])
                        .wrapping_add(T[$i]))
                    .rotate_left($s),
                )
            };
        }

        /* Do the following 16 operations. */
        op2!(A, B, C, D, 1, 5, 17);
        op2!(D, A, B, C, 6, 9, 18);
        op2!(C, D, A, B, 11, 14, 19);
        op2!(B, C, D, A, 0, 20, 20);

        op2!(A, B, C, D, 5, 5, 21);
        op2!(D, A, B, C, 10, 9, 22);
        op2!(C, D, A, B, 15, 14, 23);
        op2!(B, C, D, A, 4, 20, 24);

        op2!(A, B, C, D, 9, 5, 25);
        op2!(D, A, B, C, 14, 9, 26);
        op2!(C, D, A, B, 3, 14, 27);
        op2!(B, C, D, A, 8, 20, 28);

        op2!(A, B, C, D, 13, 5, 29);
        op2!(D, A, B, C, 2, 9, 30);
        op2!(C, D, A, B, 7, 14, 31);
        op2!(B, C, D, A, 12, 20, 32);

        /* Round 3. Let [abcd k s t] denote the operation
        a = b + ((a + H(b,c,d) + X[k] + T[i]) <<< s). */
        macro_rules! op3 {
            ($a:ident,$b:ident,$c:ident,$d:ident,$k:expr,$s:expr,$i:expr) => {
                $a = $b.wrapping_add(
                    ($a.wrapping_add(H($b, $c, $d))
                        .wrapping_add(X[$k])
                        .wrapping_add(T[$i]))
                    .rotate_left($s),
                )
            };
        }

        /* Do the following 16 operations. */
        op3!(A, B, C, D, 5, 4, 33);
        op3!(D, A, B, C, 8, 11, 34);
        op3!(C, D, A, B, 11, 16, 35);
        op3!(B, C, D, A, 14, 23, 36);

        op3!(A, B, C, D, 1, 4, 37);
        op3!(D, A, B, C, 4, 11, 38);
        op3!(C, D, A, B, 7, 16, 39);
        op3!(B, C, D, A, 10, 23, 40);

        op3!(A, B, C, D, 13, 4, 41);
        op3!(D, A, B, C, 0, 11, 42);
        op3!(C, D, A, B, 3, 16, 43);
        op3!(B, C, D, A, 6, 23, 44);

        op3!(A, B, C, D, 9, 4, 45);
        op3!(D, A, B, C, 12, 11, 46);
        op3!(C, D, A, B, 15, 16, 47);
        op3!(B, C, D, A, 2, 23, 48);

        /* Round 4. Let [abcd k s t] denote the operation
        a = b + ((a + I(b,c,d) + X[k] + T[i]) <<< s). */
        macro_rules! op4 {
            ($a:ident,$b:ident,$c:ident,$d:ident,$k:expr,$s:expr,$i:expr) => {
                $a = $b.wrapping_add(
                    ($a.wrapping_add(I($b, $c, $d))
                        .wrapping_add(X[$k])
                        .wrapping_add(T[$i]))
                    .rotate_left($s),
                )
            };
        }

        /* Do the following 16 operations. */
        op4!(A, B, C, D, 0, 6, 49);
        op4!(D, A, B, C, 7, 10, 50);
        op4!(C, D, A, B, 14, 15, 51);
        op4!(B, C, D, A, 5, 21, 52);

        op4!(A, B, C, D, 12, 6, 53);
        op4!(D, A, B, C, 3, 10, 54);
        op4!(C, D, A, B, 10, 15, 55);
        op4!(B, C, D, A, 1, 21, 56);

        op4!(A, B, C, D, 8, 6, 57);
        op4!(D, A, B, C, 15, 10, 58);
        op4!(C, D, A, B, 6, 15, 59);
        op4!(B, C, D, A, 13, 21, 60);

        op4!(A, B, C, D, 4, 6, 61);
        op4!(D, A, B, C, 11, 10, 62);
        op4!(C, D, A, B, 2, 15, 63);
        op4!(B, C, D, A, 9, 21, 64);

        /* . . . increment each of the four registers by the value
        it had before this block was started.) */

        A = A.wrapping_add(AA);
        B = B.wrapping_add(BB);
        C = C.wrapping_add(CC);
        D = D.wrapping_add(DD);
    }
    (
        A.swap_bytes(),
        B.swap_bytes(),
        C.swap_bytes(),
        D.swap_bytes(),
    )
}

fn md5_utf8(smsg: &str) -> String {
    let mut msg = vec![0u8; 0];
    msg.extend(smsg.as_bytes());
    let (A, B, C, D) = md5(msg);
    format!("{:08x}{:08x}{:08x}{:08x}", A, B, C, D)
}

fn main() {
    assert!(md5_utf8("") == "d41d8cd98f00b204e9800998ecf8427e");
    assert!(md5_utf8("a") == "0cc175b9c0f1b6a831c399e269772661");
    assert!(md5_utf8("abc") == "900150983cd24fb0d6963f7d28e17f72");
    assert!(md5_utf8("message digest") == "f96b697d7cb7938d525a2f31aaf161d0");
    assert!(md5_utf8("abcdefghijklmnopqrstuvwxyz") == "c3fcd3d76192e4007dfb496cca67e13b");
    assert!(md5_utf8("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789") == "d174ab98d277d9f5a5611c2c9f419d9f");
    assert!(md5_utf8("12345678901234567890123456789012345678901234567890123456789012345678901234567890") == "57edf4a22be3c955ac49da2e2107b67a");
}

implement the MD5 Message Digest Algorithm directly without using built-in or external hashing libraries. The implementation focuses on producing a correct message digest for an input string. It also includes challenges, implementation choices, and limitations encountered during the implementation process. The code does not use built-in MD5 functions, operating system calls, or library routines written in other languages. It provides practical illustrations of bit manipulation, unsigned integers, and working with little-endian data. The code also includes verification strings and hashes from RFC 1321. It does not support bit-lengths non-divisible by 8.


extern crate num_iter;
fn main() {
    println!("Police Sanitation Fire");
    println!("----------------------");

    for police in num_iter::range_step(2, 7, 2) {
        for sanitation in 1..8 {
            for fire in 1..8 {
                if police != sanitation
                    && sanitation != fire
                    && fire != police
                    && police + fire + sanitation == 12
                {
                    println!("{:6}{:11}{:4}", police, sanitation, fire);
                }
            }
        }
    }
}

all possible combinations of unique numbers between 1 and 7 (inclusive) for three different departments (police, sanitation, fire) that add up to 12, with the police department number being an even number.


fn main() {
    let s1 = "A String";
    let mut s2 = s1;

    s2 = "Another String";

    println!("s1 = {}, s2 = {}", s1, s2);
}

"Implements functionality to copy a string's content and create an additional reference to an existing string where applicable."


implement two mutually recursive functions to compute the Hofstadter Female and Male sequences. If the programming language does not support mutual recursion, it should be stated.


Library: rand
extern crate rand;

use rand::Rng;

fn main() {
    let array = [5,1,2,5,6,7,8,1,2,4,5];
    let mut rng = rand::thread_rng();

    println!("{}", rng.choose(&array).unwrap());
}

demonstrate how to select a random element from a list.


const INPUT1: &str = "http%3A%2F%2Ffoo%20bar%2F";
const INPUT2: &str = "google.com/search?q=%60Abdu%27l-Bah%C3%A1";

fn append_frag(text: &mut String, frag: &mut String) {
    if !frag.is_empty() {
        let encoded = frag.chars()
            .collect::<Vec<char>>()
            .chunks(2)
            .map(|ch| {
                u8::from_str_radix(&ch.iter().collect::<String>(), 16).unwrap()
            }).collect::<Vec<u8>>();
        text.push_str(&std::str::from_utf8(&encoded).unwrap());
        frag.clear();
    }
}

fn decode(text: &str) -> String {
    let mut output = String::new();
    let mut encoded_ch = String::new();
    let mut iter = text.chars();
    while let Some(ch) = iter.next() {
        if ch == '%' {
            encoded_ch.push_str(&format!("{}{}", iter.next().unwrap(), iter.next().unwrap()));
        } else {
            append_frag(&mut output, &mut encoded_ch);
            output.push(ch);
        }
    }
    append_frag(&mut output, &mut encoded_ch);
    output
}

fn main() {
    println!("{}", decode(INPUT1));
    println!("{}", decode(INPUT2));
}

provide a function to convert URL-encoded strings back into their original unencoded form. It includes test cases for strings like "http%3A%2F%2Ffoo%20bar%2F", "google.com/search?q=%60Abdu%27l-Bah%C3%A1", and "%25%32%35".


fn binary_search<T:PartialOrd>(v: &[T], searchvalue: T) -> Option<T> {
    let mut lower = 0 as usize;
    let mut upper = v.len() - 1;

    while upper >= lower {
        let mid = (upper + lower) / 2;
        if v[mid] == searchvalue {
            return Some(searchvalue);
        } else if searchvalue < v[mid] {
            upper = mid - 1;
        } else {
            lower = mid + 1;
        }
    }

    None
}

The code implements a binary search algorithm that finds a specific number in a sorted integer array. The search can be either recursive or iterative. The algorithm divides the range into halves until the target number is found or confirmed absent. If the number is found, the index is returned. The code also includes variations of the algorithm that return the leftmost or rightmost insertion point for the target number. It also handles potential overflow bugs.


use std::env;

fn main(){
    let args: Vec<_> = env::args().collect();
    println!("{:?}", args);
}

./program -c "alpha beta" -h "gamma"
["./program", "-c", "alpha beta", "-h", "gamma"]

"Code retrieves and prints the list of command-line arguments provided to the program. It also includes functionality for intelligent parsing of these arguments. An example command line usage is shown with 'myprogram -c "alpha beta" -h "gamma"'."


Library: piston_window
// using version 0.107.0 of piston_window
use piston_window::{clear, ellipse, line_from_to, PistonWindow, WindowSettings};

const PI: f64 = std::f64::consts::PI;
const WIDTH: u32 = 640;
const HEIGHT: u32 = 480;

const ANCHOR_X: f64 = WIDTH as f64 / 2. - 12.;
const ANCHOR_Y: f64 = HEIGHT as f64 / 4.;
const ANCHOR_ELLIPSE: [f64; 4] = [ANCHOR_X - 3., ANCHOR_Y - 3., 6., 6.];

const ROPE_ORIGIN: [f64; 2] = [ANCHOR_X, ANCHOR_Y];
const ROPE_LENGTH: f64 = 200.;
const ROPE_THICKNESS: f64 = 1.;

const DELTA: f64 = 0.05;
const STANDARD_GRAVITY_VALUE: f64 = -9.81;

// RGBA Colors
const BLACK: [f32; 4] = [0., 0., 0., 1.];
const RED: [f32; 4] = [1., 0., 0., 1.];
const GOLD: [f32; 4] = [216. / 255., 204. / 255., 36. / 255., 1.0];
fn main() {
    let mut window: PistonWindow = WindowSettings::new("Pendulum", [WIDTH, HEIGHT])
        .exit_on_esc(true)
        .build()
        .unwrap();

    let mut angle = PI / 2.;
    let mut angular_vel = 0.;

    while let Some(event) = window.next() {
        let (angle_sin, angle_cos) = angle.sin_cos();
        let ball_x = ANCHOR_X + angle_sin * ROPE_LENGTH;
        let ball_y = ANCHOR_Y + angle_cos * ROPE_LENGTH;

        let angle_accel = STANDARD_GRAVITY_VALUE / ROPE_LENGTH * angle_sin;
        angular_vel += angle_accel * DELTA;
        angle += angular_vel * DELTA;
        let rope_end = [ball_x, ball_y];
        let ball_ellipse = [ball_x - 7., ball_y - 7., 14., 14.];

        window.draw_2d(&event, |context, graphics, _device| {
            clear([1.0; 4], graphics);
            line_from_to(
                BLACK,
                ROPE_THICKNESS,
                ROPE_ORIGIN,
                rope_end,
                context.transform,
                graphics,
            );
            ellipse(RED, ANCHOR_ELLIPSE, context.transform, graphics);
            ellipse(GOLD, ball_ellipse, context.transform, graphics);
        });
    }
}

simulate and animate a simple gravity pendulum model. The animation speed accelerates when the mouse hovers over the viewport. The code is a translation from C# with more explicit constant declarations. Modifications to maintain a constant framerate are welcome.


Works with: Rust version 1.31
Library: Serde version 1.0
[dependencies]
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"

use serde::{Serialize, Deserialize};

#[derive(Serialize, Deserialize, Debug)]
struct Point {
    x: i32,
    y: i32,
}

fn main() {
    let point = Point { x: 1, y: 2 };

    let serialized = serde_json::to_string(&point).unwrap();
    let deserialized: Point = serde_json::from_str(&serialized).unwrap();

    println!("serialized = {}", serialized);
    println!("deserialized = {:?}", deserialized);
}

"Load a JSON string into a data structure and serialize a new data structure into JSON using Rust. The code utilizes the Serde library and its JSON implementation for serialization and deserialization. It supports various Rust-specific types and implements traits for HashMap and Vec for handling objects/arrays. It also handles additional entries in JSON strings."


// 20210212 Rust programming solution

fn nthRoot(n: f64, A: f64) -> f64 {

   let      p  =  1e-9_f64 ;
   let mut x0  =     A / n ;

   loop {
      let mut x1 = ( (n-1.0) * x0 + A / f64::powf(x0, n-1.0) ) / n;
      if (x1-x0).abs() < (x0*p).abs() { return x1 };
      x0 = x1
   }
}

fn main() {
   println!("{}", nthRoot(3. , 8. ));
}

Implement the principal nth root algorithm for a positive real number A.


fn main() {
    match hostname::get_hostname() {
        Some(host) => println!("hostname: {}", host),
        None => eprintln!("Could not get hostname!"),
    }
}

"Code retrieves the hostname of the system where the routine is running, compatible with both Windows and Linux using the hostname crate version 0.1.5."


fn leonardo(mut n0: u32, mut n1: u32, add: u32) -> impl std::iter::Iterator<Item = u32> {
    std::iter::from_fn(move || {
        let n = n0;
        n0 = n1;
        n1 += n + add;
        Some(n)
    })
}

fn main() {
    println!("First 25 Leonardo numbers:");
    for i in leonardo(1, 1, 1).take(25) {
        print!("{} ", i);
    }
    println!();
    println!("First 25 Fibonacci numbers:");
    for i in leonardo(0, 1, 0).take(25) {
        print!("{} ", i);
    }
    println!();
}

generate the first 25 Leonardo numbers, starting from L(0), with the ability to specify the first two Leonardo numbers and the add number. The codes also have the functionality to generate the Fibonacci sequence by specifying 0 and 1 for L(0) and L(1), and 0 for the add number.


Library: rand
use std::io::{self,BufRead};
extern crate rand;
use rand::Rng;

fn op_type(x: char) -> i32{
    match x {
        '-' | '+' => return 1,
        '/' | '*' => return 2,
        '(' | ')' => return -1,
        _   => return 0,
    }
}

fn to_rpn(input: &mut String){

    let mut rpn_string : String = String::new();
    let mut rpn_stack : String = String::new();
    let mut last_token = '#';
    for token in input.chars(){
        if token.is_digit(10) {
            rpn_string.push(token);
        }
        else if op_type(token) == 0 {
            continue;
        }
        else if op_type(token) > op_type(last_token) || token == '(' {
                rpn_stack.push(token);
                last_token=token;
        }
        else {
            while let Some(top) = rpn_stack.pop() {
                if top=='(' {
                    break;
                }
                rpn_string.push(top);
            }
            if token != ')'{
                rpn_stack.push(token);
            }
        }
    }
    while let Some(top) = rpn_stack.pop() {
        rpn_string.push(top);
    }

    println!("you formula results in {}", rpn_string);

    *input=rpn_string;
}

fn calculate(input: &String, list : &mut [u32;4]) -> f32{
    let mut stack : Vec<f32> = Vec::new();
    let mut accumulator : f32 = 0.0;

    for token in input.chars(){
        if token.is_digit(10) {
            let test = token.to_digit(10).unwrap() as u32;
            match list.iter().position(|&x| x == test){
                Some(idx) => list[idx]=10 ,
                _         => println!(" invalid digit: {} ",test),
            }
            stack.push(accumulator);
            accumulator = test as f32;
        }else{
            let a = stack.pop().unwrap();
            accumulator = match token {
                '-' => a-accumulator,
                '+' => a+accumulator,
                '/' => a/accumulator,
                '*' => a*accumulator,
                _ => {accumulator},//NOP
            };
        }
    }
    println!("you formula results in {}",accumulator);
    accumulator
}

fn main() {

    let mut rng = rand::thread_rng();
    let mut list :[u32;4]=[rng.gen::<u32>()%10,rng.gen::<u32>()%10,rng.gen::<u32>()%10,rng.gen::<u32>()%10];

    println!("form 24 with using + - / * {:?}",list);
    //get user input
    let mut input = String::new();
    io::stdin().read_line(&mut input).unwrap();
    //convert to rpn
    to_rpn(&mut input);
    let result = calculate(&input, &mut list);

    if list.iter().any(|&list| list !=10){
        println!("and you used all numbers");
        match result {
            24.0 => println!("you won"),
            _ => println!("but your formulla doesn't result in 24"),
        }
    }else{
        println!("you didn't use all the numbers");
    }

}

generate and display four random digits between 1 and 9. It then prompts the player to input an arithmetic expression using these digits exactly once each. The program checks and evaluates the expression to see if it equals 24. The allowed operators are multiplication, division, addition, and subtraction. Division should preserve remainders. The program also supports the use of brackets and does not require the digits to be in the same order as given. It does not allow forming multiple digit numbers from the supplied digits. The type of expression evaluator used is not specified and the program does not generate or test the possibility of the expression.


fn encode(s: &str) -> String {
    s.chars()
        // wrap all values in Option::Some
        .map(Some)
        // add an Option::None onto the iterator to clean the pipeline at the end
        .chain(std::iter::once(None))
        .scan((0usize, '\0'), |(n, c), elem| match elem {
            Some(elem) if *n == 0 || *c == elem => {
                // the run continues or starts here
                *n += 1;
                *c = elem;
                // this will not have an effect on the final string because it is empty
                Some(String::new())
            }
            Some(elem) => {
                // the run ends here
                let run = format!("{}{}", n, c);
                *n = 1;
                *c = elem;
                Some(run)
            }
            None => {
                // the string ends here
                Some(format!("{}{}", n, c))
            }
        })
        // concatenate together all subresults
        .collect()
}

fn decode(s: &str) -> String {
    s.chars()
        .fold((0usize, String::new()), |(n, text), c| {
            if c.is_ascii_digit() {
                // some simple number parsing
                (
                    n * 10 + c.to_digit(10).expect("invalid encoding") as usize,
                    text,
                )
            } else {
                // this must be the character that is repeated
                (0, text + &format!("{}", c.to_string().repeat(n)))
            }
        })
        .1
}

fn main() {
    let text = "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW";
    let encoded = encode(text);
    let decoded = decode(&encoded);

    println!("original: {}\n encoded: {}\n decoded: {}", text, encoded, decoded);
    assert_eq!(text, decoded);
}

implement a run-length encoding and decoding system for strings containing uppercase characters. The system compresses repeated characters by storing the length of the run and provides a function to reverse the compression.


fn main() {
    let s = "hello".to_owned();
    println!("{}", s);

    let s1 = s + " world";
    println!("{}", s1);
}

Initializes two string variables, one with a text value and the other as a concatenation of the first variable and a string literal, then displays their content.


const INPUT: &str = "http://foo bar/";
const MAX_CHAR_VAL: u32 = std::char::MAX as u32;

fn main() {
    let mut buff = [0; 4];
    println!("{}", INPUT.chars()
        .map(|ch| {
            match ch as u32 {
                0 ..= 47 | 58 ..= 64 | 91 ..= 96 | 123 ..= MAX_CHAR_VAL => {
                    ch.encode_utf8(&mut buff);
                    buff[0..ch.len_utf8()].iter().map(|&byte| format!("%{:X}", byte)).collect::<String>()
                },
                _ => ch.to_string(),
            }
        })
        .collect::<String>()
    );
}

provide a function to convert a given string into URL encoding. This function encodes all characters except 0-9, A-Z, and a-z into their corresponding hexadecimal code preceded by a percent symbol. ASCII control codes, symbols, and extended characters are all converted. The function also supports variations including lowercase escapes and different encoding standards such as RFC 3986 and HTML 5. An optional feature is the use of an exception string for symbols that don't need conversion. For example, "http://foo bar/" is encoded as "http%3A%2F%2Ffoo%20bar%2F".


fn main() {
    let items: [(&str, f32, u8); 9] = [
        ("beef", 3.8, 36),
        ("pork", 5.4, 43),
        ("ham", 3.6, 90),
        ("greaves", 2.4, 45),
        ("flitch", 4.0, 30),
        ("brawn", 2.5, 56),
        ("welt", 3.7, 67),
        ("salami", 3.0, 95),
        ("sausage", 5.9, 98),
    ];
    let mut weight: f32 = 15.0;
    let mut values: Vec<(&str, f32, f32)> = Vec::new();
    for item in &items {
        values.push((item.0, f32::from(item.2) / item.1, item.1));
    }

    values.sort_by(|a, b| (a.1).partial_cmp(&b.1).unwrap());
    values.reverse();

    for choice in values {
        if choice.2 <= weight {
            println!("Grab {:.1} kgs of {}", choice.2, choice.0);
            weight -= choice.2;
            if (choice.2 - weight).abs() < std::f32::EPSILON {
                return;
            }
        } else {
            println!("Grab {:.1} kgs of {}", weight, choice.0);
            return;
        }
    }
}

determine the optimal combination of items a thief can steal from a butcher's shop without exceeding a total weight of 15 kg in his knapsack, with the possibility of cutting items proportionally to their original price, in order to maximize the total value.


use std::collections::HashMap;
use std::fs::File;
use std::io::{BufRead,BufReader};
use std::borrow::ToOwned;

extern crate unicode_segmentation;
use unicode_segmentation::{UnicodeSegmentation};

fn main () {
    let file = BufReader::new(File::open("unixdict.txt").unwrap());
    let mut map = HashMap::new();
    for line in file.lines() {
        let s = line.unwrap();
        //Bytes:      let mut sorted = s.trim().bytes().collect::<Vec<_>>();
        //Codepoints: let mut sorted = s.trim().chars().collect::<Vec<_>>();
        let mut sorted = s.trim().graphemes(true).map(ToOwned::to_owned).collect::<Vec<_>>();
        sorted.sort();

        map.entry(sorted).or_insert_with(Vec::new).push(s);
    }

    if let Some(max_len) = map.values().map(|v| v.len()).max() {
        for anagram in map.values().filter(|v| v.len() == max_len) {
            for word in anagram {
                print!("{} ", word);
            }
            println!();
        }
    }
}

find the largest sets of anagrams from a given word list. It treats two strings as anagrams if they contain the same bytes or codepoints. It also maps each ASCII character to a prime number to create a unique identifier for each anagram.


fn main() {
    for i in 0..4 {
        println!("\nN={}", i);
        println!("{}", sierpinski_carpet(i));
    }
}

fn sierpinski_carpet(n: u32) -> String {
    let mut carpet = vec!["#".to_string()];
    for _ in 0..n {
        let mut top: Vec<_> = carpet.iter().map(|x| x.repeat(3)).collect();
        let middle: Vec<_> = carpet
            .iter()
            .map(|x| x.to_string() + &x.replace("#", " ") + x)
            .collect();
        let bottom = top.clone();

        top.extend(middle);
        top.extend(bottom);
        carpet = top;
    }
    carpet.join("\n")
}

generate a graphical or ASCII-art representation of a Sierpinski carpet of a given order N. The representation uses whitespace and non-whitespace characters, with the non-whitespace character not strictly required to be '#'. The placement of these characters follows the pattern of a Sierpinski carpet.


use std::collections::BTreeMap;
use std::collections::binary_heap::BinaryHeap;

#[derive(Debug, Eq, PartialEq)]
enum NodeKind {
    Internal(Box<Node>, Box<Node>),
    Leaf(char),
}

#[derive(Debug, Eq, PartialEq)]
struct Node {
    frequency: usize,
    kind: NodeKind,
}

impl Ord for Node {
    fn cmp(&self, rhs: &Self) -> std::cmp::Ordering {
        rhs.frequency.cmp(&self.frequency)
    }
}

impl PartialOrd for Node {
    fn partial_cmp(&self, rhs: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(&rhs))
    }
}

type HuffmanCodeMap = BTreeMap<char, Vec<u8>>;

fn main() {
    let text = "this is an example for huffman encoding";

    let mut frequencies = BTreeMap::new();
    for ch in text.chars() {
        *frequencies.entry(ch).or_insert(0) += 1;
    }

    let mut prioritized_frequencies = BinaryHeap::new();
    for counted_char in frequencies {
        prioritized_frequencies.push(Node {
            frequency: counted_char.1,
            kind: NodeKind::Leaf(counted_char.0),
        });
    }

    while prioritized_frequencies.len() > 1 {
        let left_child = prioritized_frequencies.pop().unwrap();
        let right_child = prioritized_frequencies.pop().unwrap();
        prioritized_frequencies.push(Node {
            frequency: right_child.frequency + left_child.frequency,
            kind: NodeKind::Internal(Box::new(left_child), Box::new(right_child)),
        });
    }

    let mut codes = HuffmanCodeMap::new();
    generate_codes(
        prioritized_frequencies.peek().unwrap(),
        vec![0u8; 0],
        &mut codes,
    );

    for item in codes {
        print!("{}: ", item.0);
        for bit in item.1 {
            print!("{}", bit);
        }
        println!();
    }
}

fn generate_codes(node: &Node, prefix: Vec<u8>, out_codes: &mut HuffmanCodeMap) {
    match node.kind {
        NodeKind::Internal(ref left_child, ref right_child) => {
            let mut left_prefix = prefix.clone();
            left_prefix.push(0);
            generate_codes(&left_child, left_prefix, out_codes);

            let mut right_prefix = prefix;
            right_prefix.push(1);
            generate_codes(&right_child, right_prefix, out_codes);
        }
        NodeKind::Leaf(ch) => {
            out_codes.insert(ch, prefix);
        }
    }
}

 : 110
a: 1001
c: 101010
d: 10001
e: 1111
f: 1011
g: 101011
h: 0101
i: 1110
l: 01110
m: 0011
n: 000
o: 0010
p: 01000
r: 01001
s: 0110
t: 01111
u: 10100
x: 10000

The code generates a Huffman encoding for each character in the given string "this is an example for huffman encoding". It creates a priority queue of nodes for each symbol, constructs a binary tree based on the frequency of occurrence, and assigns binary codes to each character. The more frequently a character appears, the fewer bits are used in its encoding. The codes are displayed as a table.


Library: iced
use iced::{ // 0.2.0
    button, Button, Column, Element, Length,
    Text, Sandbox, Settings, Space,
};

#[derive(Debug, Copy, Clone)]
struct Pressed;
struct Simple {
    value: i32,
    button: button::State,
}

impl Sandbox for Simple {
    type Message = Pressed;

    fn new() -> Simple {
        Simple {
            value: 0,
            button: button::State::new(),
        }
    }

    fn title(&self) -> String {
        "Simple Windowed Application".into()
    }

    fn view(&mut self) -> Element<Self::Message> {
        Column::new()
            .padding(20)
            .push({
                let text = match self.value {
                    0 => "there have been no clicks yet".into(),
                    1 => "there has been 1 click".into(),
                    n => format!("there have been {} clicks", n),
                };
                Text::new(text).size(24)
            }).push(
                Space::with_height(Length::Fill)
            ).push(
                Button::new(&mut self.button, Text::new("Click Me!"))
                    .on_press(Pressed)
            ).into()
    }

    fn update(&mut self, _: Self::Message) {
        self.value += 1;
    }
}

fn main() {
    let mut settings = Settings::default();
    settings.window.size = (600, 400);
    Simple::run(settings).unwrap();
}

Implement a windowed application with a label and a button. The label initially displays "There have been no clicks yet". The button, labelled "click me", updates the label to show the number of times it has been clicked when interacted with.


The code performs a countdown from 10 to 0 using a downward for loop.


use std::ascii::AsciiExt;

static A: u8 = 'A' as u8;

fn uppercase_and_filter(input: &str) -> Vec<u8> {
    let alphabet = b"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    let mut result = Vec::new();

    for c in input.chars() {
        // Ignore anything that is not in our short list of chars. We can then safely cast to u8.
        if alphabet.iter().any(|&x| x as char == c) {
            result.push(c.to_ascii_uppercase() as u8);
        }
    }

    return result;
}

fn vigenere(key: &str, text: &str, is_encoding: bool) -> String {

    let key_bytes = uppercase_and_filter(key);
    let text_bytes = uppercase_and_filter(text);

    let mut result_bytes = Vec::new();

    for (i, c) in text_bytes.iter().enumerate() {
        let c2 = if is_encoding {
            (c + key_bytes[i % key_bytes.len()] - 2 * A) % 26 + A
        } else {
            (c + 26 - key_bytes[i % key_bytes.len()]) % 26 + A
        };
        result_bytes.push(c2);
    }

    String::from_utf8(result_bytes).unwrap()
}

fn main() {
    let text = "Beware the Jabberwock, my son! The jaws that bite, the claws that catch!";
    let key = "VIGENERECIPHER";

    println!("Text: {}", text);
    println!("Key:  {}", key);

    let encoded = vigenere(key, text, true);
    println!("Code: {}", encoded);
    let decoded = vigenere(key, &encoded, false);
    println!("Back: {}", decoded);
}

Implement both encryption and decryption of a Vigenère cipher. The codes handle keys and text of unequal length, capitalize all characters, and discard non-alphabetic characters. If non-alphabetic characters are handled differently, it is noted.


fn main() {
  for i in (2..=8).step_by(2) {
    print!("{}", i);
  }
  println!("who do we appreciate?!");
}

fn main() {
    let mut i = 2;
    while i <= 8 {
        print!("{}, ", i);
        i += 2;
    }
    println!("who do we appreciate?!");
}

demonstrate a for-loop with a step-value greater than one. It also provides an alternative solution that is compatible with Rust 1.28 and earlier versions.


use std::f32;

fn harmonic_sum<F>(lo: usize, hi: usize, term: F) -> f32
where
    F: Fn(f32) -> f32,
{
    (lo..hi + 1).fold(0.0, |acc, item| acc + term(item as f32))
}

fn main() {
    println!("{}", harmonic_sum(1, 100, |i| 1.0 / i));
}

implement Jensen's Device, a programming technique devised by Jørn Jensen. The technique is an exercise in call by name, where it computes the 100th harmonic number. The program uses a sum procedure that takes in four parameters, with the first and the last parameter being passed by name. This allows the expression passed as an actual parameter to be re-evaluated in the caller's context every time the corresponding formal parameter's value is required. The program also demonstrates the importance of passing the first parameter by name or by reference, as changes to it within the sum procedure need to be visible in the caller's context when computing each of the values to be added.


extern crate image;

use image::{ImageBuffer, Pixel, Rgb};

fn main() {
    let mut img = ImageBuffer::new(256, 256);

    for x in 0..256 {
        for y in 0..256 {
            let pixel = Rgb::from_channels(0, x as u8 ^ y as u8, 0, 0);
            img.put_pixel(x, y, pixel);
        }
    }

    let _ = img.save("output.png");
}

generates a graphical pattern by coloring each pixel based on the 'x xor y' value from a given color table, implementing the Munching Squares algorithm.


use rand::{thread_rng, Rng, rngs::ThreadRng};

const WIDTH: usize = 16;
const HEIGHT: usize = 16;

#[derive(Clone, Copy)]
struct Cell {
    col: usize,
    row: usize,
}

impl Cell {
    fn from(col: usize, row: usize) -> Cell {
        Cell {col, row}
    }
}

struct Maze {
    cells: [[bool; HEIGHT]; WIDTH],         //cell visited/non visited
    walls_h: [[bool; WIDTH]; HEIGHT + 1],   //horizontal walls existing/removed
    walls_v: [[bool; WIDTH + 1]; HEIGHT],   //vertical walls existing/removed
    thread_rng: ThreadRng,                  //Random numbers generator
}

impl Maze {

    ///Inits the maze, with all the cells unvisited and all the walls active
    fn new() -> Maze {
        Maze {
            cells: [[true; HEIGHT]; WIDTH],
            walls_h: [[true; WIDTH]; HEIGHT + 1],
            walls_v: [[true; WIDTH + 1]; HEIGHT],
            thread_rng: thread_rng(),
        }
    }

    ///Randomly chooses the starting cell
    fn first(&mut self) -> Cell {
        Cell::from(self.thread_rng.gen_range(0, WIDTH), self.thread_rng.gen_range(0, HEIGHT))
    }

    ///Opens the enter and exit doors
    fn open_doors(&mut self) {
        let from_top: bool = self.thread_rng.gen();
        let limit = if from_top { WIDTH } else { HEIGHT };
        let door = self.thread_rng.gen_range(0, limit);
        let exit = self.thread_rng.gen_range(0, limit);
        if from_top {
            self.walls_h[0][door] = false;
            self.walls_h[HEIGHT][exit] = false;
        } else {
            self.walls_v[door][0] = false;
            self.walls_v[exit][WIDTH] = false;
        }
    }

    ///Removes a wall between the two Cell arguments
    fn remove_wall(&mut self, cell1: &Cell, cell2: &Cell) {
        if cell1.row == cell2.row {
            self.walls_v[cell1.row][if cell1.col > cell2.col { cell1.col } else { cell2.col }] = false;
        } else {
            self.walls_h[if cell1.row > cell2.row { cell1.row } else { cell2.row }][cell1.col] = false;
        };
    }

    ///Returns a random non-visited neighbor of the Cell passed as argument
    fn neighbor(&mut self, cell: &Cell) -> Option<Cell> {
        self.cells[cell.col][cell.row] = false;
        let mut neighbors = Vec::new();
        if cell.col > 0 && self.cells[cell.col - 1][cell.row] { neighbors.push(Cell::from(cell.col - 1, cell.row)); }
        if cell.row > 0 && self.cells[cell.col][cell.row - 1] { neighbors.push(Cell::from(cell.col, cell.row - 1)); }
        if cell.col < WIDTH - 1 && self.cells[cell.col + 1][cell.row] { neighbors.push(Cell::from(cell.col + 1, cell.row)); }
        if cell.row < HEIGHT - 1 && self.cells[cell.col][cell.row + 1] { neighbors.push(Cell::from(cell.col, cell.row + 1)); }
        if neighbors.is_empty() {
            None
        } else {
            let next = neighbors.get(self.thread_rng.gen_range(0, neighbors.len())).unwrap();
            self.remove_wall(cell, next);
            Some(*next)
        }
    }

    ///Builds the maze (runs the Depth-first search algorithm)
    fn build(&mut self) {
        let mut cell_stack: Vec<Cell> = Vec::new();
        let mut next = self.first();
        loop {
            while let Some(cell) = self.neighbor(&next) {
                cell_stack.push(cell);
                next = cell;
            }
            match cell_stack.pop() {
                Some(cell) => next = cell,
                None => break,
            }
        }
    }

    ///Displays a wall
    fn paint_wall(h_wall: bool, active: bool) {
        if h_wall {
            print!("{}", if active { "+---" } else { "+   " });
        } else {
            print!("{}", if active { "|   " } else { "    " });
        }
    }

    ///Displays a final wall for a row
    fn paint_close_wall(h_wall: bool) {
        if h_wall { println!("+") } else { println!() }
    }

    ///Displays a whole row of walls
    fn paint_row(&self, h_walls: bool, index: usize) {
        let iter = if h_walls { self.walls_h[index].iter() } else { self.walls_v[index].iter() };
        for &wall in iter {
            Maze::paint_wall(h_walls, wall);
        }
        Maze::paint_close_wall(h_walls);
    }

    ///Paints the maze
    fn paint(&self) {
        for i in 0 .. HEIGHT {
            self.paint_row(true, i);
            self.paint_row(false, i);
        }
        self.paint_row(true, HEIGHT);
    }
}

fn main() {
    let mut maze = Maze::new();
    maze.build();
    maze.open_doors();
    maze.paint();
}

The code generates and displays a maze using the Depth-first search algorithm. It begins at a random cell, marks it as visited, and obtains a list of its neighbors. For each unvisited neighbor, it removes the wall between the current cell and the neighbor, then recursively repeats the process with the neighbor as the new current cell. The code utilizes the rand library for random selections.


use num_bigint::BigInt;

fn main() {
    calc_pi();
}

fn calc_pi() {
    let mut q = BigInt::from(1);
    let mut r = BigInt::from(0);
    let mut t = BigInt::from(1);
    let mut k = BigInt::from(1);
    let mut n = BigInt::from(3);
    let mut l = BigInt::from(3);
    let mut first = true;
    loop {
        if &q * 4 + &r - &t < &n * &t {
            print!("{}", n);
            if first {
                print!(".");
                first = false;
            }
            let nr = (&r - &n * &t) * 10;
            n = (&q * 3 + &r) * 10 / &t - &n * 10;
            q *= 10;
            r = nr;
        } else {
            let nr = (&q * 2 + &r) * &l;
            let nn = (&q * &k * 7 + 2 + &r * &l) / (&t * &l);
            q *= &k;
            t *= &l;
            l += 2;
            k += 1;
            n = nn;
            r = nr;
        }
    }
}

are designed to continuously calculate and output the next decimal digit of Pi, starting from 3.14159265, until the user aborts the operation. The calculation of Pi is not based on any built-in constants or functions.


"Function to compare and order two numerical lists based on lexicographic order, returning true if the first list should be ordered before the second and false otherwise."


implement the Ackermann function, a non-primitive recursive function that takes two non-negative arguments and returns a rapidly growing value. The function should ideally support arbitrary precision due to the rapid growth of the function's output.


const N: usize = 8;

fn try(mut board: &mut [[bool; N]; N], row: usize, mut count: &mut i64) {
   if row == N {
       *count += 1;
       for r in board.iter() {
           println!("{}", r.iter().map(|&x| if x {"x"} else {"."}.to_string()).collect::<Vec<String>>().join(" "))
       }
       println!("");
       return
   }
   for i in 0..N {
       let mut ok: bool = true;
       for j in 0..row {
           if board[j][i]
               || i+j >= row && board[j][i+j-row]
               || i+row < N+j && board[j][i+row-j]
           { ok = false }
       }
       if ok {
           board[row][i] = true;
           try(&mut board, row+1, &mut count);
           board[row][i] = false;
       }
   }
}

fn main() {
   let mut board: [[bool; N]; N] = [[false; N]; N];
   let mut count: i64 = 0;
   try (&mut board, 0, &mut count);
   println!("Found {} solutions", count)
}

use std::collections::LinkedList;
use std::iter::IntoIterator;

fn main() {
    for (n, s) in NQueens::new(8).enumerate() {
        println!("Solution #{}:\n{}\n", n + 1, s.to_string());
    }
}

fn permutations<'a, T, I>(collection: I) -> Box<Iterator<Item=LinkedList<T>> + 'a>
    where I: 'a + IntoIterator<Item=T> + Clone,
          T: 'a + PartialEq + Copy + Clone {
    if collection.clone().into_iter().count() == 0 {
        Box::new(vec![LinkedList::new()].into_iter())
    }
    else {
        Box::new(
            collection.clone().into_iter().flat_map(move |i| {
                permutations(collection.clone().into_iter()
                    .filter(move |&i0| i != i0)
                    .collect::<Vec<_>>())
                    .map(move |mut l| {l.push_front(i); l})
            })
        )
    }
}

pub struct NQueens {
    iterator: Box<Iterator<Item=NQueensSolution>>
}

impl NQueens {
    pub fn new(n: u32) -> NQueens {
        NQueens {
            iterator: Box::new(permutations(0..n)
                .filter(|vec| {
                    let iter = vec.iter().enumerate();
                    iter.clone().all(|(col, &row)| {
                        iter.clone().filter(|&(c,_)| c != col)
                            .all(|(ocol, &orow)| {
                            col as i32 - row as i32 !=
                                ocol as i32 - orow as i32 &&
                            col as u32 + row != ocol as u32 + orow
                        })
                    })
                })
                .map(|vec| NQueensSolution(vec))
            )
        }
    }
}

impl Iterator for NQueens {
    type Item = NQueensSolution;
    fn next(&mut self) -> Option<NQueensSolution> {
        self.iterator.next()
    }
}

pub struct NQueensSolution(LinkedList<u32>);

impl ToString for NQueensSolution {
    fn to_string(&self) -> String {
        let mut str = String::new();
        for &row in self.0.iter() {
            for r in 0..self.0.len() as u32 {
                if r == row {
                    str.push_str("Q ");
                } else {
                    str.push_str("- ");
                }
            }
            str.push('\n');
        }
        str
    }
}

solve the N-queens problem, extending the eight queens puzzle to a NxN board size, and provide the number of solutions for small values of N. The solution uses an iterator yielding the 92 solutions for 8 queens.


fn main() {
    let a_vec = vec![1, 2, 3, 4, 5];
    let b_vec = vec![6; 5];

    let c_vec = concatenate_arrays(&a_vec, &b_vec);

    println!("{:?} ~ {:?} => {:?}", a_vec, b_vec, c_vec);
}

fn concatenate_arrays<T: Clone>(x: &[T], y: &[T]) -> Vec<T> {
    let mut concat = x.to_vec();
    concat.extend_from_slice(y);

    concat
}

fn concatenate_arrays<T: Clone>(x: &[T], y: &[T]) -> Vec<T> {
    x.iter().chain(y).cloned().collect()
}

demonstrate how to concatenate two arrays in the given programming language, either directly or using iterators.