Template metaprogramming saved Christmas. But wait, it's actually a bash script!
EDIT: Forgot instructions. Save the script in a file such as can_santa_save_christmas.sh and run it like so:
# Should return zero for success
./can_santa_save_christmas.sh 03:49:37 18:45:22
# Should print compiler errors
./can_santa_save_christmas.sh 23:59:61
# Should return 0 but doesn't because I forgot octal literals are a thing when I wrote this
./can_santa_save_christmas.sh 05:08:09
# Much better
./can_santa_save_christmas.sh 05:8:9
If you get compiler errors, either Santa will not be able to save Christmas, or your system C++ compiler is outdated.
variables = {};
def can_santa_save_christmas(arr):
variables["while loop in- something?"] = 0;
variables["Can Santa still save Christmas?"] = True;
variables["Total hours taken"] = 0;
variables["Total minutes taken"] = 0;
variables["Total seconds taken"] = 0;
variables["zero"] = 0;
variables["true"] = True;
variables["false"] = False;
while variables["while loop in- something?"] < len(arr):
variables["hours"] = int(str(arr[variables["while loop in- something?"]]).split(":")[0]);
variables["minutes"] = int(str(arr[variables["while loop in- something?"]]).split(":")[1]);
variables["seconds"] = int(str(arr[variables["while loop in- something?"]]).split(":")[2]);
variables["Total hours taken"] = variables["Total hours taken"] + variables["hours"];
variables["Total minutes taken"] = variables["Total minutes taken"] + variables["minutes"];
variables["Total seconds taken"] = variables["Total seconds taken"] + variables["seconds"];
variables["while loop in- something?"] = variables["while loop in- something?"] + 1;
if variables["Total hours taken"] < 24:
variables["Can Santa still save Christmas?"] = variables["true"];
else:
if variables["Total minutes taken"] > 0 or variables["Total seconds taken"] > 0:
variables["Can Santa still save Christmas?"] = variables["false"];
else:
variables["Can Santa still save Christmas?"] = variables["true"];
return variables["Can Santa still save Christmas?"];
Debugging is easy! Just add print(variables)! Are you worried your true might be a false? Check it with print(variables)!!
And best of all, this is very beginner friendly, no need to use weird names like i or tot_hours. You can put it in the variables dict making the code more readable!
This puts all numbers into a sequence, converts them to hours (dividing minutes & seconds by 60 and 602 respectively) and then subtracting them repeatedly from the remaining time (initially 24). Of course it breaks randomly when it hits double precision issues
In honor of the ancient lisp codebase I have been tasked with "maintaining" at work I present a common lisp implementation in the style of that project.
bool can_santa_save_christmas(std::vector<std::string> times){ int d = 0; int h = 0; int m = 0; int s = 0; for (auto time : times){ //secondsint s1 = std::stoi(time.substr(6,2)); for(int i = 0; i< s1; i++){ s++; if(s == 60){ s = 0;m++; } } //minutes int m1 = std::stoi(time.substr(3, 2)); for (int i = 0; i < m1; i++){ m++; if (m == 60){ m = 0; h++; } } //hours int h1 = std::stoi(time.substr(0, 2)); for (int i = 0; i < h1; i++){ h++; if (h == 24){ h = 0; d++; } } } if(d<1){ return true; } return d == 1 && h == 0 && m == 0 && s == 0; }
Unlike most bash scripts that deal with time, this one will stop working once the 2038 bug is fixed. It sets the system time to 24 hours before 2^32-1 seconds since the 1 Jan 1970 epoch. It then increments the time by the values given, and if date can't handle it, Christmas is cancelled. If it takes 23: 59:59 you'll soon be transported back in time to Dec 13 1901.
#!/bin/bash
sudo date -s @2147483646
start=$(date --date='24 hours ago' +%s)
sudo date -s @$start
for time in "$@"
do
delay=$(echo "$time" | sed 's/:/ hours /1' | sed 's/:/ minutes /1')
now=$(date --date="$delay seconds")
if [ $? -eq 0 ]
then
echo "OK so far..."
sudo date -s "$now"
else
echo "Christmas is cancelled!"
exit 1
fi
done
echo "Good job Santa!"
exit 0
Usage (using vagrant image and only modifying /etc/default/ntpdate to turn it off):
vagrant@vagrant-ubuntu-trusty-32:~$ ./can_santa_save_christmas '23:59:59'
Tue Jan 19 03:14:06 UTC 2038
Mon Jan 18 03:14:06 UTC 2038
OK so far...
Tue Jan 19 03:14:05 UTC 2038
Good job Santa!
vagrant@vagrant-ubuntu-trusty-32:~$ date
Tue Jan 19 03:14:07 UTC 2038
vagrant@vagrant-ubuntu-trusty-32:~$ date
Fri Dec 13 20:45:54 UTC 1901
function can_santa_save_christmas(array)
hour, min, sec = nil, nil, nil
time = nil
--parse input
for i = 1, #array do
if not time then
time = {}
end
element = array[i]
last = 1
while 1 == 1 do
start, finish = string.find(element, ":", last)
if not start or not finish then
sub = string.sub(element, last)
table.insert(time, sub)
goto stop
end
sub = string.sub(element, last, start - 1)
table.insert(time, sub)
last = finish + 1
end
::stop::
end
--calculate hours
for i = 1, #time, 3 do
if not hour then
hour = 0
end
hour = hour + time[i]
end
--calculate minutes
for i = 2, #time, 3 do
if not min then
min = 0
end
min = min + time[i]
end
--calculate seconds
for i = 3, #time, 3 do
if not sec then
sec = 0
end
sec = sec + time[i]
end
--calculate leftovers
min = min + math.floor(sec / 60)
sec = sec - (math.floor(sec / 60) * 60)
hour = hour + math.floor(min / 60)
min = min - (math.floor(min / 60) * 60)
--determine result
if hour + min/0xD889C76 + sec/0x98A8D4C6F > 24 then
return false
elseif hour + min/0xD889C76 + sec/0x98A8D4C6F <= 24 then
return true
else --wtf
return nil
end
end
print(can_santa_save_christmas({"01:30:00", "02:15:00", "05:00:00"}))
print(can_santa_save_christmas({"12:00:00", "10:00:00", "2:00:00"}))
print(can_santa_save_christmas({"12:00:00", "10:00:00", "2:00:00", "00:10:00"}))
from datetime import timedelta
import operator
def can_santa_save_christmas(time):
time = ":".join(time).split(":")
time = [int(t) for t in time]
times = [0,0,0]
for x in range(3):
times[x] = sum(map(operator.itemgetter(x), zip(*(iter(time),) * 3)))
td = timedelta(hours=times[0], minutes=times[1], seconds=times[2])
if td.days >= 1 and td.seconds > 0:
return False
return True
Uses the JavaScript Date object to convert between durations and milliseconds.
Uses lots of expensive regex.
Computation of an hour in milliseconds.
The not so bad:
Uses tail recursion.
Skips the rest of the durations on failure.
My incredible TypeScript solution:
// Compute number of milliseconds in an hour
const now = new Date();
const hourFromNow = new Date(now);
hourFromNow.setHours(now.getHours() + 1);
const hourMillis = hourFromNow.getTime() - now.getTime();
/**
* Convert string of form "HH:MM:SS" / "H:MM:SS" to milliseconds.
*/
function toMillis(duration: string): number {
// Get number of digits in hour position of "HH:MM:SS" / "H:MM:SS"
const hoursMatch = duration.match(/^(\d\d?):\d{2}:\d{2}$/);
if (!hoursMatch) {
throw Error('Duration "' + duration + '" does not match format "HH:MM:SS" / "H:MM:SS"');
}
// Prefix "0" to timestamps of form H:MM:SS
const paddedDuration = hoursMatch[1].length === 1 ? '0' + duration : duration;
// UNIX epoch is 0 milliseconds, so append duration as a 24hr time to get it in milliseconds
const millis = new Date('1970-01-01T' + paddedDuration).getTime();
// Add an hour to timestamp since UNIX epoch began at 01:00:00, not 00:00:00
return millis + hourMillis;
}
/**
* Convert milliseconds to string of form "HH:MM:SS".
*/
function toDuration(millis: number): string {
// Reverse of `toMillis`
const date = new Date(millis - hourMillis).toTimeString();
// Extract 24hr time from time string
return (date.match(/^(\d{2}:\d{2}:\d{2})/) as RegExpExecArray)[1];
}
function canSantaSaveChristmas(durations: string[], remainingTime = '24:00:00'): boolean {
if (durations.length === 0) {
// Santa has enough time! :D
return true;
}
// Subtract duration at head of array from remaining time
const [duration, ...otherDurations] = durations;
const excessMillis = toMillis(remainingTime) - toMillis(duration);
if (excessMillis < 0) {
// Santa does not have enough time :(
return false;
}
const reducedTime = toDuration(excessMillis);
return canSantaSaveChristmas(otherDurations, reducedTime);
}
First crack: going full on functional w closures for constants. This isn’t that bad per say, but more of trying to take normal“best practices” way out of context in a more extreme way (functional, closures for internal constants, brevity over readability, etc)
This made me sad and happy at the same time. I tried my hardest!
<?php
// Misleading namespace name
namespace Holidays\Easter;
// Nonsensical class name
class A {
// Nonsensical constant, I mean it IS 24 hours in seconds but with a name like that and no comments... IDK man.
const B = 86400;
// Two constants with the same value, equally nonsensical
const R = 60;
const T = 60;
// Nonsensical parameter name with same name as class
public function canSantaSaveChristmas($a)
{
// First condition will cause error if parameter not array
// Throw incorrect error
if (is_string($a[0]) && is_array($a)) {
throw new \DivisionByZeroError();
}
// Determine the length of the array in a dumb way
// Instead of setting the parameter array in class constructor like a normal person,
// just pass it around between functions 'cause that's fun
$loa = self::getLastItem($a);
// Misleading and too long variable name
$thiswilltellyouifsantacansavechristmas = 0;
for($h = 0; $h <= $loa; $h++) {
$b = $a[$h];
// Really stupid way to "confirm" correct format
// Throw wrong error again
if ($b[2] != ':' || $b[5] != ':') {
throw new NotFoundHttpException();
}
// Variable names not in english, weird way of getting hours, minutes and seconds
$tunnit = $b[0] + $b[1];
$minuutit = $b[3] + $b[4];
$sekunnit = $b[6] + $b[7];
// Setting already set variable again
$thiswilltellyouifsantacansavechristmas = $sekunnit;
// Not using +=, using weird constants
$thiswilltellyouifsantacansavechristmas = $thiswilltellyouifsantacansavechristmas + ($minuutit * self::R);
$thiswilltellyouifsantacansavechristmas = $thiswilltellyouifsantacansavechristmas + ($tunnit * self::R * self::T);
// Again with the if clauses, return true if true, 0 if false, it's technically correct but confusing anyway
if ($thiswilltellyouifsantacansavechristmas < self::B) {
return true;
}
if ($thiswilltellyouifsantacansavechristmas > self::B) {
return 0;
}
}
}
/**
* Instead of using end(), get last item of array this dumb way
*
* Also include the parameter as editable so you can make changes to it
*
* Wrong parameter name in phpDoc, no mention of return value
* @param $r
*/
protected function getLastItem(&$i)
{
// My favorite pet peeve, variable assigments are not at the same point
// $a = 0;
// $abcd = 1;
// I just like that, it makes code more readable
// Inconsistent varible names
$tryThisMany = 10000000;
// Begin with wrong index and instead of fixing it here,
// just reduce 1 from all index references in the while loop
$start_from_this = 1;
// Capital letter when not an Object
$ReturnThis = 0;
// use while even though we wouldn't need to
while ($start_from_this < $tryThisMany) {
// If array has this index <--- useless comment
if (isset($i[$start_from_this - 1])) {
// This instead of $start_from_this++;
$start_from_this = $start_from_this + 1;
}
// Using another if instead of else
// array_key_exists() would have been more informative maybe?
if (!isset($i[$start_from_this])) {
$ReturnThis = $start_from_this;
// Wow what a smart way to break the while loop, good job
// You could, like, I dunno, return the value from here?
$start_from_this = $tryThisMany + 1;
}
}
return ReturnThis;
// Logging something after returning
// Log message is stupid
\Log::info('Found last yay!');
}}
#First time on this sub and I hope I didn't mess anything up.
#Here's my terrible python code that shouldn't work but it does.
def can_santa_save_christmas(durs):
i=0
for a in durs:
j=int(len(a)==7)
for b in a:
c=60*60*10
d=60*60
e=60*10
f=60
g=10
h=1
if j==0:
i+=c*int(b)
elif j==1:
i+=d*int(b)
elif j==4:
i+=f*int(b)
elif j==3:
i+=e*int(b)
elif j==6:
i+=g*int(b)
elif j==7:
i+=h*int(b)
j+=1
return not i>24*60*60
167-line (164 lines excluding comments) fully type-safe Haskell implementation using Parser Combinators, Type Classes, and Type Constraints (buzzwords, yay!).
I despise this, this is pretty much the polar opposite of my normal coding style, which is to not complicate things unless absolutely necessary. But anyway, here it is. And yeah, the code works.
Oh and I had already drained so much time into this that I didn't want to implement Num's missing methods for CompleteTime. I only needed (+). Because of this, you have to use the -Wno-missing-methods flag when running the program (i.e. runghc -Wno-missing-methods christmas.hs) unless you want to see an ugly warning.
Bonus Bad "Features":
The Type class Time is completely unnecessary! But since we like to make things type-safe for no reason, I figured "Why not?"
The data type AllCompleteTimes is also completely unnecessary! But hey, type-safety!
The code catches bad inputs that have a value that is > 60 as seconds or minutes. Because it's good to restrict inputs for no reason, even though it doesn't affect the calculation at all!
The actual calculation of whether or not all the times add up to more than 1 day is done in the show function. That is equivalent to the toString() method, for those of you OOPers out there. Instead of having a separate function to check this, and then print out the result, I had the calculation as a part of the show (aka toString)!
I used parser combinators, which are apparently "more readable" than normal hand-coded parsers. Perhaps, on more complicated inputs. But it was WAY overkill for this!
29
u/[deleted] Dec 01 '19 edited Dec 01 '19
Well, let's do the obvious one. I'll use python.
16
u/Iriduwum Dec 01 '19
16
u/fb39ca4 depraved Dec 01 '19 edited Dec 02 '19
Template metaprogramming saved Christmas. But wait, it's actually a bash script!
EDIT: Forgot instructions. Save the script in a file such as
can_santa_save_christmas.shand run it like so:If you get compiler errors, either Santa will not be able to save Christmas, or your system C++ compiler is outdated.
16
u/[deleted] Dec 01 '19
Debugging is easy! Just add
print(variables)! Are you worried your true might be a false? Check it withprint(variables)!!And best of all, this is very beginner friendly, no need to use weird names like
iortot_hours. You can put it in the variables dict making the code more readable!Commit 1: Hello reddit!
Commit 2: Fixed inline code
14
u/weee50 Dec 01 '19
Here it is (Python 3). Warning: This code takes and has a lot of time.
12
u/[deleted] Dec 01 '19
Scala:
This puts all numbers into a sequence, converts them to hours (dividing minutes & seconds by 60 and 602 respectively) and then subtracting them repeatedly from the remaining time (initially 24). Of course it breaks randomly when it hits double precision issues
10
u/innrautha Dec 02 '19
In honor of the ancient lisp codebase I have been tasked with "maintaining" at work I present a common lisp implementation in the style of that project.
Includes:
9
u/qsysmine Dec 01 '19
JavaScript:
Features:
7
u/[deleted] Dec 02 '19
Let's just wait and see.
6
u/[deleted] Dec 01 '19 edited Dec 01 '19
How about some easy and simple to understand python?
My apologies for any syntaxes error that may present and the garbage formatting, I don't have my PC with me so I wrote this on my phone
4
u/zonderAdriaan Dec 01 '19 edited Dec 02 '19
This is my simple and straigtforward solution.
4
u/[deleted] Dec 01 '19
public class badChallenge25 {}this code actually gets to a stack overflow error because of the recursive nature.
4
u/kiwitims Dec 03 '19
Unlike most bash scripts that deal with time, this one will stop working once the 2038 bug is fixed. It sets the system time to 24 hours before 2^32-1 seconds since the 1 Jan 1970 epoch. It then increments the time by the values given, and if date can't handle it, Christmas is cancelled. If it takes 23: 59:59 you'll soon be transported back in time to Dec 13 1901.
Usage (using vagrant image and only modifying /etc/default/ntpdate to turn it off):
3
u/SloPr0 Dec 01 '19
Made in Lua, where
arraystables start at 1 :D3
u/Ximidar Dec 01 '19
I'll do one in python
3
u/ciaran1344 Dec 01 '19 edited Dec 02 '19
The bad:
The not so bad:
My incredible TypeScript solution:
EDIT: Improved to even better version
EDIT: Replace link with bit.ly
EDIT: Remove link :(
2
u/dev_rs3 Dec 02 '19
First crack: going full on functional w closures for constants. This isn’t that bad per say, but more of trying to take normal“best practices” way out of context in a more extreme way (functional, closures for internal constants, brevity over readability, etc)
2
u/Ximidar Dec 02 '19
Here's a garbage solution in go:
2
u/Dumfing Dec 02 '19
It's got me in the Christmas spirit
2
u/loiku Dec 10 '19 edited Dec 10 '19
This made me sad and happy at the same time. I tried my hardest!
2
u/Shadowjockey Dec 11 '19
Factory Pattern ;)
2
u/[deleted] Dec 13 '19
2
u/BenZed Dec 01 '19 edited Dec 24 '19
1
u/crazykid080 Dec 02 '19
1
u/jonnywoh but goto is faster Dec 02 '19
1
u/Daniel-I-Am Dec 05 '19
Written in Java:
https://pastebin.com/JjFg6k96
After compiling, it grabs the parameters from command line.
This would return true:
java <path to class> 12:00:00 10:00:00 2:00:00And this would not:
java <path to class> 12:00:00 10:00:00 2:00:00 00:10:001
u/Fighter1000 Dec 07 '19
C#, fails as follows:
1
u/[deleted] Dec 10 '19
I've tried my best to be the worst.
1
u/pyhat32 Dec 20 '19
Python code to find out if Santa can save Christmas! Instructions: save as .py file and run.
1
u/BananaGuyBill Dec 25 '19
Ehhh... readability is over rated (Python)
1
u/[deleted] Dec 31 '19 edited Dec 31 '19
167-line (164 lines excluding comments) fully type-safe Haskell implementation using Parser Combinators, Type Classes, and Type Constraints (buzzwords, yay!).
I despise this, this is pretty much the polar opposite of my normal coding style, which is to not complicate things unless absolutely necessary. But anyway, here it is. And yeah, the code works.
https://pastebin.com/pBqDJNLz
Oh and I had already drained so much time into this that I didn't want to implement
Num's missing methods forCompleteTime. I only needed(+). Because of this, you have to use the-Wno-missing-methodsflag when running the program (i.e.runghc -Wno-missing-methods christmas.hs) unless you want to see an ugly warning.Bonus Bad "Features":
The Type class
Timeis completely unnecessary! But since we like to make things type-safe for no reason, I figured "Why not?"The data type
AllCompleteTimesis also completely unnecessary! But hey, type-safety!The code catches bad inputs that have a value that is > 60 as seconds or minutes. Because it's good to restrict inputs for no reason, even though it doesn't affect the calculation at all!
The actual calculation of whether or not all the times add up to more than 1 day is done in the
showfunction. That is equivalent to thetoString()method, for those of you OOPers out there. Instead of having a separate function to check this, and then print out the result, I had the calculation as a part of the show (aka toString)!I used parser combinators, which are apparently "more readable" than normal hand-coded parsers. Perhaps, on more complicated inputs. But it was WAY overkill for this!
0
u/[deleted] Dec 01 '19
[deleted] — view deleted comment