Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Python3 version - 600_000ns
- // Zig version -Doptimize=ReleaseFast = 60_000ns
- // Mac M2Pro
- const std = @import("std");
- const Country = struct {
- name: []const u8,
- population: f32,
- isInEu: bool,
- hasCoastline: bool,
- pub fn format(this: Country, comptime _: []const u8, _: std.fmt.FormatOptions, stream: anytype) !void {
- try stream.print(
- "Country=`{[name]s}`, population={[population]d:.3}, isInEu={[isInEu]}, hasCoastline={[hasCoastline]}",
- this,
- );
- }
- };
- const City = struct {
- name: []const u8,
- country: ?*const Country,
- latitude: f32,
- longitude: f32,
- temperature: f32,
- pub fn format(this: City, comptime _: []const u8, _: std.fmt.FormatOptions, stream: anytype) !void {
- try stream.print(
- "CityName=`{[name]s}`, country={[country]?}, latitude={[latitude]d:.3}, longitude={[longitude]d:.3}, temperature={[temperature]d:.3}",
- this,
- );
- }
- };
- pub fn main() !void {
- var timer = try std.time.Timer.start();
- var stdout_buffered = std.io.bufferedWriter(std.io.getStdOut().writer());
- const stdout = stdout_buffered.writer();
- defer {
- stdout_buffered.flush() catch {};
- }
- // const stdout = std.io.getStdOut().writer();
- var GPA = std.heap.GeneralPurposeAllocator(.{}){};
- defer _ = GPA.deinit();
- const allocator = GPA.allocator();
- const countriesData = @embedFile("Countries.csv");
- var countries = std.StringHashMap(Country).init(allocator);
- defer countries.deinit();
- var countryIt = std.mem.splitScalar(u8, countriesData, '\n');
- _ = countryIt.first(); //Ignore header
- while (countryIt.next()) |originalCountryData| {
- const countryData = std.mem.trimRight(u8, originalCountryData, "\n\r\t ");
- var dataIt = std.mem.splitScalar(u8, countryData, ',');
- const countryName = dataIt.first();
- countries.put(countryName, Country{
- .name = countryName,
- .population = try std.fmt.parseFloat(f32, dataIt.next() orelse {
- return stdout.print("{s}{s}{s}", .{ "Failed to parse population for country `", countryName, "`.\n" });
- }),
- .isInEu = !std.mem.eql(u8, dataIt.next() orelse {
- return stdout.print("{s}{s}{s}", .{ "Failed to parse isInEu for country `", countryName, "`.\n" });
- }, "no"),
- .hasCoastline = !std.mem.eql(u8, dataIt.next() orelse {
- return stdout.print("{s}{s}{s}", .{ "Failed to parse hasCoastline for country `", countryName, "`.\n" });
- }, "no"),
- }) catch {
- return stdout.print("{s}{s}{s}", .{ "Failed to allocate memory for country `", countryName, "`.\n" });
- };
- }
- const citiesData = @embedFile("Cities.csv");
- var cities = try std.ArrayList(City).initCapacity(allocator, std.mem.count(u8, citiesData, "\n"));
- //var cities = std.ArrayList(City).init(allocator);
- defer cities.deinit();
- var cityIt = std.mem.splitScalar(u8, citiesData, '\n');
- _ = cityIt.first(); //Ignore header
- while (cityIt.next()) |originalcityData| {
- const cityData = std.mem.trimRight(u8, originalcityData, "\n\r\t ");
- var dataIt = std.mem.splitScalar(u8, cityData, ',');
- const cityName = dataIt.first();
- const new_city = try cities.addOne();
- new_city.* = .{
- .name = cityName,
- .country = countries.getPtr(dataIt.next() orelse {
- return stdout.print("{s}{s}{s}", .{ "Failed to parse country for city `", cityName, "`.\n" });
- }),
- .latitude = try std.fmt.parseFloat(f32, dataIt.next() orelse {
- return stdout.print("{s}{s}{s}", .{ "Expecting latitude city `", cityName, "`.\n" });
- }),
- .longitude = try std.fmt.parseFloat(f32, dataIt.next() orelse {
- return stdout.print("{s}{s}{s}", .{ "Expecting longitude for city `", cityName, "`.\n" });
- }),
- .temperature = try std.fmt.parseFloat(f32, dataIt.next() orelse {
- return stdout.print("{s}{s}{s}", .{ "Expecting temperature for city `", cityName, "`.\n" });
- }),
- };
- }
- try stdout.writeAll("All cities that are not in the EU and whose average temperatures are below 5.0:\n");
- for (cities.items) |city| {
- if (city.temperature < 5 and !(city.country orelse continue).isInEu)
- try stdout.print("{any}{c}", .{ city, '\n' });
- }
- try stdout.writeAll("Average temperature for all cities in Italy:\n");
- const avgItalyTemp = blk: {
- var count: usize = 0;
- var totalTemp: f32 = 0;
- for (cities.items) |city| {
- if (city.country) |cc| {
- if (std.mem.eql(u8, cc.name, "Italy")) {
- count += 1;
- totalTemp += city.temperature;
- }
- }
- }
- break :blk totalTemp / @as(f32, @floatFromInt(count));
- };
- try stdout.print("{d:.5}{c}", .{ avgItalyTemp, '\n' });
- const timeElapsed = timer.read();
- try stdout.print("{s}{d}{s}", .{ "Time elapsed: ", timeElapsed, " nanoseconds\n" });
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement