typestar

temp_stats.zig in Zig

A week of daily highs reduced to low, high and mean, with a scaled bar per day.

// One week of daily highs: spread, mean, and a scaled bar chart.
const std = @import("std");

const days = [_][]const u8{ "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun" };
const temps = [_]i32{ 61, 68, 74, 79, 72, 65, 58 };

pub fn main() void {
    var lo: i32 = temps[0];
    var hi: i32 = temps[0];
    var sum: i32 = 0;
    for (temps) |t| {
        if (t < lo) lo = t;
        if (t > hi) hi = t;
        sum += t;
    }
    const mean = @as(f32, @floatFromInt(sum)) / temps.len;
    const span = @max(hi - lo, 1);

    std.debug.print("day temp range                 diff\n", .{});
    std.debug.print("------------------------------------\n", .{});
    // Bars scale to the week's spread; the +1 keeps Sunday visible.
    const bars = "#####################";
    var warm_days: u32 = 0;
    for (days, temps) |day, t| {
        const width: usize = @intCast(@divTrunc(20 * (t - lo), span) + 1);
        const diff = @as(f32, @floatFromInt(t)) - mean;
        const sign: []const u8 = if (diff >= 0) "+" else "";
        if (diff > 0) warm_days += 1;
        std.debug.print("{s} {d:>4}  {s:<21} {s}{d:.1}\n", .{
            day, t, bars[0..width], sign, diff,
        });
    }
    std.debug.print("------------------------------------\n", .{});
    std.debug.print("low {d}, high {d}, mean {d:.1}\n", .{ lo, hi, mean });
    std.debug.print("days above the mean: {d}\n", .{warm_days});
}

How it works

  1. One pass tracks the coolest and warmest days and the running sum.
  2. for (days, temps) walks both arrays in lockstep — lengths must match.
  3. Bars scale to the spread by slicing a string of hashes; the sign is chosen by hand.

Keywords and builtins used here

The run, in numbers

Lines
36
Characters to type
1246
Tokens
389
Three-star pace
65 tpm

At the three-star pace of 65 tokens a minute, this run takes about 359 seconds.

Type this snippet

Step 3 of 3 in Encore, step 27 of 27 in Language basics.

← Previous