Created
September 27, 2021 22:39
-
-
Save malthejorgensen/fd0e4da502e6235267e25c4f3b2bbcc7 to your computer and use it in GitHub Desktop.
Summing a file of integers in Rust and Zig
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::fs::File; | |
use std::io::prelude::*; | |
fn main() -> std::io::Result<()> { | |
let mut file = File::open("foo.txt")?; | |
let mut contents = String::new(); | |
file.read_to_string(&mut contents)?; | |
let mut sum: u64 = 0; | |
for line in contents.lines() { | |
match line.parse::<u64>() { | |
Ok(val) => sum += val, | |
Err(_) => println!("\"{}\" was not a number", line), | |
}; | |
} | |
println!("{}", sum); | |
Ok(()) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const std = @import("std"); | |
const ArrayList = std.ArrayList; | |
const test_allocator = std.testing.allocator; | |
pub fn main() anyerror!void { | |
const file = try std.fs.cwd().openFile("numbers.txt", .{ .read = true }); | |
const contents = try file.reader().readAllAlloc( | |
test_allocator, | |
10000, | |
); | |
var lines = ArrayList(ArrayList(u8)).init(test_allocator); | |
var lineIndex: u8 = 0; | |
var currentLine = ArrayList(u8).init(test_allocator); | |
for (contents) |c| { | |
if (c == '\n') { | |
try lines.append(currentLine); | |
currentLine = ArrayList(u8).init(test_allocator); | |
} else { | |
try currentLine.append(c); | |
} | |
} | |
var sum: u64 = 0; | |
for (lines.items) |line| { | |
if (std.fmt.parseInt(u64, line.items, 10)) |value| { | |
sum += value; | |
} else |err| { | |
std.log.warn("Unable to parse {s}", .{line.items}); | |
} | |
} | |
std.log.info("{d}", .{sum}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment