1

I'm trying to concatenate all of the contents of a vector into a single number. This would be like [1, 2, 4] -> 124. Here's what I have right now:

fn sumVector(vec: &Vec<u32>) -> u32 {
    return vec.to_owned().concat();
}

This is failing with error

error[E0599]: no method named `concat` found for type `std::vec::Vec<u32>` in the current scope
 --> src/lib.rs:2:27
  |
2 |     return vec.to_owned().concat();
  |                           ^^^^^^ method not found in `std::vec::Vec<u32>`
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
  • 1
    What should `vec![9, 9, ...<1000 more>..., 9, 9]` result in? – Shepmaster Nov 18 '19 at 20:45
  • [Why is it discouraged to accept a reference to a String (&String), Vec (&Vec), or Box (&Box) as a function argument?](https://stackoverflow.com/q/40006219/155423) – Shepmaster Nov 18 '19 at 20:45
  • 1
    It is misleading to title this function **sum**. By the way, idiomatic Rust uses `snake_case` for variables, methods, macros, fields and modules; `UpperCamelCase` for types and enum variants; and `SCREAMING_SNAKE_CASE` for statics and constants. – Shepmaster Nov 18 '19 at 20:46
  • 2
    https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=e928bcc5fe70378bacafa49c807a1ad2 ? – Stargateur Nov 18 '19 at 20:51

2 Answers2

6

As said in the comments by Stargateur, you can do:

fn concat(vec: &[u32]) -> u32 {
    vec.iter().fold(0, |acc, elem| acc * 10 + elem)
}

You can also write the same function in imperative style:

fn concat(vec: &[u32]) -> u32 {
    let mut acc = 0;
    for elem in vec {
        acc *= 10;
        acc += elem;
    }
    acc
}
Ortomala Lokni
  • 56,620
  • 24
  • 188
  • 240
-1

You can follow Ortomala Lokni's procedure if your input vector contains single digit integers.

If the vector contains multi-digit integers, the function may not return the intended value. The following concat_new function handles this case.

fn main() {
    let a = vec![10_i32, 20, 300];

    println!("{:?}", concat_new(&a));
    println!("{:?}", concat(&a));   
}

fn concat_new(vec: &[i32]) -> i32 {
    let t = vec.iter().fold("".to_string(), |acc, x| acc + &x.to_string());
    t.parse::<i32>().unwrap()
}

fn concat(vec: &[i32]) -> i32 {
    vec.iter().fold(0, |acc, elem| acc * 10 + elem)
}
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
basic_bgnr
  • 697
  • 5
  • 14
  • 3
    This is a very inefficient way, even ignoring that it's ultimately a string. [How can I append a formatted string to an existing String?](https://stackoverflow.com/q/28333612/155423) – Shepmaster Nov 19 '19 at 17:30
  • @shepmaster, thanks for the link.but, I was just highlighting case where multi digit integer would not work. – basic_bgnr Nov 19 '19 at 17:38