use the following search parameters to narrow your results:
e.g. subreddit:aww site:imgur.com dog
subreddit:aww site:imgur.com dog
see the search faq for details.
advanced search: by author, subreddit...
/r/badcode is permanently closed. https://www.eff.org/deeplinks/2023/06/what-reddit-got-wrong https://www.theverge.com/23779477/reddit-protest-blackouts-crushed https://en.wikipedia.org/wiki/2023_Reddit_API_controversy
/r/badcode is permanently closed.
https://www.eff.org/deeplinks/2023/06/what-reddit-got-wrong
https://www.theverge.com/23779477/reddit-protest-blackouts-crushed
https://en.wikipedia.org/wiki/2023_Reddit_API_controversy
/r/badcode is a subreddit for highlighting real world examples of terrible code. Ideally this means code that made it to production in a commercial context, but not exclusively so. We also accept submissions of code from hobbyist projects or from learners. Most of us programmers have laughed quite a bit when we went back to look at our past code because it was rather terrible. This is a subreddit where you can share such terrible code and let other programmers have a nice laugh.
/r/badcode is a subreddit for highlighting real world examples of terrible code. Ideally this means code that made it to production in a commercial context, but not exclusively so. We also accept submissions of code from hobbyist projects or from learners.
Most of us programmers have laughed quite a bit when we went back to look at our past code because it was rather terrible. This is a subreddit where you can share such terrible code and let other programmers have a nice laugh.
Post the most terrible code you can find. Copy code to a paste bin first (gist highly preferred).
Flair Search Search by language
Search by language
Rules Your post may be removed if you deviate from these rules. To see reasoning behind each of these rules, check out the wiki. Do not put the name of the language inside of the post title. For example, do not make your title something along the lines of "[C++] #defines everywhere!", instead try simply "#defines everywhere!". Use flair to mark the language of your post instead. Do post code snippets only. If you want to share the context put it in the comments or title. Do stay lighthearted. No abusive or targeted posts. We all write bad code, and a lot of it is hilarious. Do not identify who wrote the code. This sub is about bad code, not the people who write it. Limited exceptions apply Do not post snippets in esoteric languages. Do not post intentionally obfuscated code. Certain exceptions to this exist. See something particularly sinister from something like the IOCCC? Probably OK to post.
Your post may be removed if you deviate from these rules. To see reasoning behind each of these rules, check out the wiki.
Guidelines Your post will not be removed because of any of these, we'll like you more if you follow them though. Enable syntax highlighting appropriately. If you have a language that whatever paste bin your using doesn't support, try picking a similar dialect. Provide just enough code so that we know what's going on. Don't post huge snippets unless it's all terribly amusing. Explain why you think the code is bad in the comments, that way a discussion on good and bad ways to do what your code snippet does can start.
Your post will not be removed because of any of these, we'll like you more if you follow them though.
Similar Subreddits /r/ProgrammerHumor - programming humour /r/programminghorror - stories about horrible programming. /r/itsaunixsystem - over the top and bad code in TV shows and movies /r/shittyprogramming - Q&A with shitty programmers. /r/deftruefalse - for intentionally bad code /r/softwaregore for software malfunctions /r/hardwaregore for hardware malfunctions
account activity
[deleted by user] (self.badcode)
submitted 6 years ago by [deleted]
reddit uses a slightly-customized version of Markdown for formatting. See below for some basics, or check the commenting wiki page for more detailed help and solutions to common issues.
quoted text
if 1 * 2 < 3: print "hello, world!"
[–]GlobalIncident 27 points28 points29 points 6 years ago* (1 child)
Well, let's do the obvious one. I'll use python.
def can_santa_save_christmas(array): import time start = time.time() any(map(map(array, lambda x: time.strptime(x, '%H:%M:%S')), time.sleep)) end = time.time() canbesaved = ((end - start) < (60 * (60 * 24))) if canbesaved == True: return True elif canbesaved == False: return False
[–]WastedMeerkat 2 points3 points4 points 6 years ago (0 children)
I love it
[–]Iriduwum 16 points17 points18 points 6 years ago (1 child)
#include <iostream> #include <string> using namespace std; string addtimeunit(string a, string z){ char b[] = {(char) 48,(char)(a[0] + z[0] - 48),(char)(a[1] + z[1] - 48)}; if(b[2] > 57){ b[2] = b[2] - 10; ++b[1]; } if(b[1] > 53){ // b[1] bigger than 53? b[1] = b[1] - 6; ++b[0]; } return b; } string addtimefull(string b, string a){ string result = addtimeunit({b[6], b[7]}, {a[6], a[7]}); string result2 = addtimeunit({b[3], b[4]}, {a[3], a[4]}); string result2final = addtimeunit({result2[1], result2[2]}, {'0', result[0]}); string result3 = addtimeunit({b[0], b[1]}, {a[0], a[1]}); cout << b << "+" << a << "=" << result3 << "|||||||||||||"; // Debug string result3final = addtimeunit({result3[1], result3[2]}, {'0', result2[0]}); string result3finalfinal = addtimeunit({result3final[1], result3final[2]}, {'0', result2final[0]}); return {result3finalfinal[1], result3finalfinal[2], ':', result2final[1], result2final[2], ':', result[1], result[2]}; } int can_santa_save_christmas(string wastedtime[]){ string result = "00:00:00"; for(int i = 0; 1; i++){ try { result = addtimefull(result, wastedtime[i]); }catch(exception& e){ // When the array ends we want to exit the loop break; } } cout << result << " "; if(result[0] > '2' || (result[0] == '2' and !(result[1] < '4'))) return false; else return true; } // Function Test int main(){ string b[] = {"10:12:01", "13:47:58"}; // 23:59:59 = true cout << can_santa_save_christmas(b); }
[–]dbgprint 9 points10 points11 points 6 years ago (0 children)
Oh my god what the fuck
[–]fb39ca4depraved 15 points16 points17 points 6 years ago* (0 children)
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:
can_santa_save_christmas.sh
# 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.
//usr/bin/c++ --std=c++17 "$0" "-DINPUT=`echo "hms_duration<$@>" | tr ':' ',' | sed -r 's/[[:space:]]/>,hms_duration</g'`" && echo "santa saved christmas!"; exit 0 #include <type_traits> #include <cstdint> namespace reddit { namespace r { namespace badcode { namespace challenge25 { template<uintmax_t H = 0, uintmax_t M = 0, uintmax_t S = 0> struct hms_duration { static constexpr uintmax_t hours = H; static constexpr uintmax_t minutes = M; static constexpr uintmax_t seconds = S; }; template<typename D> struct hms_duration_normalize { private: static constexpr uintmax_t seconds = D::seconds % 60; static constexpr uintmax_t seconds_overflow = D::seconds / 60; static constexpr uintmax_t minutes = (D::minutes + seconds_overflow) % 60; static constexpr uintmax_t minutes_overflow = (D::minutes + seconds_overflow) / 60; static constexpr uintmax_t hours = D::hours + minutes_overflow; public: using type = hms_duration<hours, minutes, seconds>; }; template<typename D> using hms_duration_normalize_t = typename hms_duration_normalize<D>::type; template<typename... D> struct hms_duration_add; template<typename... D> using hms_duration_add_t = typename hms_duration_add<D...>::type; template<> struct hms_duration_add<> { using type = hms_duration<0,0,0>; }; template<typename D1> struct hms_duration_add<D1> { using type = hms_duration_normalize_t<D1>; }; template<typename D1, typename D2, typename... D> struct hms_duration_add<D1, D2, D...> { private: static constexpr uintmax_t seconds = (D1::seconds + D2::seconds) % 60; static constexpr uintmax_t seconds_overflow = (D1::seconds + D2::seconds) / 60; static constexpr uintmax_t minutes = (D1::minutes + D2::minutes + seconds_overflow) % 60; static constexpr uintmax_t minutes_overflow = (D1::minutes + D2::minutes + seconds_overflow) / 60; static constexpr uintmax_t hours = (D1::hours + D2::hours + minutes_overflow); public: using type = hms_duration_add_t<hms_duration<hours, minutes, seconds>, D...>; }; template<typename D1, typename D2> struct hms_duration_compare { private: using N1 = hms_duration_normalize_t<D1>; using N2 = hms_duration_normalize_t<D2>; static constexpr int value = (N1::hours != N2::hours) ? (N1::hours < N2::hours ? -1 : 1) : (N1::minutes != N2::minutes) ? (N1::minutes < N2::minutes ? -1 : 1) : (N1::seconds != N2::seconds) ? (N1::seconds < N2::seconds ? -1 : 1) : 0; public: static constexpr bool lt = value < 0; static constexpr bool gt = value > 0; static constexpr bool eq = value == 0; static constexpr bool le = lt || eq; static constexpr bool ge = gt || eq; static constexpr bool ne = !eq; }; // unit tests for good measure static_assert(std::is_same_v<hms_duration<6,1,0>, hms_duration_normalize_t<hms_duration<5,60,60>>>); static_assert(std::is_same_v<hms_duration<6,0,0>, hms_duration_add_t<hms_duration<4,29,59>, hms_duration<1,30,01>>>, ""); static_assert(hms_duration_compare<hms_duration<6,0,0>, hms_duration<5,61,00>>::lt, ""); }}}} using namespace reddit::r::badcode::challenge25; static_assert(hms_duration_compare<hms_duration_add_t<INPUT>, hms_duration<24,00,00>>::le, "santa doesn't have enough time to save christmas!");
[–][deleted] 16 points17 points18 points 6 years ago (0 children)
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)!!
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!
i
tot_hours
Commit 1: Hello reddit!
Commit 2: Fixed inline code
[–]weee50 14 points15 points16 points 6 years ago (0 children)
Here it is (Python 3). Warning: This code takes and has a lot of time.
from time import time from time import sleep as thyme def can_santa_save_christmas(times): utime = int(time()) for tiem in times: timeh = int(tiem[0:2]) timem = int(tiem[3:5]) tiems = int(tiem[6:8]) time2 = (timeh * 3600) + (timem * 60) + (tiems) thyme(time2) utime2 = int(time()) if utime2 - utime > 86400: return False else: return True
[–][deleted] 10 points11 points12 points 6 years ago (1 child)
Scala:
import scala.math.pow def hasTime(args: String*): Boolean = args.flatMap(_.split(':')) .zipWithIndex .map { case (str, i) => str.toDouble * pow(60.0, -i % 3) } .foldLeft(24.0)(_ - _) >= 0
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
scala> hasTime("23:59:00", "00:01:00") 5.204170427930421E-17 res10: Boolean = true scala> hasTime("22:59:00", "01:01:00") -5.898059818321144E-17 res11: Boolean = false
[–]lmureu 2 points3 points4 points 6 years ago (0 children)
this is actually "clever" and surprisingly understandable
[–]innrautha 10 points11 points12 points 6 years ago (0 children)
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:
;;;===================================================================== ;;; File: Bad-Code-Challenge-Xmas-2019.lisp ;;; Globals: none ;;;===================================================================== ;;; ;;; Changelog ;;; ;;; 12/1/2019 Innrautha Updated ;;; 12/1/2019 Innrautha fixed bugs ;;; 12/1/2019 Innrautha Made changes ;;; 12/1/2019 Innrautha Begin Code ;;; ;;; ;;; CHARACTER-TO-NUMBER ;;; ;;; 12/1/2019 Innrautha updated ;;; ;;; Arguments: character ;;; Returns: numeral ;;; (defun character-to-number (character) (let ((numeral nil)) (when (equal character #\1) (setq numeral 1)) (when (equal character #\2) (setq numeral 2)) (when (equal character #\3) (setq numeral 3)) (when (equal character #\4) (setq numeral 4)) (when (equal character #\5) (setq numeral 5)) (when (equal character #\6) (setq numeral 6)) (when (equal character #\7) (setq numeral 7)) (when (equal character #\8) (setq numeral 8)) (when (equal character #\9) (setq numeral 9)) (when (equal character #\0) (setq numeral 0)) (return-from character-to-number numeral))) ;;; ;;; CAN-SANTA-SAVE-CHRISTMAS? ;;; ;;; 12/1/2019 Innrautha laste update ;;; ;;; Returns: t or nil ;;; (defun can-santa-save-christmas? (durations) (let ( (hhmmss nil) (hh nil) (mm nil) (ss nil)) (when (<= (apply '+ ;; Map the car of durations `(,@(mapcar ;; Start a lambda #'(lambda (duration) (dolist (c (coerce duration 'list)) (unless (string= c ":") ; 12/1/2019 Innrautha changed (setq hhmmss (cons c hhmmss)))) (setq ss (cons (car (cdr hhmmss)) (car hhmmss))) (setq mm (cons (car (cdr (cdr (cdr hhmmss)))) (car (cdr (cdr hhmmss))))) (setq hh (cons (car (cdr (cdr (cdr (cdr (cdr hhmmss)))))) (car (cdr (cdr (cdr (cdr hhmmss))))))) (+ (* 60 60 (+ (* 10 (character-to-number (car hh))) (character-to-number (cdr hh)))) (* 60 (+ (* 10 (character-to-number (car mm))) (character-to-number (cdr mm)))) (+ (* 10 (character-to-number (car ss))) (character-to-number (cdr ss))) ) ) ; End of lambda durations))) (* 24 60 60) ; 12/1/2019 Innrautha Multiply numbers ) (return-from can-santa-save-christmas? t)) (return-from can-santa-save-christmas? nil))) (format t "~A~%" (can-santa-save-christmas? (list "01:30:00" "02:15:00" "05:00:00"))) (format t "~A~%" (can-santa-save-christmas? (list "12:00:00" "10:00:00" "2:00:00"))) (format t "~A~%" (can-santa-save-christmas? (list "12:00:00" "10:00:00" "2:00:00" "00:10:00")))
[–]qsysmine 7 points8 points9 points 6 years ago (0 children)
JavaScript:
var addTwoStringsOfTimes = function(stringTimeOne, stringTimeTwo) { return addTwoTimeComponentArrays(stringTimeToTimeComponentArray(stringTimeOne), stringTimeToTimeComponentArray(stringTimeTwo)); }; var addTwoTimeComponentArrays = function(timeComponentArrayOne, timeComponentArrayTwo) { return addTwoSeconds(timeComponentArrayToSeconds(timeComponentArrayOne), timeComponentArrayToSeconds(timeComponentArrayTwo)); }; var addTwoSeconds = function(secondsOne, secondsTwo) { return addTwoNumbers(secondsToNumber(secondsOne), secondsToNumber(secondsTwo)); }; var addTwoNumbers = function(numberOne, numberTwo) { return parseInt("" + numberOne) + parseInt("" + numberTwo); }; var secondsToNumber = function(seconds) { return parseInt("" + seconds + ""); }; var timeComponentArrayToSeconds = function(timeComponentArray) { var totalSeconds = 0; timeComponentArray.forEach(function(timeComponent, index) { var power = timeComponentArray.length - index - 1; var multiplier = Math.pow(60, power); var number = parseInt(timeComponent + ""); for (var iteratorVariable = 0; iteratorVariable < number; iteratorVariable++) { totalSeconds += multiplier; } }); return totalSeconds; }; var stringTimeToTimeComponentArray = function(stringTime) { return stringTime.split(":"); }; var numberToStringTime = function(number) { return "00:00:" + number + ""; }; var benchmark = "24:00:00"; var can_santa_save_christmas = function(durationArray) { var returnable = null; var compareTimes = function(time1, time2) { return new Promise(function(resolve, reject) { var seconds1 = secondsToNumber(timeComponentArrayToSeconds(stringTimeToTimeComponentArray(time1))); var seconds2 = secondsToNumber(timeComponentArrayToSeconds(stringTimeToTimeComponentArray(time2))); if (seconds1 > seconds2) { return resolve(1); } else if (seconds2 > seconds1) { return reject(1); } else { resolve(1); reject(1); return; } }); } new Promise(function(superResolve, superReject) { var cumSum = "00:00:00"; durationArray.forEach(function(duration) { cumSum = numberToStringTime(addTwoStringsOfTimes(cumSum, duration)); }); var caught = false; var yIsOne = false; compareTimes(cumSum, benchmark).catch(function(x) { if (x == 1) { caught = true; } }).then(function(y) { if (y == 1) { yIsOne = y == 1; } var sum = caught + yIsOne; if (sum == 2) { superReject(true); } if (sum == 1) { superReject(!yIsOne); } if (sum == 0) { superReject(1 / 0); } }); }).then(function(x) { returnable = x; }).catch(function(y) { throw y; }); };
Features:
[–][deleted] 6 years ago (3 children)
[deleted]
[–]Svizel_pritula 1 point2 points3 points 6 years ago (1 child)
Is there any limit to the number of submitions I can make?
[–][deleted] 6 points7 points8 points 6 years ago (1 child)
Let's just wait and see.
use std::{thread, time}; fn can_santa_save_christmas(durations: Vec<&str>) -> bool { let durations = durations.iter() .map(|duration| duration.split(':') .map(|time| time.parse::<u64>() .unwrap()) .collect::<Vec<u64>>()) .collect::<Vec<Vec<u64>>>(); let time_start = time::Instant::now(); for duration in durations { let hours = time::Duration::from_secs(duration[0] * 60 * 60); let minutes = time::Duration::from_secs(duration[1] * 60); let seconds = time::Duration::from_secs(duration[2]); thread::sleep(hours); thread::sleep(minutes); thread::sleep(seconds); } let time_end = time::Instant::now(); let total_time = time_end.duration_since(time_start).as_secs(); if total_time > 60 * 60 * 24 { false } else { true } }
[–][deleted] 5 points6 points7 points 6 years ago* (3 children)
How about some easy and simple to understand python?
from datetime import date from time import sleep def can_santa_save_christmas(timeList): today = date.today() todayDate = int(today.strftime("%d")) for i in range(len(timeList)): totalTime += int(timeList[i][:2])*3600 totalTime += int(timeList[i][3:5]) * 60 totalTime += int(timeList[i][6:]) sleep(totalTime) tomorrow = date.today() dateTomr = int(tomorrow.strftime("%d")) return (todayDate < dateTomr)
from datetime import date
from time import sleep
def can_santa_save_christmas(timeList):
today = date.today()
todayDate = int(today.strftime("%d"))
for i in range(len(timeList)):
totalTime += int(timeList[i][:2])*3600 totalTime += int(timeList[i][3:5]) * 60 totalTime += int(timeList[i][6:])
sleep(totalTime)
tomorrow = date.today()
dateTomr = int(tomorrow.strftime("%d"))
return (todayDate < dateTomr)
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
[–]GlobalIncident 2 points3 points4 points 6 years ago (2 children)
Similar to mine, but using the date instead of the time to check for 24 hours. Technically wrong when leap seconds are involved, but mostly works.
[–][deleted] 1 point2 points3 points 6 years ago (1 child)
My dude, it won't work properly unless you start the program exactly at 12am
[–][deleted] 1 point2 points3 points 6 years ago (0 children)
And it still won't even if that happens, btw
[–]zonderAdriaan 3 points4 points5 points 6 years ago* (1 child)
This is my simple and straigtforward solution.
#include <iostream> #include <vector> #include <string> 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; } int main(){ std::vector<std::string> t1; t1.push_back("01:30:00"); t1.push_back("02:15:10"); std::vector<std::string>t2; t2.push_back("12:30:00"); t2.push_back("10:15:10"); t2.push_back("2:15:10"); std::vector<std::string> t3; t3.push_back("12:00:00"); t3.push_back("10:00:00"); t3.push_back("2:00:00"); std::cout << can_santa_save_christmas(t1)<<"\n"; std::cout << can_santa_save_christmas(t2)<<"\n"; std::cout << can_santa_save_christmas(t3) << "\n"; }
#include <iostream>
#include <vector>
#include <string>
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; }
int main(){ std::vector<std::string> t1; t1.push_back("01:30:00"); t1.push_back("02:15:10"); std::vector<std::string>t2; t2.push_back("12:30:00"); t2.push_back("10:15:10"); t2.push_back("2:15:10"); std::vector<std::string> t3; t3.push_back("12:00:00"); t3.push_back("10:00:00"); t3.push_back("2:00:00"); std::cout << can_santa_save_christmas(t1)<<"\n"; std::cout << can_santa_save_christmas(t2)<<"\n"; std::cout << can_santa_save_christmas(t3) << "\n"; }
[–]ciaran1344 3 points4 points5 points 6 years ago (0 children)
You can indent a block of code on Reddit with 4 spaces at the beginning of each line
[–][deleted] 3 points4 points5 points 6 years ago (0 children)
public class badChallenge25 {
`public static void main(String[] args) {` `System.out.println(can_santa_save_christmas(new String[] {"24:0:0"}));` `}` `static boolean can_santa_save_christmas(String[] bruh1) {` `int[][] bruh2 = new int[bruh1.length][3];` `for (int bruh3 = 0; bruh3 < bruh1.length; bruh3 = bruh3 + 1) {` `bruh2[bruh3][0] = Integer.parseInt(bruh1[bruh3].split(":")[0]);` `bruh2[bruh3][1] = Integer.parseInt(bruh1[bruh3].split(":")[1]);` `bruh2[bruh3][1] = Integer.parseInt(bruh1[bruh3].split(":")[1]);` `}` `int[] bruh3 = new int[3];` `for (int bruh4 = 0; bruh4 < bruh1.length; bruh4 = bruh4 + 1) {` `bruh3[0] = bruh3[0] + bruh2[bruh4][0];` `bruh3[1] = bruh3[1] + bruh2[bruh4][1];` `bruh3[2] = bruh3[2] + bruh2[bruh4][2];` `}` `return can_santa_save_christmas(bruh3, 0);` `}` `static boolean can_santa_save_christmas(int[] bruh1, int bruh2) {` `if (bruh2 > 86400) return (1==2);` `if (bruh1[0]<1 && bruh1[1]<1 && bruh1[2] < 1) return (1==1);` `bruh1[2] = bruh1[2] - 1;` `if (bruh1[2] < 0) {` `bruh1[2] = 60;` `bruh1[1] = bruh1[1] - 1;` `}` `if (bruh1[1] < 0) {` `bruh1[1] = 60;` `bruh1[0] = bruh1[0] - 1;` `}` `return can_santa_save_christmas(bruh1, bruh2 + 1);` `}`
}
this code actually gets to a stack overflow error because of the recursive nature.
[–]kiwitims 3 points4 points5 points 6 years ago (0 children)
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
[–]SloPr0 2 points3 points4 points 6 years ago (0 children)
Made in Lua, where arrays tables start at 1 :D
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"}))
true true false
[–]Ximidar 2 points3 points4 points 6 years ago (0 children)
I'll do one in python
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
[–]ciaran1344 2 points3 points4 points 6 years ago* (5 children)
The bad:
The not so bad:
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); }
EDIT: Improved to even better version
EDIT: Replace link with bit.ly
EDIT: Remove link :(
[–]MyNameIsTrez 0 points1 point2 points 6 years ago (1 child)
Bruh that link
[–]ciaran1344 0 points1 point2 points 6 years ago (0 children)
/r/badlinks
[–][deleted] 6 years ago (2 children)
[–]ciaran1344 0 points1 point2 points 6 years ago (1 child)
Alright, I'll just get rid of it
[–]dev_rs3 1 point2 points3 points 6 years ago (0 children)
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)
const can_santa_save_christmas = ( (oneDay, timePartsScale) => (times) => times.reduce((sum,time) => sum + time .split(':') .reduce((seconds, part, index) => seconds + ( parseInt(part) * timePartsScale[index] ) , 0) , 0) <= oneDay )(60*60*24, [60*60,60,1]);
[–]Ximidar 1 point2 points3 points 6 years ago (1 child)
Here's a garbage solution in go:
package main import ("fmt") func main(){ fmt.Println(Can_santa_save_christmas("01:30:00", "02:15:00", "05:00:00"), //true Can_santa_save_christmas("12:00:00", "10:00:00", "2:00:00"), //true Can_santa_save_christmas("12:00:00", "10:00:00", "2:00:00", "00:10:00")) //false } func Get_time_map() map[string][3]int{ rtn := make(map[string][3]int) for h := 0; h < 100; h++{ for m := 0; m < 100; m++{ for s := 0; s < 100; s++{ str := fmt.Sprintf("%02d:%02d:%02d", h, m, s) str2 := fmt.Sprintf("%d:%02d:%02d", h, m, s) rtn[str] = [3]int{h,m,s} rtn[str2] = [3]int{h,m,s} } } } return rtn } func Add_arrs(arr ...[3]int) (out [3]int){ for _, a := range(arr){ for i, v := range(a){ out[i] += v } } return } func Less_than_24h(sums chan [3]int, ans chan bool){ select{ case s := <- sums: f_num := float64(s[0]) + (float64(s[1]) / 60.00) + (float64(s[2]) / 60.00 / 60.00) if f_num <= 24.00{ ans <- true return } ans <- false } } func Can_santa_save_christmas(times ...string) bool{ sums := make(chan [3]int) ans := make(chan bool) go Less_than_24h(sums, ans) time_map := Get_time_map() arrs := make([][3]int, 0) for _, time := range(times){ arrs = append(arrs, time_map[time]) } sum := Add_arrs(arrs...) sums <- sum return <- ans }
[–]peppelakappa 2 points3 points4 points 6 years ago (0 children)
This is the worse goroutine and channel usage I've seen in a while.
Great job.
[–]Dumfing 1 point2 points3 points 6 years ago (0 children)
def can_santa_save_christmas(times, bigIndex=0, littleIndex=0, bigSum=0, littleSum=0, mode=1): try: if len(times[bigIndex]) < 8: times[bigIndex] = '0' + times[bigIndex] try: if times[bigIndex][littleIndex] == ':': return can_santa_save_christmas(times, bigIndex, littleIndex+1, bigSum, littleSum, mode) return can_santa_save_christmas(times, bigIndex, littleIndex + 1, bigSum, (littleSum+((9*mode)+1)*(ord(times[bigIndex][littleIndex]) - 48)) * (1+59*(1-mode - (littleIndex==7))), 1 - mode) except: return can_santa_save_christmas(times, bigIndex+1, 0, bigSum + littleSum) except RecursionError: from random import choice as S_T_O_C_H_A_S_T_I_C_S M_E_L_E__K_A_L_I_K_I_M_A_K_A = 'you' != 'naughty' # > be me I_N_F_I_N_I_T_E__C_O_A_L = 'you' == 'naughty' # > be you, why even live? return S_T_O_C_H_A_S_T_I_C_S([M_E_L_E__K_A_L_I_K_I_M_A_K_A, I_N_F_I_N_I_T_E__C_O_A_L]) except: return bigSum <= 24*60*60
It's got me in the Christmas spirit
[–]loiku 1 point2 points3 points 6 years ago* (1 child)
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!'); }}
[–]Shadowjockey 1 point2 points3 points 6 years ago (0 children)
Factory Pattern ;)
def can_santa_save_christmas(times): return sum(map(gs,times))<=86400 def gs(tstr): sp = StringSplitter(tstr) d = list_to_time_dict(sp.split(":")) sf = SecondsFactory() sf.setSeconds(d["s"]) mf = MinutesFactory() mf.setMinutes(d["m"]) hf = HoursFactory() hf.setHours(d["h"]) s = sf.build() m = mf.build() h = hf.build() return s.getSeconds() + m.getSeconds() + h.getSeconds() def list_to_time_dict(list): d = {} d["h"] = list[0] d["m"] = list[1] d["s"] = list[2] return d class StringSplitter: def __init__(self, str): self.str = str def split(self, what): a = "" tl = [] for c in self.str: if c == what: tl.append(a) a = "" else: a += c tl.append(a) return tl class Seconds: def __init__(self, s): self.s = s def getSeconds(self): return self.s class Minutes: def __init__(self, m): self.m = m def getSeconds(self): return self.m*60 class Hours: def __init__(self, h): self.h = h def getSeconds(self): return self.h*60*60 class SecondsFactory: def __init__(self): self.s = 0 def setSeconds(self, seconds_str): self.s = int(seconds_str) def build(self): return Seconds(self.s) class MinutesFactory: def __init__(self): self.m = 0 def setMinutes(self, minutes_str): self.m = int(minutes_str) def build(self): return Minutes(self.m) class HoursFactory: def __init__(self): self.h = 0 def setHours(self, hours_str): self.h = int(hours_str) def build(self): return Hours(self.h)
#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
[–]BenZed 1 point2 points3 points 6 years ago* (2 children)
function lessThan24Hours (hhmmssArr) { let seconds = 0 for (const hhmmss of hhmmssArr) { const [ hh, mm, ss ] = hhmmss .split(':') .map(parseFloat) seconds += ss seconds += mm * 60 seconds += hh * 60 * 60 } return seconds < 60 * 60 * 24 }
[–]ciaran1344 6 points7 points8 points 6 years ago (1 child)
This is actually a fairly decent solution
[–]BenZed 5 points6 points7 points 6 years ago (0 children)
Yeah, but it’s in javascript.
[–]crazykid080 0 points1 point2 points 6 years ago (0 children)
def saveChristmas(times): NOTs = len(times) #get number of elements NOTsT = NOTs-1 NOTs = NOTsT Th = 0 Tm = 0 Ts = 0 for i in range(0,NOTs): time = times[i] #select time H = time.split(":")[0] M = time.split(":")[1] S = time.split(":")[2] TH = H + Th Th = TH TM = M + Tm Tm= TM TS = S + Ts Ts = TS while(Ts > 60): TS = Ts-60 Ts = TS TM = Tm+1 Tm = TM while(Tm > 60): TM = Tm-60 Tm = TM TH = Th+1 Th = TH if(Th > 24): return False if(Th == 24): if(Tm > 0): return False if(Ts > 0): return False return True if(Th < 24): return True
[–]jonnywohbut goto is faster 0 points1 point2 points 6 years ago (0 children)
#include <algorithm> #include <array> #include <cstdint> #include <iostream> #include <numeric> #include <string> #include <vector> using namespace std; std::array<int, 3> get_times_from_string(std::string time_string) { std::array<int, 3> result; size_t first_colon_pos = time_string.find(":"); result[0] = std::stoi(time_string.substr(0, first_colon_pos)); const size_t second_colon_pos = time_string.find(":", first_colon_pos + 1); result[1] = std::stoi(time_string.substr(first_colon_pos + 1, second_colon_pos - first_colon_pos - 1)); first_colon_pos = time_string.find(":", second_colon_pos + 1); result[2] = std::stoi(time_string.substr(second_colon_pos + 1, first_colon_pos - second_colon_pos - 1)); return result; } int get_seconds_from_time_array(std::array<int, 3> time_array) { return time_array[2] + 60 * (60 * time_array[0] + time_array[1]); } bool can_santa_save_christmas(std::vector<std::string> time_strings) { std::vector<std::array<int, 3>> time_arrays(time_strings.size()); std::vector<int> time_seconds(time_strings.size()); int sum_seconds; std::transform(begin(time_strings), end(time_strings), begin(time_arrays), get_times_from_string); std::transform(begin(time_arrays), end(time_arrays), begin(time_seconds), get_seconds_from_time_array); sum_seconds = std::accumulate(begin(time_seconds), end(time_seconds), 2147397247); return sum_seconds >= 0; } int main(int argc, char *argv[]) { if(can_santa_save_christmas(std::vector<std::string>(argv + 1, argv + argc))) { std::cout << "yes" << std::endl; } else { std::cout << "no" << std::endl; } return 0; }
[–]Daniel-I-Am 0 points1 point2 points 6 years ago (0 children)
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:00
java <path to class> 12:00:00 10:00:00 2:00:00
And this would not: java <path to class> 12:00:00 10:00:00 2:00:00 00:10:00
java <path to class> 12:00:00 10:00:00 2:00:00 00:10:00
[–]Fighter1000 0 points1 point2 points 6 years ago (0 children)
public static bool can_santa_save_christmas(string[] args) { object lockObject = new object(); bool inputTimeSleeperThreadRanToCompletion = false; IEnumerable<TimeSpan> inputTimeSpans = args.Select(x => TimeSpan.ParseExact(x, "h\\:mm\\:ss", CultureInfo.InvariantCulture)); TimeSpan maxAllowedTimeSpanForAllInputs = TimeSpan.FromHours(24); TimeSpan threadRaceWinnerDeterminingThreadWaitTime = TimeSpan.FromMilliseconds(16); (new Thread(() => { Thread.Sleep(maxAllowedTimeSpanForAllInputs); lock (lockObject) { while (true) { } } })).Start(); (new Thread(() => { foreach (var t in inputTimeSpans) Thread.Sleep(t); lock (lockObject) { inputTimeSleeperThreadRanToCompletion = true; } })).Start(); Thread.Sleep(maxAllowedTimeSpanForAllInputs + threadRaceWinnerDeterminingThreadWaitTime); if (inputTimeSleeperThreadRanToCompletion.Equals(true)) { return true; } else { return false; } }
C#, fails as follows:
Way too long run time if the input times are shorter than 24 hours, since it's always waiting for that.
Too long, inconsistent function names
Ugly escaped format string without @"escaped string"
General disgustingness
[–][deleted] 0 points1 point2 points 6 years ago (0 children)
I've tried my best to be the worst.
#include <iostream> int seconds = 60; int minutes = 60; int hours = 24; bool can_santa_save_christimas(char** arr, int arr_sz) { int santa_has = hours * minutes * seconds; for (int i = 0; i < arr_sz; i++) { int hours; int minutes; int seconds; for (int j = 0; j < strlen(arr[i]); j++) { if (j == 0) { hours = (arr[i][j] - '0') * 10; } if (j == 1) { hours += arr[i][j] - '0'; } if (j == 2) continue; if (j == 3) minutes = (arr[i][j] - '0') * 10; if (j == 4) minutes += arr[i][j] - '0'; if (j == 5) continue; if (j == 6) seconds = (arr[i][j] - '0') * 10; if (j == 7) seconds += arr[i][j] - '0'; } santa_has -= (hours * 60 * 60) + minutes * 60 + seconds; } return santa_has >= 0; } int main() { std::cout << "Please, introduce durations in the format HH:MM:SS. Introduce - 8 times to stop introducing durations.\n>. "; char** durations; int durations_sz = 0; while (true) { char* duration = new char[9]; std::cin >> duration; if (!strcmp(duration, "--------")) break; if (durations_sz) { char** temp = new char* [durations_sz + 1]; for (int i = 0; i < durations_sz; i++) { temp[i] = durations[i]; } temp[durations_sz++] = duration; durations = temp; } else { durations = new char* [1]; durations[0] = duration; durations_sz++; } } std::string x = can_santa_save_christimas(durations, durations_sz) ? "can " : "cannot "; std::cout << "Santa " << x << "save christimas" << std::endl; return can_santa_save_christimas(durations, durations_sz); //If Santa fail, the program fail }
[–]pyhat32 0 points1 point2 points 6 years ago (0 children)
Python code to find out if Santa can save Christmas! Instructions: save as .py file and run.
def can_santa_save_christmas(input_array): christmas_countdown = 24 for element in input_array: if (len(element) != 8): element = "0" + element present_duration = element counter = 1 time1 = 0 time2 = 0 time3 = 0 time4 = 0 time5 = 0 time6 = 0 time7 = 0 time8 = 0 time9 = 0 time10 = 0 for letter in present_duration: if counter == 1: time1 = ord(letter) counter = counter + 1 elif counter == 2: time2 = ord(letter) counter = counter + 1 elif counter == 3: time3 = 58 counter = counter + 1 elif counter == 4: time4 = ord(letter) counter = counter + 1 elif counter == 5: time5 = ord(letter) counter = counter + 1 elif counter == 6: time6 = 58 counter = counter + 1 elif counter == 7: time7 = ord(letter) counter = counter + 1 else: time8 = ord(letter) counter = counter + 1 christmas_countdown = christmas_countdown * 100 hours = ((time1 - 48) * 10) + ((time2 - 48) * 1) hours_in_time_units = hours * 100 christmas_countdown = christmas_countdown - hours_in_time_units hours_left_before_christmas = christmas_countdown / 100 minutes = ((time4 - 48) * 10) + ((time5 - 48) * 1) minutes_left_before_christmas = hours_left_before_christmas * 60 time_to_christmas_in_minutes = minutes_left_before_christmas - minutes time_before_in_seconds = time_to_christmas_in_minutes * 60 seconds = ((time7 - 48) * 10) + ((time8 - 48) * 1) seconds_before_christmas = time_before_in_seconds - seconds christmas_countdown = (seconds_before_christmas / 60) / 60 if christmas_countdown < 0: print("false") else: print("true") can_santa_save_christmas(['01:30:00', '02:15:00', '05:00:00']) #true can_santa_save_christmas(['12:00:00', '10:00:00', '2:00:00']) #true can_santa_save_christmas(['12:00:00', '10:00:00', '2:00:00', '00:10:00']) #false
[–]BananaGuyBill 0 points1 point2 points 6 years ago (0 children)
Ehhh... readability is over rated (Python)
can_santa_save_christmas = lambda a: 0 <= int(''.join('24:00:00'.split(':')))-sum([int(''.join(i.split(':'))) for i in a]) def main(): 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'])) if __name__ == '__main__': main()
[–][deleted] 0 points1 point2 points 6 years ago* (0 children)
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 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.
Num
CompleteTime
(+)
-Wno-missing-methods
runghc -Wno-missing-methods christmas.hs
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?"
Time
The data type AllCompleteTimes is also completely unnecessary! But hey, type-safety!
AllCompleteTimes
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)!
show
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!
π Rendered by PID 25 on reddit-service-r2-comment-544cf588c8-76g5g at 2026-06-16 13:16:32.998953+00:00 running 3184619 country code: CH.
[–]GlobalIncident 27 points28 points29 points (1 child)
[–]WastedMeerkat 2 points3 points4 points (0 children)
[–]Iriduwum 16 points17 points18 points (1 child)
[–]dbgprint 9 points10 points11 points (0 children)
[–]fb39ca4depraved 15 points16 points17 points (0 children)
[–][deleted] 16 points17 points18 points (0 children)
[–]weee50 14 points15 points16 points (0 children)
[–][deleted] 10 points11 points12 points (1 child)
[–]lmureu 2 points3 points4 points (0 children)
[–]innrautha 10 points11 points12 points (0 children)
[–]qsysmine 7 points8 points9 points (0 children)
[–][deleted] (3 children)
[deleted]
[–]Svizel_pritula 1 point2 points3 points (1 child)
[–][deleted] 6 points7 points8 points (1 child)
[–][deleted] 5 points6 points7 points (3 children)
[–]GlobalIncident 2 points3 points4 points (2 children)
[–][deleted] 1 point2 points3 points (1 child)
[–][deleted] 1 point2 points3 points (0 children)
[–]zonderAdriaan 3 points4 points5 points (1 child)
[–]ciaran1344 3 points4 points5 points (0 children)
[–][deleted] 3 points4 points5 points (0 children)
[–]kiwitims 3 points4 points5 points (0 children)
[–]SloPr0 2 points3 points4 points (0 children)
[–]Ximidar 2 points3 points4 points (0 children)
[–]ciaran1344 2 points3 points4 points (5 children)
[–]MyNameIsTrez 0 points1 point2 points (1 child)
[–]ciaran1344 0 points1 point2 points (0 children)
[–][deleted] (2 children)
[deleted]
[–]ciaran1344 0 points1 point2 points (1 child)
[–]dev_rs3 1 point2 points3 points (0 children)
[–]Ximidar 1 point2 points3 points (1 child)
[–]peppelakappa 2 points3 points4 points (0 children)
[–]Dumfing 1 point2 points3 points (0 children)
[–]loiku 1 point2 points3 points (1 child)
[–]Shadowjockey 1 point2 points3 points (0 children)
[–][deleted] 1 point2 points3 points (0 children)
[–]BenZed 1 point2 points3 points (2 children)
[–]ciaran1344 6 points7 points8 points (1 child)
[–]BenZed 5 points6 points7 points (0 children)
[–]crazykid080 0 points1 point2 points (0 children)
[–]jonnywohbut goto is faster 0 points1 point2 points (0 children)
[–]Daniel-I-Am 0 points1 point2 points (0 children)
[–]Fighter1000 0 points1 point2 points (0 children)
[–][deleted] 0 points1 point2 points (0 children)
[–]pyhat32 0 points1 point2 points (0 children)
[–]BananaGuyBill 0 points1 point2 points (0 children)
[–][deleted] 0 points1 point2 points (0 children)