[a / b / c / d / e / f / g / gif / h / hr / k / m / o / p / r / s / t / u / v / vg / vm / vmg / vr / vrpg / vst / w / wg] [i / ic] [r9k / s4s / vip] [cm / hm / lgbt / y] [3 / aco / adv / an / bant / biz / cgl / ck / co / diy / fa / fit / gd / hc / his / int / jp / lit / mlp / mu / n / news / out / po / pol / pw / qst / sci / soc / sp / tg / toy / trv / tv / vp / vt / wsg / wsr / x / xs] [Settings] [Search] [Mobile] [Home]
Board
Settings Mobile Home
/g/ - Technology


Thread archived.
You cannot reply anymore.


[Advertise on 4chan]


File: GLG9NYkaMAAHnZY.png (10 KB, 576x538)
10 KB
10 KB PNG
Rewrite this program in your language of choice.
Standard library only.
Programs that don't fit into a post are automatically disqualified.

from datetime import datetime
from json import loads, dump
from pathlib import Path
from sys import argv


JSON_PATH = "./data.json"


def write_json(json, path_string):
with open(path_string, "w", encoding="utf-8") as f:
dump(json, f, indent=2)


def print_stats(json):
print(f"Reps: {json['reps']}\nSets: {json['sets']}")


def main():
args = argv[1:]

if not Path(JSON_PATH).exists():
write_json(loads('{"sets": 0, "reps": 0, "history": {}}'), JSON_PATH)

json = loads(Path(JSON_PATH).read_text(encoding="utf-8"))

if not args:
print_stats(json)
else:
for a in args:
a = int(a)

json["sets"] = json["sets"] + 1
json["reps"] = json["reps"] + a

now = datetime.now()
json["history"][json["sets"]] = {
"date": f"{now.year}-{now.month:02d}-{now.day:02d}",
"count": a,
}

write_json(json, JSON_PATH)
print_stats(json)


if __name__ == "__main__":
main()

$ python program.py 16 32 64
Reps: 112
Sets: 3
$ cat data.json
{
"sets": 3,
"reps": 112,
"history": {
"1": {
"date": "2025-10-08",
"count": 16
},
"2": {
"date": "2025-10-08",
"count": 32
},
"3": {
"date": "2025-10-08",
"count": 64
}
}
}
>>
>>106829932
Damn brat...
>>
File: nope f205111792.gif (1.02 MB, 600x352)
1.02 MB
1.02 MB GIF
>>106829932
>help me do my homework /g/
>>
File: 1717199642418607.webm (320 KB, 360x360)
320 KB
320 KB WEBM
>>106829932
I am not doing your homework
>>
>>106829932
@grok can you do this
>>
File: GVbpkNRaMAAfekQ.png (12 KB, 665x581)
12 KB
12 KB PNG
>complete program posted
>no restrictions on the language
>dat ur homework doe!!
Be big boys and just say that you can't do it with your shitlangs without relying on half a dozen of third-party libraries or reinventing the wheel for hundreds of LoC.
>>
File: copilot.png (123 KB, 1024x1024)
123 KB
123 KB PNG
Here’s a faithful C# rewrite of your Python program, using only the standard library (System, System.IO, System.Text.Json). It’s compact enough to fit into a 4chan post:
using System;
using System.IO;
using System.Text.Json;
using System.Collections.Generic;

class Program
{
const string JsonPath = "./data.json";

class HistoryEntry
{
public string date { get; set; }
public int count { get; set; }
}

class Data
{
public int sets { get; set; }
public int reps { get; set; }
public Dictionary<int, HistoryEntry> history { get; set; }
}

static void WriteJson(Data data, string path)
{
var opts = new JsonSerializerOptions { WriteIndented = true };
File.WriteAllText(path, JsonSerializer.Serialize(data, opts));
}

static void PrintStats(Data data)
{
Console.WriteLine($"Reps: {data.reps}\nSets: {data.sets}");
}

static void Main(string[] args)
{
if (!File.Exists(JsonPath))
{
var init = new Data { sets = 0, reps = 0, history = new Dictionary<int, HistoryEntry>() };
WriteJson(init, JsonPath);
}

var json = File.ReadAllText(JsonPath);
var data = JsonSerializer.Deserialize<Data>(json);

if (args.Length == 0)
{
PrintStats(data);
return;
}

foreach (var a in args)
{
if (!int.TryParse(a, out int val)) continue;

data.sets++;
data.reps += val;

var now = DateTime.Now;
data.history[data.sets] = new HistoryEntry
{
date = $"{now:yyyy-MM-dd}",
count = val
};
}

WriteJson(data, JsonPath);
PrintStats(data);
}
}
>>
>>106835485
>>
>>106835485
>all small property names
wew
should have asked it to use records with primary constructors instead of regular classes, that would save like 8 lines
>>
File: 1000039423.jpg (79 KB, 1000x1000)
79 KB
79 KB JPG
>>106829932
```
args=($@);
for i in $@; do reps=$((reps+i)); sets=$((sets+1)); done;
echo -e "Reps: $reps\nSets: $sets";
date=$(date --iso);
echo -en '{\n "sets": '$sets',\n "reps": '$reps',\n "history": {' > data.json;
for i in $(seq ${#args[@]}); do
ii=${args[$i-1]};
echo -en '\n "'$i'": {\n "date": "'$date'",\n "count": '$ii'\n }' >> data.json;
if [ $i -lt ${#args[@]} ]; then echo -n ',' >> data.json; fi;
done;
echo -e '\n }\n}' >> data.json;
```

$ bash program.sh 16 32 64
```
Reps: 112
Sets: 3
```
$ cat data.json
```
{
"sets": 3,
"reps": 112,
"history": {
"1": {
"date": "2025-10-09",
"count": 16
},
"2": {
"date": "2025-10-09",
"count": 32
},
"3": {
"date": "2025-10-09",
"count": 64
}
}
}
```
>>
# nigger.rb
require 'json'
require 'date'

JSON_PATH = './data.json'

def print_stats(j)
puts "Reps: #{j['reps']}\nSets: #{j['sets']}"
end

unless File.exist?(JSON_PATH)
File.write(JSON_PATH, JSON.pretty_generate({'sets' => 0, 'reps' => 0, 'history' => {}}))
end

j = JSON.parse(File.read(JSON_PATH))
args = ARGV

if args.empty?
print_stats(j)
else
args.each do |a|
n = Integer(a)
j['sets'] += 1
j['reps']
>>
>>106836277
piece of shit fucking website omg
# nigger.rb
require 'json'
require 'date'

JSON_PATH = './data.json'

def print_stats(j)
puts "Reps: #{j['reps']}\nSets: #{j['sets']}"
end

unless File.exist?(JSON_PATH)
File.write(JSON_PATH, JSON.pretty_generate({'sets' => 0, 'reps' => 0, 'history' => {}}))
end

j = JSON.parse(File.read(JSON_PATH))
args = ARGV

if args.empty?
print_stats(j)
else
args.each do |a|
n = Integer(a)
j['sets'] += 1
j['reps'] += n
date = Date.today.strftime('%Y-%m-%d')
j['history'][j['sets'].to_s] = { 'date' => date, 'count' => n }
end
File.write(JSON_PATH, JSON.pretty_generate(j))
print_stats(j)
end
>>
>>106829932
>>106834253
will bratty miku have sex with me if I do?
>>
>>106835485
>It’s compact enough to fit into a 4chan post:
GPT
>>
>>106836277
tim toady upon thee:
#!/usr/bin/env perl
use strict;
use warnings;
use JSON::PP qw(decode_json);
use Time::Piece;

my $JSON_PATH = './data.json';

sub write_json {
my ($data) = @_;
open my $fh, '>:encoding(UTF-8)', $JSON_PATH or die "Can't write $JSON_PATH: $!";
print $fh JSON::PP->new->pretty->encode($data);
close $fh;
}

sub print_stats {
my ($d) = @_;
print "Reps: $d->{reps}\nSets: $d->{sets}\n";
}

my $data;
if (-e $JSON_PATH) {
open my $fh, '<:encoding(UTF-8)', $JSON_PATH or die "Can't read $JSON_PATH: $!";
local $/;
my $txt = <$fh> // '';
close $fh;
$data = eval { decode_json($txt) } || { sets => 0, reps => 0, history => {} };
} else {
$data = { sets => 0, reps => 0, history => {} };
write_json($data);
}

if (@ARGV) {
for my $a (@ARGV) {
my $n = int($a);
$data->{sets}++;
$data->{reps} += $n;
my $date = localtime->strftime('%Y-%m-%d');
$data->{history}{ $data->{sets} } = { date => $date, count => $n };
}
write_json($data);
}

print_stats($data);
>>
File: GSDM9IHbIAAe65K.png (15 KB, 746x621)
15 KB
15 KB PNG
>>106835485
C# is pretty nice and comfy based on my limited experience with it, too bad it's a Microsoft product.
using System.Text.Json;

const string JsonPath = "./data.json";


Main(Environment.GetCommandLineArgs());


static void WriteJson(Data data, string path)
{
var opts = new JsonSerializerOptions { WriteIndented = true };
File.WriteAllText(path, JsonSerializer.Serialize(data, opts));
}

static void PrintStats(Data data)
{
Console.WriteLine($"Reps: {data.Reps}\nSets: {data.Sets}");
}

static void Main(string[] args)
{
if (!File.Exists(JsonPath))
{
var init = new Data { Sets = 0, Reps = 0, History = new Dictionary<int, HistoryEntry>() };
WriteJson(init, JsonPath);
}

var json = File.ReadAllText(JsonPath);
var data = JsonSerializer.Deserialize<Data>(json);

if (args.Length == 0)
{
PrintStats(data);
return;
}

foreach (var a in args)
{
if (!int.TryParse(a, out int val)) continue;

data.Sets++;
data.Reps += val;

var now = DateTime.Now;
data.History[data.Sets] = new HistoryEntry($"{now:yyyy-MM-dd}", val);
}
WriteJson(data, JsonPath);
PrintStats(data);
}

class Data
{
public int Sets { get; set; }
public int Reps { get; set; }
public required Dictionary<int, HistoryEntry> History { get; set; }
}

record HistoryEntry(string Date, int Count);


>>106836229
Hideous and concise, as expected.
Doesn't format properly, doesn't initialize data.json properly, but OK, you passed.
>>
File: daria.jpg (123 KB, 1119x839)
123 KB
123 KB JPG
function workout(reps)
arguments (Repeating)
reps int32
end
JSON_PATH = "./data.json";

if ~isfile(JSON_PATH)
json = struct(sets=int32(0), reps=int32(0), history={struct(date={}, count={})});
else
json = readstruct(JSON_PATH);
end
if ~isempty(reps)
for a = cell2mat(reps)
json.sets = json.sets + 1;
json.reps = json.reps + a;
date = datetime('today', format='yyyy-MM-dd');
json.history(end+1) = struct(date=date, count=a);
writestruct(json, JSON_PATH);
end
end
fprintf("Reps: %i\nSets: %i\n", json.reps, json.sets);
end
>>
File: GRkK4qzbYAA9LTK.png (15 KB, 806x772)
15 KB
15 KB PNG
>>106836302
Maybe.

>>106836294
Nice. Now do it in Elixir.

>>106836469
The Ruby version mogs this, sorry.

>>106838369
Is this...MATLAB?
>>
File: 1759078442032280.png (1.51 MB, 1566x729)
1.51 MB
1.51 MB PNG
<?php

const JSON_PATH = "./data.json";

main();


function writeJson($data, $path)
{
file_put_contents($path, json_encode($data, JSON_PRETTY_PRINT));
}


function printStats($data)
{
echo "Reps: {$data['reps']}\nSets: {$data['sets']}";
}


function main()
{
global $argv;
$args = array_slice($argv, 1);

if (!is_file(JSON_PATH)) {
writeJson(json_decode('{"sets": 0, "reps": 0, "history": {}}'), JSON_PATH);
}

$data = json_decode(file_get_contents(JSON_PATH), true);

if (!$args) {
printStats($data);
} else {
foreach ($args as $arg) {
$arg = (int) $arg;
$data["sets"] = $data["sets"] + 1;
$data["reps"] = $data["reps"] + $arg;

$data["history"][$data["sets"]] = [
"date" => date("Y-m-d"),
"count" => $arg
];
}

writeJson($data, JSON_PATH);
printStats($data);
}
}

>>
>>106838744
>MATLAB
It's just Matlab now
>>
>>106838838
Oh wait that's Fortran, I guess it is still MATLAB
>>
Error checks? None

