Skip to content

Instantly share code, notes, and snippets.

@Tofaa2
Created December 31, 2024 14:48
Show Gist options
  • Save Tofaa2/72efeee8fece854140c4a88e1ba5f501 to your computer and use it in GitHub Desktop.
Save Tofaa2/72efeee8fece854140c4a88e1ba5f501 to your computer and use it in GitHub Desktop.
const std = @import("std");
const int = i512;
const max_rank: i32 = 1000;
const Map = std.json.ArrayHashMap(int);
pub fn main() !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
const allocator = gpa.allocator();
//defer _ = gpa.deinit(); dont care;
var ranks = Map{};
for (1..@intCast(max_rank + 1)) |i| {
const buf = try usizeToStr(i, allocator);
try ranks.map.put(allocator, buf, try formula(@intCast(i), allocator, &ranks));
std.debug.print("Rank {} : {any}\n", .{ i, ranks.map.get(buf) });
//allocator.free(buf);
}
std.debug.print("Writing file data. Do not stop the program.\n", .{});
const file = try std.fs.cwd().createFile("ranks.json", .{});
defer file.close();
try std.json.stringify(ranks, .{}, file.writer());
std.debug.print("Done.\n", .{});
}
pub fn usizeToStr(v: usize, alloc: std.mem.Allocator) ![]const u8 {
return try std.fmt.allocPrint(alloc, "{d}", .{v});
}
pub fn formula(rank: i32, allocator: std.mem.Allocator, ranks: *Map) !int {
if (rank == 1) {
const buf = try usizeToStr(1, allocator);
try ranks.map.put(allocator, buf, formulaBase(rank));
const value = ranks.map.get(buf).?;
//allocator.free(value);
return value;
}
const cachedPreviousBuf = try usizeToStr(@as(usize, @intCast(rank)) - 1, allocator);
const cachedPrevious = ranks.map.get(cachedPreviousBuf).?;
const buf = try usizeToStr(@as(usize, @intCast(rank)), allocator);
try ranks.map.put(allocator, buf, cachedPrevious + formulaBase(rank));
const value = ranks.map.get(buf).?;
//allocator.free(cachedPrevious);
return value;
}
pub fn formulaBase(rank: i32) int {
const rankModed = @as(int, @intCast(rank));
return 30 * (rankModed * rankModed * rankModed) + 140 * (rankModed * rankModed) + 290 * rankModed + 1180;
}
@whosLevity
Copy link

based

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment