#4-1 작은 프로젝트들

Pt J·2020년 8월 15일
0

[完] Rust Programming

목록 보기
6/41
post-thumbnail

이 시리즈는 Rust 공식문서를 통해 공부한 흔적임을 밝힙니다.

이번 포스팅은 약간 번외편이다.

🦀 Ferris | "피터, 잠깐! 다음 장으로 넘어가기 전에 여길 보라고!"

If you want to practice with the concepts discussed in this chapter, try building programs to do the following:

  • Convert temperatures between Fahrenheit and Celsius.
  • Generate the nth Fibonacci number.
  • Print the lyrics to the Christmas carol “The Twelve Days of Christmas,” taking advantage of the repetition in the song.

🐧 Peter | "그러니까 이걸 구현해보고 넘어가자는 거지?"

그렇게 피터와 페리스는 Rust 공식문서에서 소개해준 작은 프로젝트를 진행하고 가기로 했다.

섭씨 화씨 온도 변환

🦀 Ferris | "먼저 온도 변환 프로그램을 작성해볼까?"

🐧 Peter | "좋아, 구체적인 요구사항은 없긴 한데... 섭씨 온도를 화씨 온도로 변환하는 함수와 화씨 온도를 섭씨 온도로 변환하는 함수를 각각 작성해서 main 함수에서 그것을 호출하도록 하면 되겠지?"

🦀 Ferris | "자료형은 부동소수점으로, 그러니까 f64를 사용하면 좋을 것 같아."

🐧 Peter | "온도를 사용자가 입력하도록 하자. 그리고 무엇에서 무엇으로 변환하는지도 사용자에게 입력을 받으면 되겠다."

🦀 Ferris | "입력 받을 땐 그것을 부동소수점으로 변환할 수 없는 경우에 대한 예외처리를 잊지 말고!!"

🐧 Peter | "예외처리! 그거 아주 중요하지."

🦀 Ferris | "피터 피터! 내가 참고할 만한 변환식을 가져왔어! 그런 의미에서 코딩은 네 몫이야!"

  • °F = °C × 1.8 + 32
  • °C = (°F − 32) / 1.8
peter@hp-laptop:~/rust-practice/chapter03$ mkdir practice
peter@hp-laptop:~/rust-practice/chapter03$ cd practice/
peter@hp-laptop:~/rust-practice/chapter03/practice$ cargo new temperature_converter
     Created binary (application) `temperature_converter` package
peter@hp-laptop:~/rust-practice/chapter03/practice$ cd temperature_converter/
peter@hp-laptop:~/rust-practice/chapter03/practice/temperature_converter$ vi src/main.rs

src/main.rs

use std::io;

fn main() {
    println!("[1] Convert Fahrenheit to Celsius");
    println!("[2] Convert Celsius to Fahrenheit");
    let choice = loop {
        println!("Input the choice.");

        let mut choice = String::new();

        io::stdin().read_line(&mut choice)
            .expect("Fail to read line");

        let choice: u32 = match choice.trim().parse() {
            Ok(num) => num,
            Err(_) => {
                println!("Input number 1 or 2");
                continue
            },
        };

        if choice > 0 && choice < 3 {
            break choice;
        }
    };

    let temperature = loop {
        println!("Input the temperature to convert without the unit symbol.");

        let mut temperature = String::new();

        io::stdin().read_line(&mut temperature)
            .expect("Fail to read line");

        let temperature: f64 = match temperature.trim().parse() {
            Ok(num) => num,
            Err(_) => {
                println!("Please input the tempeture without unit symbol");
                continue
            },

        };

        break temperature;
    };

    let temperature = if choice == 1 {
        fahrenheit_to_celsius(temperature)
    } else {
        celsius_to_fahrenheit(temperature)
    };

    println!("result: {}", temperature);
}

fn fahrenheit_to_celsius(temp: f64) -> f64 {
    (temp - 32.) / 1.8
}

fn celsius_to_fahrenheit(temp: f64) -> f64 {
    temp * 1.8 + 32.
}

🐧 Peter | "이거 봐 페리스, 먼저 화씨 온도를 섭씨 온도로 변환하는 거."

peter@hp-laptop:~/rust-practice/chapter03/practice/temperature_converter$ cargo run
   Compiling temperature_converter v0.1.0 (/home/peter/rust-practice/chapter03/practice/temperature_converter)
    Finished dev [unoptimized + debuginfo] target(s) in 0.30s
     Running `target/debug/temperature_converter`
[1] Convert Fahrenheit to Celsius
[2] Convert Celsius to Fahrenheit
Input the choice.
1
Input the temperature to convert without the unit symbol.
100
result: 37.77777777777778
peter@hp-laptop:~/rust-practice/chapter03/practice/temperature_converter$ 

🐧 Peter | "그리고 섭씨 온도를 화씨 온도로 변환하는 거."

peter@hp-laptop:~/rust-practice/chapter03/practice/temperature_converter$ cargo run
    Finished dev [unoptimized + debuginfo] target(s) in 0.01s
     Running `target/debug/temperature_converter`
[1] Convert Fahrenheit to Celsius
[2] Convert Celsius to Fahrenheit
Input the choice.
2
Input the temperature to convert without the unit symbol.
100
result: 212
peter@hp-laptop:~/rust-practice/chapter03/practice/temperature_converter$ 

🐧 Peter | "그리고 잘못된 값이 입력되었을 경우 프로그램을 종료하지 않고 의도된 입력이 들어올 때까지 반복문을 돌도록 예외처리를 했지!"

peter@hp-laptop:~/rust-practice/chapter03/practice/temperature_converter$ cargo run
    Finished dev [unoptimized + debuginfo] target(s) in 0.01s
     Running `target/debug/temperature_converter`
[1] Convert Fahrenheit to Celsius
[2] Convert Celsius to Fahrenheit
Input the choice.
string
Input number 1 or 2
Input the choice.
0
Input the choice.
2
Input the temperature to convert without the unit symbol.
36.5°C 
Please input the tempeture without unit symbol
Input the temperature to convert without the unit symbol.
36.5
result: 97.7
peter@hp-laptop:~/rust-practice/chapter03/practice/temperature_converter$

🦀 Ferris | "좋아, 이 정도면 다음으로 넘어가도 될 것 같아."

n번째 피보나치 수

🦀 Ferris | "이번에는 피보나치 수를 구하는 프로그램이야. 피보나치 수가 뭔진 알겠지?"

🐧 Peter | "물론 알지. 1, 1, 2, 3, 5, 8, 13, ... 이렇게 앞의 두 수를 더해서 구한 숫자들의 수열이잖아. 반복문이나 재귀함수를 배우면 항상 나오는 예제인걸?"

🦀 Ferris | "너 말 잘했다. 말 나온 김에 두 가지 방식 모두로 구현해보지 그래?"

🐧 Peter | "어... 어? 뭔가 사서 고생하는 것 같은데... 뭐, 좋아. 다양한 방식으로 문제를 해결해보는 건 좋은 경험이니까."

ver. 반복문

🐧 Peter | "반복문을 통해 피보나치 수를 구하려면 이전 두 개의 값을 가지고 있어야 하지."

🦀 Ferris | "말로만 하지 말고 코드로 보여줘. 포괄적인 문서보다 작동하는 소프트웨어를!

🐧 Peter | "아니, 애자일 선언문은 왼쪽에 있는 것들도 가치가 있다니까?"

peter@hp-laptop:~/rust-practice/chapter03/practice/temperature_converter$ cd ..
peter@hp-laptop:~/rust-practice/chapter03/practice$ cargo new iterative_fibonacci
     Created binary (application) `iterative_fibonacci` package
peter@hp-laptop:~/rust-practice/chapter03/practice$ cd iterative_fibonacci/
peter@hp-laptop:~/rust-practice/chapter03/practice/iterative_fibonacci$ vi src/main.rs

src/main.rs

use std::io;

fn main() {
    let number = loop {
        println!("Input the number.");
      
        let mut number = String::new();

        io::stdin().read_line(&mut number)
            .expect("Fail to read line");

        let number: u32 = match number.trim().parse() {
            Ok(num) => num,
            Err(_) => {
                println!("Try again...");
                continue
            },
        };

        break number;
    };

    println!("{}th fibonacci number is {}.", number, fibonacci(number));
}

