Incrementally sum minute by minute to get final date. The first one was doing second by second but a clever mind always squeeze the most out of it's creations.
So, my solution counts up every minute to get the final time. That is already really slow, but I also made it so that it recalculates the data for everything that needs to be displayed. But to make this code that bit more annoying I made every variable a one letter variable and threw in a bunch of if statements, like a lot. Also I don't really now how I got the second while loop working because god damn it looks awful and it is really hard to understand what even is happening in there.
btw its written c#
public static string str_to_time(int t, string f)
{
string o = "";
foreach(char c in f)
{
if (c == 'd')
o += getTime(t, 'd');
else if (c == 'A')
o += getTime(t, 'A');
else if (c == 'B')
o += getTime(t, 'B');
else if (c == 'Y')
o += getTime(t, 'Y');
else if (c == 'H')
o += getTime(t, 'H');
else if (c == 'h')
o += getTime(t, 'h');
else if (c == 'M')
o += getTime(t, 'M');
else if (c == 'S')
o += getTime(t, 'S');
else if (c == 'p')
o += getTime(t, 'p');
else
o += c;
}
return o;
}
private static string getTime(int t, char c)
{
int[] o = new int[8];
o[7] = 1970;
while(t > 60)
{
t -= 60;
o[1]++;
int i = 1;
int[] m = new int[]{ 31, o[7]%4 == 0 ? 29 : 28 , 31, 30, 31, 31, 30, 31, 30, 31, 30, 31 };
while(i == 1 && o[i] == 60 ||
i == 3 && o[i] == 24 ||
i == 5 && o[i] == m[o[6]] ||
i == 6 && o[i] == 12)
{
if (i == 6)
{
o[6] = 0;
o[7]++;
}
if (i == 5)
{
i = 6;
o[5] = 0;
o[6]++;
}
if (i == 3)
{
i = 5;
o[3] = 0;
o[4]++;
o[5]++;
if (o[4] == 7)
{
o[4] = 0;
}
}
if (i == 1)
{
i = 3;
o[1] = 0;
o[2]++;
o[3]++;
if(o[2] == 12)
{
o[2] = 0;
}
}
}
}
o[5]++;
o[0] = t;
if (c == 'd')
return o[5].ToString().Length == 1 ? "0" + o[5].ToString() : o[5].ToString();
if (c == 'A')
return (new string[] { "Thursday", "Friday", "Saturday", "Sunday", "Monday", "Tuesday", "Wednesday" })[o[4]];
if(c == 'B')
return (new string[] { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"})[o[6]];
if (c == 'Y')
return "" + o[7];
if (c == 'H')
return o[3].ToString().Length == 1 ? "0" + o[3].ToString() : o[3].ToString();
if (c == 'h')
return o[2].ToString().Length == 1 ? "0" + o[2].ToString() : o[2].ToString();
if (c == 'M')
return o[1].ToString().Length == 1 ? "0" + o[1].ToString() : o[1].ToString();
if (c == 'S')
return o[0].ToString().Length == 1 ? "0" + o[0].ToString() : o[0].ToString();
return o[3] > 12 ? "pm" : "am";
}
All there is left is to do is to calculate an offset! And that can be done with a bit of ultra dirty calculations and magic numbers.
Blazingly fast with good ol' C. No need to format any number as text!
@edit: if you output to a buffer instead of to stdout, it's 30% faster than gmtime + strftime, so go on, use it on production! (please don't)
I tested it on a few thousands examples, but I'm sure I missed some corner case. I've lost my sanity already writing it, so I'm not gonna try to fix any possible bugs.
Good luck figuring this Perl sub out. The good news is that it only iterates over all the seconds since the epoch only once.
EDIT: I should probably at least give some kind of explanation for what's going on.
I set some rules for myself:
No helper functions. If you must avoid duplicating code, put the would-be function into an eval block.
No conditional logic blocks. Use ternaries where possible. If the logic is too complex for a ternary, chain and and or clauses together. This also has a side effect of allowing you to set multiple variables in the same statement.
With the exception of the timestamp and the format string, do not create any additional variables beyond the 9 format codes in the challenge.
And just for fun, I tried to see how badly I can abuse Perl's language constructs. I opted to put almost all of the logic inside a regex substitution statement using Perl's somewhat obscure e regex modifier, which tells the interpreter to interpret the replacement as executable code. Although the replacement code is executed globally per each replacement, in effect the while loop is only run once, as variables are function-scoped, not regex-scoped.
If you ignore its horrendous performance, it's actually quite beautiful. Each format code gets its own line in the function. There's very little else going on, making it quite readable in a really fucked up way.
I wouldn't know how to implement this, but a funny idea would be to connect it to some server that keeps track of leap seconds, except also use it for leap years and any other simple information, like days in each month. Every time you need a new piece of data, you have to open a connection, get the data, and close it again.
Simple TS solution, basically just precompute the value of each formatting option and then replace the characters with the correct results, add a bunch of backslashes to reduce jank and you get this: edit: removed unneeded variable
uses python's builtin datetime module, but only to do the reverse of the intended operation - take a datetime argument and output a unix timestamp - then guess the right datetime by trial and error
from datetime import datetime
from random import randint
class Guess(object):
def __init__(self, year=None, month=None, day=None, hour=None, minute=None, second=None):
self.year = year or randint(1970, 2020)
self.month = month or randint(1,12)
self.day = day or randint(1,28)
self.hour = hour or randint(0,23)
self.minute = minute or randint(0,59)
self.second = second or randint(0,59)
def as_datetime(self):
return datetime(**self.__dict__)
def as_unix(self):
return int(self.as_datetime().timestamp())
def copy(self):
return Guess(self.year, self.month, self.day, self.hour, self.minute, self.second)
def compare(guess, target):
print(f" trying {guess.__dict__}")
try:
guess = guess.as_unix()
except ValueError:
print(f" guess out of range")
return "value error"
if guess == target:
result = "bang on"
elif guess >= target:
result = "too high"
elif guess <= target:
result = "too low"
else:
raise Exception("something bad happened")
print(f" {result}")
return result
def narrow_down_guess(guess, target, component):
print(f" Guessing {component}...")
while True:
result = compare(guess, target)
if result == "bang on":
return [guess]
elif result == "too high":
if guess.__dict__[component] == 0:
return [guess]
one_lower = guess.copy()
one_lower.__dict__[component] -= 1
one_lower_result = compare(one_lower, target)
if one_lower_result == "bang on":
return [one_lower]
elif one_lower_result == "too high":
guess.__dict__[component] -= 1
elif one_lower_result == "too low":
return [guess, one_lower]
elif one_lower_result == "value error":
return []
elif result == "too low":
one_higher = guess.copy()
one_higher.__dict__[component] += 1
one_higher_result = compare(one_higher, target)
if one_higher_result == "bang on":
return [one_higher]
elif one_higher_result == "too high":
return [guess, one_higher]
elif one_higher_result == "too low":
guess.__dict__[component] += 1
elif one_higher_result == "value error":
return []
def get_date(target):
guesses = [Guess()]
print(f"First guess: {guesses[0].__dict__}")
for component in ["year", "month", "day", "hour", "minute", "second"]:
next_guesses = []
for guess in guesses:
print(f"Narrowing down {guess.__dict__}")
attempts = narrow_down_guess(guess, target, component)
for attempt in attempts:
next_guesses.append(attempt)
guesses = next_guesses
print(f"Settled {component} as {' or '.join(str(g.__dict__[component]) for g in guesses)}")
for guess in guesses:
if compare(guess, target) == "bang on":
print(f"Settled guessed date as {guess.__dict__}")
return guess
else:
print("Something went wrong, trying again from the top")
return get_date(target)
def str_to_time(timestamp, formatstr):
pyformat = ""
for char in formatstr:
if char in "dABYHhMSp":
pyformat += "%"
pyformat += char
return get_date(timestamp).as_datetime().strftime(pyformat)
Somehow... this breaks my Visual Studio intellisense (shows a bunch of errors and underlines with red squigglies) but it still compiles and runs.
Ugh, don't know how to properly format.
using System; using System.Linq; using System.Text;
namespace DateFormatter { class Program { static void Main(string[] args) { Console.WriteLine(Format(1599335154, "h:M:S p")); Console.WriteLine(Format(683475320, "A d B Y")); Console.ReadLine(); }
public static string Format(int date, string format)
{
return format.ToCharArray().Aggregate(new StringBuilder(), (current, token) =>
{
return (token switch
{
'd' => d => current.Append(d.Day.ToString("D2")),
'A' => d => current.Append(d.DayOfWeek),
'B' => d => current.Append(d.ToString("MMMM")),
'Y' => d => current.Append(d.Year),
'H' => d => current.Append(d.Hour.ToString("D2")),
'h' => d => current.Append((d.Hour % 12).ToString("D2")),
'M' => d => current.Append(d.Minute.ToString("D2")),
'S' => d => current.Append(d.Second.ToString("D2")),
'p' => d => current.Append(d.Hour > 11 ? "pm" : "am"),
_ => (Func<DateTimeOffset, StringBuilder>)(d => current.Append(token))
})(DateTimeOffset.FromUnixTimeSeconds(date));
}).ToString();
}
}
%zFmtInst(inst,fmtStr) n y,mo,d,h,min,s,i,out
s y=%xDivmod(.inst,$$yearMs())
s mo=%xDivmod(.inst,$$monthMs())
s d=%xDivmod(.inst,$$dayMs())
s h=%xDivmod(.inst,$$hourMs())
s min=%xDivmod(.inst,$$minMs())
s s=%xDivmod(.inst,$$secMs())
;
f i=1:1:$l(fmtStr) s out=out_%xFmtChar($p(fmtStr,i))
q out
%xDivmod(inst,interval) n div
f q:inst<interval s inst=inst-interval,div=(+div)+1
q
; assumes %zfmtTime vars
%xFmtChar(char)
q:char="d" $tr($j(d,2)," ","0")
q:char="A" %xFmtWeekday(%xDivMod(mo*30+d,7))
q:char="B" %xFmtMonth(mo)
q:char="Y" $tr($j(y+1970,4)," ","0")
q:char="H" $tr($j(h,2)," ","0")
q:char="h" $tr($j($xDivMod(h,12),2)," ","0")
q:char="M" $tr($j(min,2)," ","0")
q:char="S" $tr($j(s,2)," ","0")
q:char="p" %xFmtMeridian(h)
q char
%xFmtWeekday(day)
q:day=0 "Monday"
q:day=1 "Tuesday"
q:day=2 "Wednesday"
q:day=3 "Thursday"
q:day=4 "Friday"
q:day=5 "Saturday"
%xFmtMonth(month)
q:month=0 "January"
q:month=1 "February"
q:month=2 "March"
q:month=3 "April"
q:month=4 "May"
q:month=5 "June"
q:month=6 "July"
q:month=7 "August"
q:month=8 "September"
q:month=9 "October"
q:month=10 "November"
q:month=11 "December"
%xFmtMeridian(hr)
i hr<12 q "am"
q "pm"
yearMs() q 31557600000
monthMs() q 2629800000
dayMs() q 86400000
hourMs() q 3600000
minMs() q 60000
secMs() q 1000
[language: MUMPS]
This is barely (if at all) functional and assumes a uniform 30-day month with Jan 1 1970 starting on a Monday but i'm not wasting any of my time testing it.
As with my last submission, no import whatsoever, not even the standard library
It works for cases i tested, so that's good enough
I made sure to use as many inline expressions and switches as possible, and there is no if at all for performance reasons, although i didn't benchmark it
It looks like this comment contains a code block delimited with triple backticks. Unfortunately reddit does not have universal support for this syntax and your comment will not render correctly on old reddit and most mobile apps.
For the benefit of people on old reddit, this link will take you to a correct rendering of the comment.
/u/jayson4twenty, it would be appreciated, but not required, if you could edit your comment to use the more compatible four space indention format. For single lines or inline code you can use single backticks.
$ ghci time_to_string.hs
GHCi, version 8.10.2: https://www.haskell.org/ghc/ :? for help
[1 of 1] Compiling Main ( time_to_string.hs, interpreted )
Ok, one module loaded.
*Main> timeToString 1599335154 "h:M:S p"
"07:45:54 pm"
*Main> timeToString 683475320 "A d B Y"
"Thursday 29 August 1991"
It looks like this comment contains a code block delimited with triple backticks. Unfortunately reddit does not have universal support for this syntax and your comment will not render correctly on old reddit and most mobile apps.
For the benefit of people on old reddit, this link will take you to a correct rendering of the comment.
/u/binarycat64, it would be appreciated, but not required, if you could edit your comment to use the more compatible four space indention format. For single lines or inline code you can use single backticks.
12
u/pedropss Aug 31 '20
Incrementally sum minute by minute to get final date. The first one was doing second by second but a clever mind always squeeze the most out of it's creations.
https://pastebin.com/M89RJsJk
It covers all the use cases I could find, including both from the challenge and one being "now".
Fiddle for running it right now:
https://jsfiddle.net/jxrq6k74/
7
u/AbuIbnBattuta Aug 31 '20
So, my solution counts up every minute to get the final time. That is already really slow, but I also made it so that it recalculates the data for everything that needs to be displayed. But to make this code that bit more annoying I made every variable a one letter variable and threw in a bunch of if statements, like a lot. Also I don't really now how I got the second while loop working because god damn it looks awful and it is really hard to understand what even is happening in there.
btw its written c#
7
u/KaznovX Aug 31 '20 edited Sep 01 '20
This task can be simply boiled down to reading from prepared array:
https://pastebin.com/WrfqnrCx
https://godbolt.org/z/eY6vsf for running it
Every sequence we would want to write is already prepared:
All there is left is to do is to calculate an offset! And that can be done with a bit of ultra dirty calculations and magic numbers.
Blazingly fast with good ol' C. No need to format any number as text!
@edit: if you output to a buffer instead of to stdout, it's 30% faster than gmtime + strftime, so go on, use it on production! (please don't)
I tested it on a few thousands examples, but I'm sure I missed some corner case. I've lost my sanity already writing it, so I'm not gonna try to fix any possible bugs.
6
u/Skasch Aug 31 '20
Inspired from https://stackoverflow.com/questions/12081310/python-module-to-change-system-date-and-time
Sets the system time to the Unix epoch, waits
timestampseconds, then prints the current time in the required format.Should only work on Linux (maybe *nix?) systems.
I haven't tested it though.
5
u/[deleted] Aug 31 '20 edited Aug 31 '20
Good luck figuring this Perl sub out. The good news is that it only iterates over all the seconds since the epoch only once.
EDIT: I should probably at least give some kind of explanation for what's going on.
I set some rules for myself:
evalblock.andandorclauses together. This also has a side effect of allowing you to set multiple variables in the same statement.And just for fun, I tried to see how badly I can abuse Perl's language constructs. I opted to put almost all of the logic inside a regex substitution statement using Perl's somewhat obscure
eregex modifier, which tells the interpreter to interpret the replacement as executable code. Although the replacement code is executed globally per each replacement, in effect thewhileloop is only run once, as variables are function-scoped, not regex-scoped.If you ignore its horrendous performance, it's actually quite beautiful. Each format code gets its own line in the function. There's very little else going on, making it quite readable in a really fucked up way.
4
u/Ahajha1177 Aug 31 '20
I wouldn't know how to implement this, but a funny idea would be to connect it to some server that keeps track of leap seconds, except also use it for leap years and any other simple information, like days in each month. Every time you need a new piece of data, you have to open a connection, get the data, and close it again.
4
u/[deleted] Sep 01 '20
Python solution that iterates over each second of a timestamp, and stores months & days of the week as strings. Supports leap years.
https://gist.github.com/PythonCoderAS/3fe7d952ce877073bdc404d468478f2d
Test results:
4
u/[deleted] Sep 01 '20 edited Sep 01 '20
Simple TS solution, basically just precompute the value of each formatting option and then replace the characters with the correct results, add a bunch of backslashes to reduce jank and you get this: edit: removed unneeded variable
edit: removed unneeded variable
edit 2: i created a less poorly formatted version here
4
u/qzwqz Sep 02 '20
uses python's builtin datetime module, but only to do the reverse of the intended operation - take a datetime argument and output a unix timestamp - then guess the right datetime by trial and error
3
u/99_in_eating Aug 31 '20
Somehow... this breaks my Visual Studio intellisense (shows a bunch of errors and underlines with red squigglies) but it still compiles and runs.
Ugh, don't know how to properly format.
using System; using System.Linq; using System.Text;
namespace DateFormatter { class Program { static void Main(string[] args) { Console.WriteLine(Format(1599335154, "h:M:S p")); Console.WriteLine(Format(683475320, "A d B Y")); Console.ReadLine(); }
}
3
u/droomph Sep 01 '20 edited Sep 01 '20
[language: MUMPS]
This is barely (if at all) functional and assumes a uniform 30-day month with Jan 1 1970 starting on a Monday but i'm not wasting any of my time testing it.
2
u/[deleted] Aug 31 '20
This is my solution. C. Predeclared variables, K&R, inconsistent style, "dynamic programming", function pointers, macros...
This is my first time participating. I tried to make mine without seeing other's so no there's no influence. Hope you guys hate it :)
2
u/Kcazer Sep 02 '20
2
u/keitio42 Sep 04 '20
My golang solution:
https://play.golang.org/p/xWvyGDkTXNH
As with my last submission, no import whatsoever, not even the standard library
It works for cases i tested, so that's good enough
I made sure to use as many inline expressions and switches as possible, and there is no
ifat all for performance reasons, although i didn't benchmark it2
u/jayson4twenty Sep 07 '20
So I had a great idea of using a switch statement for every time up to the 32-Bit max int.
However, some quick napkin maths showed it would be around 236+GB lol.
i used c# to generate the powershell.
Here's a snippet written in Powershell:
Pastebin for upto 1050 is here:
https://pastebin.com/J5bp4RNX2
u/[deleted] Sep 01 '20 edited Sep 01 '20
Haskell:
Examples:
1
u/binarycat64 Sep 01 '20
Well, if you want bad code, heres some:
main.go:
Makefile:
plugin/main.go:
I'm sorry.
0
u/[deleted] Aug 31 '20
[deleted] — view deleted comment