```go
// main.go

package main

import (
"encoding/json"
"fmt"
"os"
"strconv"
"time"
)

const JSON_PATH = "./data.json"

type HistoryEntry struct {
Date string `json:"date"`
Count int `json:"count"`
}

type Data struct {
Sets int `json:"sets"`
Reps int `json:"reps"`
History map[string]HistoryEntry `json:"history"`
}

func writeJson(data any) {
converted, _ := json.MarshalIndent(data, "", " ")
os.WriteFile(JSON_PATH, converted, 0644)
}

func printStats(data Data) {
fmt.Printf("Reps: %d\nSets: %d\n", data.Reps, data.Sets)
}

func main() {
args := os.Args[1:]

if _, err := os.Stat(JSON_PATH); os.IsNotExist(err) {
writeJson(Data{History: make(map[string]HistoryEntry)})
}

d, _ := os.ReadFile(JSON_PATH)
data := Data{}
json.Unmarshal(d, &data)

if len(args) <= 0 {
printStats(data)
} else {
for _, a := range args {
aInt, _ := strconv.Atoi(a)

data.Sets++
data.Reps += aInt

now := time.Now()

data.History[strconv.Itoa(data.Sets)] = HistoryEntry{
Date: now.Format("2006-01-02"),
Count: aInt,
}
}
writeJson(data)
printStats(data)
}
}
```
>>
fucking non-Markdown compliant shit

>>106839821
Error-checked version:

[code=go]
// main.go

package main

import (
"encoding/json"
"fmt"
"os"
"strconv"
"time"
)

const JSON_PATH = "./data.json"

type HistoryEntry struct {
Date string `json:"date"`
Count int `json:"count"`
}

type Data struct {
Sets int `json:"sets"`
Reps int `json:"reps"`
History map[string]HistoryEntry `json:"history"`
}

func writeJson(data any) error {
converted, err := json.MarshalIndent(data, "", " ")
if err != nil {
return err
}
return os.WriteFile(JSON_PATH, converted, 0644)
}

func printStats(data Data) {
fmt.Printf("Reps: %d\nSets: %d\n", data.Reps, data.Sets)
}

func main() {
args := os.Args[1:]

if _, err := os.Stat(JSON_PATH); os.IsNotExist(err) {
if writeJson(Data{History: make(map[string]HistoryEntry)}) != nil {
fmt.Printf("Error: %v\n", err)
os.Exit(1)
}
} else {
if err != nil {
fmt.Printf("Error: %v\n", err)
os.Exit(2)
}
}

d, err := os.ReadFile(JSON_PATH)
if err != nil {
fmt.Printf("Error: %v\n", err)
os.Exit(3)
}
data := Data{}
err = json.Unmarshal(d, &data)
if err != nil {
fmt.Printf("Error: %v\n", err)
os.Exit(4)
}

if len(args) <= 0 {
printStats(data)
} else {
for _, a := range args {
aInt, _ := strconv.Atoi(a)

data.Sets++
data.Reps += aInt

now := time.Now()

data.History[strconv.Itoa(data.Sets)] = HistoryEntry{
Date: now.Format("2006-01-02"),
Count: aInt,
}
}
if writeJson(data) != nil {
fmt.Printf("Error: %v\n", err)
os.Exit(5)
}
printStats(data)
}
}
[/code]
>>
>>106839903
damn son this shit's long af
>>
File: 1747375020867124.png (85 KB, 264x294)
85 KB
85 KB PNG
import fs from 'node:fs'

const init = { sets: 0, reps: 0, history: {} }
const func = (...args) =>
args.reduce((acc, value, index) => {
const date = new Date()
acc.sets += 1
acc.reps += Number(value)
acc.history[index + 1] = {
date: `${date.getFullYear()}-${date
.getDate()
.toString()
.padStart(2, '0')}-${
Number(date.getMonth().toString().padStart(2, '0')) + 1
}`,
count: value,
}
return acc
}, init)

const args = process.argv.slice(2)
const result = func(...args)
args.length
? fs.writeFileSync('data.json', JSON.stringify(result, null, 2))
: fs.writeFileSync('data.json', JSON.stringify(init, null, 2))
console.log(`Sets: ${result.sets}\nReps: ${result.reps}`)


Date is love.
>>
>>106840328
Oops, looks like func return the init if given no arguments anyway so the args.length ternary is redundant.
>>
>>106840370
import fs from 'node:fs';

const func = (...args) =>
args.reduce(
(acc, value, index) => {
const date = new Date();
acc.sets += 1;
acc.reps += Number(value);
acc.history[index + 1] = {
date: `${date.getFullYear()}-${date
.getDate()
.toString()
.padStart(2, "0")}-${
Number(date.getMonth().toString().padStart(2, "0")) + 1
}`,
count: Number(value),
};
return acc;
},
{ sets: 0, reps: 0, history: {} },
);

const args = process.argv.slice(2);
const result = func(...args)
fs.writeFileSync('data.json', JSON.stringify(result, null, 2))
console.log(`Sets: ${result.sets}\nReps: ${result.reps}`)

Fix'd
>>
>>106829932
make sure to use -std=gnu89
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
typedef struct{char*n;int r;struct tm t;}S;
typedef struct{int s,r;S**h;}W;
S*wp(W*w,char*n){
int i=0;
for(;w->h && w->h[i];i++);
w->h=realloc(w->h,(i+2)*8);
w->h[i]=malloc(sizeof(S));
if(!n)
n=malloc(100),sprintf(n,"%d",i);
w->h[i+1]=0;
w->h[i]->n=n;
return w->h[i];
}
jk(FILE*fp,char*b){
char c;
fscanf(fp," %c",&c);
if(fscanf(fp," \"%[^\"]\" :",b) == 1)
return 1;
fscanf(fp,"}");
return 0;
}
sr(FILE*fp,S*s){
char b[99];
while(jk(fp,b)){
if(!strcmp(b,"count")){
fscanf(fp," %d",&s->r);
}
if(!strcmp(b,"date")){
fscanf(fp," \"%[^\"]\"",b);
strptime(b,"%Y-%02m-%02d",&s->t);
}
}
}
wr(FILE*fp,W*w){
char b[99];
while(jk(fp,b)){
if(!strcmp(b,"sets"))
fscanf(fp," %d",&w->s);
if(!strcmp(b,"reps"))
fscanf(fp," %d",&w->r);
if(!strcmp(b,"history")){
while(jk(fp,b)){
sr(fp,wp(w,strdup(b)));
}
}
}
}
char*fn="./data.json";
main(int argc,char**argv){
int i;
FILE*fp=fopen(fn, "r+");
W w={0};
if(fp) wr(fp,&w),fclose(fp);
for(i=1; i<argc; i++){
int r=atoi(argv[i]);
w.s++,w.r+=r;
S*s=wp(&w,0);
s->r=r;
time_t t=time(0);
s->t=*localtime(&t);
}
printf("Reps: %d\nSets: %d\n", w.r, w.s);
fp=fopen(fn,"w+");
fprintf(fp,"{\"sets\":%d,\"reps\":%d,\"history\":{",w.s,w.r);
for(i=0;w.h && w.h[i];i++){
S s=*w.h[i];
char buf[99];
strftime(buf,99,"%Y-%02m-%02d",&s.t);
fprintf(fp,"\"%s\":{\"date\":\"%s\",\"count\":%d}%s",s.n,buf,s.r,w.h[i+1]?",":"}}");
}
}
>>
op actually thought this would be difficult lmao
>>
{
currentDir,
argv,
file ? null,
...
}:
let
lib = import <nixpkgs/lib>;
d = final: {
history = if lib.pathExists file then (builtins.fromJSON (builtins.readFile file)).history else { };
inherit
(builtins.foldl'
(
acc: elem:
acc
// {
sets = acc.sets + 1;
reps = acc.reps + elem.count;
}
)
{
sets = 0;
reps = 0;
}
(builtins.attrValues final.history)
)
sets
reps
;
};

overlay = final: prev: {
history =
prev.history
// (builtins.listToAttrs (
lib.imap1 (
i: v:
lib.nameValuePair (toString (i + (builtins.length (builtins.attrValues prev.history)))) {
date = builtins.currentTime;
count = lib.toInt v;
}
) (builtins.tail argv)
));
};
in
builtins.toJSON (lib.fix (lib.extends overlay d))

$ nint --arg file ./data.json ./a.nix 16 32 64 | jq '.history |= map_values(.date |= strftime("%Y-%m-%d"))'
{
"history": {
"1": {
"count": 16,
"date": "2025-10-09"
},
"2": {
"count": 32,
"date": "2025-10-09"
},
"3": {
"count": 64,
"date": "2025-10-09"
}
},
"reps": 112,
"sets": 3
}
bunch of concessions done here (mainly obviously no file-writing since this Nix interpreter doesn't allow for side-effects) as you can see but I thought it was fun to try and give it a go.
>>
>>106840683
>cnile posts minified code
As expected
>>
>>106841105
I thought I was going to need to golf it but I had tons of bytes to spare. Json parsing in c is too easy, very sad.



[Advertise on 4chan]

Delete Post: [File Only] Style:
[Disable Mobile View / Use Desktop Site]

[Enable Mobile View / Use Mobile Site]

All trademarks and copyrights on this page are owned by their respective parties. Images uploaded are the responsibility of the Poster. Comments are owned by the Poster.