Create a two-dimensional array at runtime: Difference between revisions

Content added Content deleted
m (→‎{{header|Rust}}: Added comment explanations)
(→‎{{header|Rust}}: Fixed argument handling)
Line 1,937: Line 1,937:
<lang rust>use std::env;
<lang rust>use std::env;
fn main() {
fn main() {
let mut args = env::args();
let mut args = env::args().skip(1).flat_map(|num| num.parse());
let rows = args.nth(1).unwrap().parse().unwrap();
let rows = args.next().expect("Expected number of rows as first argument");
let cols = args.nth(2).unwrap().parse().unwrap();
let cols = args.next().expect("Expected number of columns as second argument");


assert!(rows != 0 && cols != 0);
assert!(rows != 0 && cols != 0);


// Creates a vector of vectors with all elements initialized to 0.
// Creates a vector of vectors with all elements initialized to 0.
let mut v = init_vec(|| init_vec(|| 0, cols), rows);
let mut v = init_vec(rows, || init_vec(cols, || 0));
v[rows-1][cols-1] = 4;
v[0][0] = 1;
println!("{}", v[rows-1][cols-1]);
println!("{}", v[0][0]);




Line 1,954: Line 1,954:
// initialized with the values computed by `f`
// initialized with the values computed by `f`


fn init_vec<F,T>(f: F, n: usize) -> Vec<T>
fn init_vec<F,T>(n: usize, f: F) -> Vec<T>
where F: Fn() -> T
where F: Fn() -> T
{
{
let mut vec = Vec::with_capacity(n);
let mut vec = Vec::with_capacity(n);
for i in 0..n {
for _ in 0..n {
vec.push(f());
vec.push(f());
}
}