fn fibonacci(num: u32) -> u32 {
    let mut n1 = 1;
    let mut n2 = 1;

    if num <= 2 {
        return 1;
    }
    for _ in 3..num+1 {
        let tmp = n1;
        n1 = n2;
        n2 = tmp + n1;
    }

    n2
}
peter@hp-laptop:~/rust-practice/chapter03/practice/iterative_fibonacci$ cargo run
   Compiling iterative_fibonacci v0.1.0 (/home/peter/rust-practice/chapter03/practice/iterative_fibonacci)
    Finished dev [unoptimized + debuginfo] target(s) in 0.28s
     Running `target/debug/iterative_fibonacci`
Input the number.
10
10th fibonacci number is 55.
peter@hp-laptop:~/rust-practice/chapter03/practice/iterative_fibonacci$

🐧 Peter | "1, 1, 2, 3, 5, 8, 13, 21, 34, 55. 10번째 55, 맞는 것 같아!"

🦀 Ferris | "자, 이제 제귀함수로도 마저 구현해야지?"

ver. 재귀함수

🐧 Peter | "main 함수는 그대로 두고 fibonacci 함수만 수정해야지!"

peter@hp-laptop:~/rust-practice/chapter03/practice/iterative_fibonacci$ cd ..
peter@hp-laptop:~/rust-practice/chapter03/practice$ cargo new recursive_fibonacci
     Created binary (application) `recursive_fibonacci` package
peter@hp-laptop:~/rust-practice/chapter03/practice$ cd recursive_fibonacci/
peter@hp-laptop:~/rust-practice/chapter03/practice/recursive_fibonacci$ cp ../iterative_fibonacci/src/main.rs src/main.rs 
peter@hp-laptop:~/rust-practice/chapter03/practice/recursive_fibonacci$ vi src/main.rs 

src/main.rs

use std::io;

fn main() {
    let number = loop {
        println!("Input the number.");
      
        let mut number = String::new();

        io::stdin().read_line(&mut number)
            .expect("Fail to read line");

        let number: u32 = match number.trim().parse() {
            Ok(num) => num,
            Err(_) => {
                println!("Try again...");
                continue
            },
        };

        break number;
    };

    println!("{}th fibonacci number is {}.", number, fibonacci(number));
}

fn fibonacci(num: u32) -> u32 {
    if num <= 2 {
        return 1;
    }

    fibonacci(num-1) + fibonacci(num-2)
}
peter@hp-laptop:~/rust-practice/chapter03/practice/recursive_fibonacci$ cargo run
   Compiling recursive_fibonacci v0.1.0 (/home/peter/rust-practice/chapter03/practice/recursive_fibonacci)
    Finished dev [unoptimized + debuginfo] target(s) in 0.21s
     Running `target/debug/recursive_fibonacci`
Input the number.
10
10th fibonacci number is 55.
peter@hp-laptop:~/rust-practice/chapter03/practice/recursive_fibonacci$ 

🐧 Peter | "재귀함수로도 잘 작동하는 걸 확인했어."

🦀 Ferris | "그럼 다음으로 넘어가보자."

캐롤 가사 출력

🐧 Peter | "The Twelve Days of Christmas?"

🦀 Ferris | "날짜가 넘어갈 때마다 새 선물이 추가되며 기존의 선물들을 역순으로 열거하는 게 이 캐롤의 특징이지."

🐧 Peter | "12일, 개수가 정해져 있는 것들의 집합, 반복문... 배열과 for를 사용하면 될 것 같은데?"

🦀 Ferris | "그래? 어디 한 번 보여줘봐."

peter@hp-laptop:~/rust-practice/chapter03/practice/recursive_fibonacci$ cd ..
peter@hp-laptop:~/rust-practice/chapter03/practice$ cargo new the_twelve_days_of_christmas
     Created binary (application) `the_twelve_days_of_christmas` package
peter@hp-laptop:~/rust-practice/chapter03/practice$ cd the_twelve_days_of_christmas/
peter@hp-laptop:~/rust-practice/chapter03/practice/the_twelve_days_of_christmas$ vi src/main.rs

src/main.rs

fn main() {
    let sequence = ["first", "second", "third", "fourth", "fifth", "sixth", "seventh", "eighth", "ninth", "tenth", "eleventh", "twelfth"];
    let lylic_block = [
        "A partridge in a pear tree",
        "Two turtle doves",
        "Three French hens",
        "Four calling birds",
        "Five gold rings, badam-pam-pam",
        "Six geese a laying",
        "Seven swans a swimming",
        "Eight maids a milking",
        "Nine ladies dancing",
        "Ten lords a leaping",
        "Eleven pipers piping",
        "Twelve drummers drumming",
    ];

    for day in 0..12 {
        println!("On the {} day of Christmas", sequence[day]);
        println!("My true love gave to me");

        for n in (0..day+1).rev() {
            if day != 0 && n == 0 {
                print!("And ");
            }
            println!("{}", lylic_block[n]);
        }
        println!("");
    }
}
peter@hp-laptop:~/rust-practice/chapter03/practice/the_twelve_days_of_christmas$ cargo run
   Compiling the_twelve_days_of_christmas v0.1.0 (/home/peter/rust-practice/chapter03/practice/the_twelve_days_of_christmas)
    Finished dev [unoptimized + debuginfo] target(s) in 0.26s
     Running `target/debug/the_twelve_days_of_christmas`
On the first day of Christmas
My true love gave to me
A partridge in a pear tree

On the second day of Christmas
My true love gave to me
Two turtle doves
And A partridge in a pear tree

On the third day of Christmas
My true love gave to me
Three French hens
Two turtle doves
And A partridge in a pear tree

On the fourth day of Christmas
My true love gave to me
Four calling birds
Three French hens
Two turtle doves
And A partridge in a pear tree

On the fifth day of Christmas
My true love gave to me
Five gold rings, badam-pam-pam
Four calling birds
Three French hens
Two turtle doves
And A partridge in a pear tree

On the sixth day of Christmas
My true love gave to me
Six geese a laying
Five gold rings, badam-pam-pam
Four calling birds
Three French hens
Two turtle doves
And A partridge in a pear tree

On the seventh day of Christmas
My true love gave to me
Seven swans a swimming
Six geese a laying
Five gold rings, badam-pam-pam
Four calling birds
Three French hens
Two turtle doves
And A partridge in a pear tree

On the eighth day of Christmas
My true love gave to me
Eight maids a milking
Seven swans a swimming
Six geese a laying
Five gold rings, badam-pam-pam
Four calling birds
Three French hens
Two turtle doves
And A partridge in a pear tree

On the ninth day of Christmas
My true love gave to me
Nine ladies dancing
Eight maids a milking
Seven swans a swimming
Six geese a laying
Five gold rings, badam-pam-pam
Four calling birds
Three French hens
Two turtle doves
And A partridge in a pear tree

On the tenth day of Christmas
My true love gave to me
Ten lords a leaping
Nine ladies dancing
Eight maids a milking
Seven swans a swimming
Six geese a laying
Five gold rings, badam-pam-pam
Four calling birds
Three French hens
Two turtle doves
And A partridge in a pear tree

On the eleventh day of Christmas
My true love gave to me
Eleven pipers piping
Ten lords a leaping
Nine ladies dancing
Eight maids a milking
Seven swans a swimming
Six geese a laying
Five gold rings, badam-pam-pam
Four calling birds
Three French hens
Two turtle doves
And A partridge in a pear tree

On the twelfth day of Christmas
My true love gave to me
Twelve drummers drumming
Eleven pipers piping
Ten lords a leaping
Nine ladies dancing
Eight maids a milking
Seven swans a swimming
Six geese a laying
Five gold rings, badam-pam-pam
Four calling birds
Three French hens
Two turtle doves
And A partridge in a pear tree

peter@hp-laptop:~/rust-practice/chapter03/practice/the_twelve_days_of_christmas$ 

🐧 Peter | "반복문 없이 이 모든 문장을 입력했다면 정말 힘들었을거야."

🦀 Ferris | "맞아, 그래서 반복문이 필요한거지. 반복문에서 iter 메서드와 enumerate 메서드를 사용하는 방법도 있지만. 그걸 쓰면 (인덱스, 원소에 대한 참조) 튜플을 반환하거든.

🐧 Peter | "아니, 그걸 왜 이제 말해주는거지;;"

🦀 Ferris | "아무튼 이제 충분히 연습이 된 것 같으니 다음 장으로 넘어가자고."

profile
Peter J Online Space - since July 2020

0개의 댓글