Created
December 2, 2023 11:50
-
-
Save marcusramberg/0ec94ce2d098e202bf94c42c692979ff to your computer and use it in GitHub Desktop.
This file contains hidden or 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 MatchError = error{ PartialMatch, NoMatch }; | |
pub fn main() !void { | |
const allocator = std.heap.page_allocator; | |
// stdout is for the actual output of your application, for example if you | |
// are implementing gzip, then only the compressed bytes should be sent to | |
// stdout, not any debugging messages. | |
const stdin_file = std.io.getStdIn().reader(); | |
var br = std.io.bufferedReader(stdin_file); | |
const stdin = br.reader(); | |
var buf: [100]u8 = undefined; | |
var sum: u32 = 0; | |
var firstNumber: u8 = 0; | |
var lastNumber: u8 = 0; | |
var cipher = std.ArrayList(u8).init(allocator); | |
defer cipher.deinit(); | |
while (try stdin.readUntilDelimiterOrEof(buf[0..], '\n')) |user_input| { | |
for (user_input) |c| { | |
var num: u8 = c; | |
if (c < '0' or c > '9') { | |
try cipher.append(c); | |
// std.debug.print("Checking: {s}.\n", .{cipher.items}); | |
num = getNum(cipher.items) catch |err| { | |
if (err == MatchError.NoMatch) { | |
cipher.clearRetainingCapacity(); | |
try cipher.append(c); | |
} | |
continue; | |
}; | |
} | |
// std.debug.print("Found a number: {c}.\n", .{num}); | |
cipher.clearRetainingCapacity(); | |
if (firstNumber == 0) { | |
firstNumber = num; | |
} | |
lastNumber = num; | |
} | |
cipher.clearRetainingCapacity(); | |
const num = (firstNumber - '0') * 10 + (lastNumber - '0'); | |
std.debug.print("The number for {s} is {}.\n", .{ user_input, num }); | |
sum = sum + num; | |
std.debug.print("The sum is {}.\n", .{sum}); | |
firstNumber = 0; | |
lastNumber = 0; | |
} | |
std.debug.print("The answer is {}.", .{sum}); | |
} | |
fn getNum(c: []u8) MatchError!u8 { | |
const numbers = [_][]const u8{ "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" }; | |
for (numbers, 0..) |number, i| { | |
if (std.mem.eql(u8, c, number)) { | |
// return '1' + @as(u8, @intCast(i)); | |
return '1' + i; | |
} | |
if (std.mem.startsWith(u8, number, c)) return MatchError.PartialMatch; | |
} | |
return MatchError.NoMatch; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment