-1

I have an input:

let b = String::from("1 2 4 5 6");

And my task is to return the exponential function of each value as a string as output:

let output = "2.718281828459045 7.38905609893065 54.598150033144236 148.4131591025766 403.4287934927351";

I have no idea how to solve this task. How to parse each value and use exp function and send string of the result?

kmdreko
  • 25,172
  • 5
  • 32
  • 61

2 Answers2

5

Here's the ingredients:

phimuemue
  • 32,638
  • 9
  • 79
  • 112
2

I'm not going to repeat what phimuemue has already explained so here's an implementation:

fn example(s: &str) -> String {
    s.trim()
        .split_whitespace()
        .map(|n| {
            let mut n = n.parse::<f64>().unwrap();
            n = n.exp();
            n.to_string()
        })
        .collect::<Vec<String>>()
        .join(" ")
}

fn main() {
    let input = String::from("1 2 4 5 6");
    let output = example(&input);
    dbg!(output); // "2.718281828459045 7.3890560989306495 54.59815003314423 148.41315910257657 403.428793492735"
}

playground

pretzelhammer
  • 12,263
  • 15
  • 41
  • 88
  • Or using [`Itertools::join`](https://docs.rs/itertools/0.10.0/itertools/trait.Itertools.html#method.join): https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=ce539a2fbc815184fe85c1488c84f60e – Jmb Feb 16 '21 at 14:37