Adding file::read_to_matrix, parse::string_to_numbers.

This commit is contained in:
Patrick MARIE 2021-01-17 18:46:58 +01:00
parent a4f69cc2c2
commit 89da9b45a9
2 changed files with 31 additions and 1 deletions

View File

@ -1,5 +1,7 @@
use std::fs;
use crate::parse::string_to_numbers;
pub fn read_to_lines(_filename: &str) -> Result<Vec<String>, String> {
let _contents = fs::read_to_string(_filename);
if let Err(v) = _contents {
@ -23,3 +25,18 @@ pub fn read_to_string(_filename: &str) -> Result<String, String> {
Err(v) => Err(v)
}
}
pub fn read_to_matrix(_filename: &str) -> Result<Vec<Vec<i128>>, String> {
let _lines = read_to_lines(_filename);
if let Err(v) = _lines {
return Err(v);
}
Ok(_lines
.unwrap()
.iter()
.map(|x| string_to_numbers(x.to_string()))
.collect()
)
}

View File

@ -2,7 +2,20 @@ pub fn string_to_usize_vec(input: String) -> Vec<usize> {
input.chars().map(|x| x.to_digit(10).unwrap() as usize).collect()
}
pub fn string_to_numbers(input: String) -> Vec<i128> {
input
.split_whitespace()
.map(|x| x.parse::<i128>().unwrap())
.collect()
}
#[test]
fn test_string_to_usize_vec() {
assert_eq!(vec![1, 2, 3, 4], string_to_usize_vec(String::from("1234")));
}
#[test]
fn test_string_to_numbers() {
assert_eq!(vec![1, 2, -3, -4], string_to_numbers(String::from("1 2 -3 -4")));
}