completed hex_color challenge
This commit is contained in:
parent
db882dd5dc
commit
854fdfb6b1
7
rust/hex_colors/Cargo.toml
Normal file
7
rust/hex_colors/Cargo.toml
Normal file
@ -0,0 +1,7 @@
|
||||
[package]
|
||||
name = "hex_colors"
|
||||
version = "0.1.0"
|
||||
authors = ["nkoch001 <nilskoch94@gmail.com>"]
|
||||
edition = "2018"
|
||||
|
||||
[dependencies]
|
51
rust/hex_colors/src/main.rs
Normal file
51
rust/hex_colors/src/main.rs
Normal file
@ -0,0 +1,51 @@
|
||||
// THIS IS PART OF REDDITS DAILY PROGRAMMING CHALLENGES
|
||||
// this programm generates a hex-color-string from decimal input values
|
||||
//
|
||||
|
||||
// converts a 3-tuple of 8 bit decimals to a color-string of the Format "#FF00EE"
|
||||
fn hexcolor(r: u8, g: u8, b: u8) -> String {
|
||||
let result = format!("#{0:03$X}{1:03$X}{2:03$X}", r, g, b, 2);
|
||||
result
|
||||
}
|
||||
|
||||
// Averages two u8 values
|
||||
fn mix(x: u8, y: u8) -> u8 {
|
||||
let sum: u16 = u16::from(x) + u16::from(y);
|
||||
(sum / 2) as u8
|
||||
}
|
||||
|
||||
// blends two decimal colors
|
||||
fn blend_int(x: (u8, u8, u8), y: (u8, u8, u8)) -> String {
|
||||
hexcolor(mix(x.0, y.0), mix(x.1, y.1), mix(x.2, y.2))
|
||||
}
|
||||
|
||||
// parses hex to uint
|
||||
fn parse_hex_to_uint(x: String) -> u8 {
|
||||
u8::from_str_radix(&x, 16).unwrap()
|
||||
}
|
||||
|
||||
// parses color string to decimal values
|
||||
fn parse_hexstring(x: String) -> (u8, u8, u8) {
|
||||
let y = x.trim_start_matches("#").to_string();
|
||||
(
|
||||
parse_hex_to_uint(y[0..2].to_string()),
|
||||
parse_hex_to_uint(y[2..4].to_string()),
|
||||
parse_hex_to_uint(y[4..6].to_string()),
|
||||
)
|
||||
}
|
||||
|
||||
// blends two color strings
|
||||
fn blend(x: (String, String)) -> String {
|
||||
let color_1 = parse_hexstring(x.0);
|
||||
let color_2 = parse_hexstring(x.1);
|
||||
blend_int(color_1, color_2)
|
||||
}
|
||||
|
||||
fn main() {
|
||||
println!("{}", hexcolor(123, 21, 12));
|
||||
println!("{}", hexcolor(0, 21, 0));
|
||||
println!(
|
||||
"{}",
|
||||
blend((hexcolor(123, 241, 21), hexcolor(201, 94, 111)))
|
||||
);
|
||||
}
|
Loading…
Reference in New Issue
Block a user