Add exercise 212, 258, fix clippy warnings

Emelie Graven 2022-04-03 12:28:12 +02:00
parent c5aa3d4abf
commit 6ff23340af
Signed by: emelie
GPG Key ID: C11123726DBB55A1
6 changed files with 260 additions and 4 deletions

e_212/Cargo.toml Normal file
View File

@ -0,0 +1,9 @@
name = "e_212"
version = "0.1.0"
authors = ["Emelie Graven <>"]
edition = "2021"
# See more keys and their definitions at

e_212/src/ Normal file
View File

@ -0,0 +1,130 @@
/*! # Description
When we Swedes are young, we are taught a SUPER-SECRET language that only kids know, so we can hide secrets from our confused parents. This language is known as "Rövarspråket" (which means "Robber's language", more or less), and is surprisingly easy to become fluent in, at least when you're a kid. Recently, the cheeky residents of /r/Sweden decided to play a trick on the rest on reddit, and get a thread entirely in Rövarspråket to /r/all. [The results were hilarious](
Rövarspråket is not very complicated: you take an ordinary word and replace the consonants with the consonant doubled and with an "o" in between. So the consonant "b" is replaced by "bob", "r" is replaced with "ror", "s" is replaced with "sos", and so on. Vowels are left intact. It's made for Swedish, but it works just as well in English.
Your task today is to write a program that can encode a string of text into Rövarspråket.
(note: this is a higly guarded Swedish state secret, so I trust that none of you will share this very privileged information with anyone! If you do, you will be extradited to Sweden and be forced to eat [surströmming]( as penance.)
(note 2: surströmming is actually not that bad, it's much tastier than its reputation would suggest! I'd go so far as to say that it's the tastiest half-rotten fish in the world!)
# Formal inputs &amp; outputs
## Input
You will recieve one line of input, which is a text string that should be encoded into Rövarspråket.
## Output
The output will be the encoded string.
A few notes: your program should be able to handle case properly, which means that "Hello" should be encoded to "Hohelollolo", and *not* as "HoHelollolo" (note the second capital "H").
Also, since Rövarspråket is a Swedish invention, your program should follow Swedish rules regarding what is a vowel and what is a consonant. The Swedish alphabet is the same as the English alphabet except that there are three extra characters at the end (Å, Ä and Ö) which are all vowels. In addition, Y is always a vowel in Swedish, so the full list of vowels in Swedish is A, E, I, O, U, Y, Å, Ä and Ö. The rest are consonants.
Lastly, any character that is not a vowel or a consonant (i.e. things like punctuation) should be left intact in the output.
# Example inputs
## Input 1
Jag talar Rövarspråket!
## Output 1
Jojagog totalolaror Rorövovarorsospoproråkoketot!
## Input 2
I'm speaking Robber's language!
## Output 2
I'mom sospopeakokinongog Rorobobboberor'sos lolanongoguagoge!
# Challenge inputs
## Input 1
Tre Kronor är världens bästa ishockeylag.
## Input 2
Vår kung är coolare än er kung.
# Bonus
Make your program able to decode a Rövarspråket-encoded sentence as well as encode it.
# Notes
This excellent problem (which filled my crusty old Swedish heart with glee) was suggested by /u/pogotc. Thanks so much for the suggestion!
If you have an idea for a problem, head on over to /r/dailyprogrammer_ideas and post your suggestion! If it's good idea, we might use it, and you'll be as cool as /u/pogotc.
const CONSONANTS: [char; 40] = [
'b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'w', 'v', 'x',
'z', 'B', 'C', 'D', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'W', 'V',
'X', 'Z',
fn main() {}
fn encode(input: String) -> String {
input.chars().fold(String::new(), |output, ch| {
if is_consonant(&ch) {
output + &ch.to_string() + "o" + &ch.to_string().to_ascii_lowercase()
} else {
output + &ch.to_string()
fn decode(input: String) -> String {
let mut chars = input.chars();
let mut output = String::new();
while let Some(ch) = & {
if is_consonant(ch) {
// Would use advance_by() here, but it requires nightly;;
output += &ch.to_string();
fn is_consonant(ch: &char) -> bool {
mod tests {
use super::*;
fn challenge_input_1() {
assert_eq!(encode(String::from("Tre Kronor är världens bästa ishockeylag.")), String::from("Totrore Kokrorononoror äror vovärorloldodenonsos bobäsostota isoshohocockokeylolagog."));
fn challenge_input_2() {
encode(String::from("Vår kung är coolare än er kung.")),
String::from("Vovåror kokunongog äror cocoololarore änon eror kokunongog.")
fn bonus_challenge_input_1() {
assert_eq!(decode(String::from("Totrore Kokrorononoror äror vovärorloldodenonsos bobäsostota isoshohocockokeylolagog.")), (String::from("Tre Kronor är världens bästa ishockeylag.")));
fn bonus_challenge_input_2() {
"Vovåror kokunongog äror cocoololarore änon eror kokunongog."
String::from("Vår kung är coolare än er kung.")

e_258/Cargo.toml Normal file
View File

@ -0,0 +1,9 @@
name = "e_258"
version = "0.1.0"
authors = ["Emelie Graven <>"]
edition = "2021"
# See more keys and their definitions at

e_258/src/ Normal file
View File

@ -0,0 +1,106 @@
# Description
A [network socket]( is an endpoint of a connection across a computer network.
Today, most communication between computers is based on the Internet Protocol; therefore most network sockets are Internet
sockets. [Internet Relay Chat]( (IRC) is a chat system on the Internet.
It allows people from around the world to have conversations together, but it can also be used for two people to chat
[Freenode]( is an IRC network used to discuss peer-directed projects. Their servers
are all accessible from the domain names and In 2010, it became the largest free and
open source software-focused IRC network. In 2013 it became the largest IRC network, encompassing more than 90,000 users
and 40,000 channels and gaining almost 5,000 new users per year. We have a channel on freenode ourselves for all things
/r/DailyProgrammer on freenode, which is
Your challenge today will be to communicate with the freenode IRC server. This will consist of opening a TCP socket to
freenode and sending two protocol messages to initiate the connection. The original
[IRC RFC]( defines a message as a line of text up to 512 bytes starting
with a message code, followed by one or more space separated parameters, and ending with a CRLF (`\r\n`). The last
paramater can be prefixed by a colon to mark it as a parameter that can contain spaces, which will take up the rest of the
line. An example of a colon-prefixed parameter would be the contents of a chat message, as that is something that contains spaces.
The first of the two initiation messages (`NICK`) defines what name people will see when you send a chat message.
It will have to be unique, and you will not be able to connect if you specify a name which is currently in use or reserved.
It has a single parameter `<nickname>` and will be sent in the following form:
NICK <nickname>
The second of the two initiation messages (`USER`) defines your username, user mode, server name, and real name. The username must also be unique and is usually set to be the same as the nickname. Originally, hostname was sent instead of user mode, but this was changed in a later version of the IRC protocol. For our purposes, standard mode `0` will work fine. As for server name, this will be ignored by the server and is conventionally set as an asterisk (`*`). The real name parameter can be whatever you want, though it is usually set to be the same value as the nickname. It does not have to be unique and may contain spaces. As such, it must be prefixed by a colon. The `USER` message will be sent in the following form:
USER <username> 0 * :<realname>
# Input Description
You will give your program a list of lines specifying server, port, nickname, username, and realname. The first line will contain the server and the port, separated by a colon. The second through fourth lines will contain nick information.
Real Name
# Output Description
Your program will open a socket to the specified server and port, and send the two required messages. For example:
NICK Nickname
USER Username 0 * :Real Name
Afterwards, it will begin to receive messages back from the server. Many messages sent from the server will be prefixed to indicate the origin of the message. This will be in the format `:server` or `:nick[!user][@host]`, followed by a space. The exact contents of these initial messages are usually not important, but you must output them in some manner. The first few messages received on a successful connection will look something like this: NOTICE * :*** Looking up your hostname... NOTICE * :*** Checking Ident NOTICE * :*** Found your hostname NOTICE * :*** No Ident response 001 Nickname :Welcome to the freenode Internet Relay Chat Network Nickname
# Challenge Input
The server will occasionally send `PING` messages to you. These have a single parameter beginning with a colon. The exact contents of that parameter will vary between servers, but is usually a unique string used to verify that your client is still connected and responsive. On freenode, it appears to be the name of the specific server you are connected to. For example:
# Challenge Output
In response, you must send a `PONG` message with the parameter being the same unique string from the `PING`. You must continue to do this for the entire time your program is running, or it will get automatically disconnected from the server. For example:
# Notes
You can see the full original IRC specification at Sections 2.3 and 4.1 are of particular note, as they describe the message format and the initial connection. See also,
[A Regular Expression For IRC Messages](
Happy Pi Day!
use std::error::Error;
use std::io::{BufRead, BufReader, Write};
use std::net::TcpStream;
const SERVER: &str = "";
const NICK: &str = "dailyprog_2851";
const USER_NAME: &str = "dailyprog_2851";
const REAL_NAME: &str = "dailyprog_2851";
fn main() -> Result<(), Box<dyn Error>> {
let mut stream = TcpStream::connect(SERVER)?;
stream.write_all((String::from("NICK ") + NICK + "\r\n").as_bytes())?;
(String::from("USER ") + USER_NAME + " 0 * :" + REAL_NAME + "\r\n").as_bytes(),
let mut reader = BufReader::new(stream);
let mut line = String::new();
loop {
reader.read_line(&mut line)?;
println!("{}", &line);
if line.starts_with("PING") {
.write_all(line.replace("PING", "PONG").as_bytes())?;

View File

@ -116,7 +116,7 @@ impl FromStr for Dice {
fn from_str(s: &str) -> Result<Dice, Self::Err> {
// Split string at "d" delimeter, parse elements into Dice struct containing u32s
let dice = s
.map(|x| x.parse::<u32>())
.collect::<Result<Vec<u32>, ParseIntError>>();
let dice = match dice {
@ -149,7 +149,7 @@ fn main() {
/// Main exercise loop
fn e_364() {
let input = fs::read_to_string("input.txt").unwrap();
let dice: Result<Vec<Dice>, DiceError> = input.split("\n").map(|x| x.parse()).collect();
let dice: Result<Vec<Dice>, DiceError> = input.split('\n').map(|x| x.parse()).collect();
match dice {
Ok(d) => d.iter().for_each(|x| println!("{}", x.roll_dice())),
Err(DiceError::ParseInt(e)) => eprintln!("Could not parse integer: {:?}", e),
@ -169,7 +169,7 @@ mod tests {
Dice { count: 16, die: 2 }
fn test_error_handling() {
assert!(matches!("3dx".parse::<Dice>(), Err(DiceError::ParseInt(_))));
assert_eq!("3d3d3".parse::<Dice>(), Err(DiceError::ParseFields));

View File

@ -98,6 +98,8 @@ Here's the first pass through the algorithm using the original example:
At this point you would start over at step 1 with the sequence `[5, 4, 4, 2, 1, 1, 1]`. After your second pass through the algorithm, your sequence will be `[3, 3, 1, 0, 0, 1]`, so start back at step 1 with this sequence. After your third pass you'll have `[2, 0, 0]`. On your fourth pass, you'll stop at step 5, because you'll have `N = 2` and an empty sequence (`[]`), and 2 > 0, so you will return false.
fn main() {}
@ -122,7 +124,7 @@ fn warmup_4(i: i32, mut set: Vec<i32>) -> Vec<i32> {
fn e_378(mut set: Vec<i32>) -> bool {
loop {
set = warmup_1(set);
if set.len() == 0 {
if set.is_empty() {
break true;
set = warmup_2(set);