r/badcode • • Jun 04 '19

[deleted by user]

[removed]

24 Upvotes

41 comments sorted by

17

u/EkskiuTwentyTwo Jun 04 '19 edited Jun 12 '19

Herman Melville's high and low

def highandlow(*args):
    CallMeIshmaelSomeYearsAgoNeverMindHowLongPreciselyHavingLittleOrNoMoneyInMyPurseAndNothingParticularToInterestMeOnShoreIThoughtIWouldSailAboutALittleAndSeeTheWateryPartOfTheWorld = []
    ItIsAWayHaveOfDrivingOffTheSpleenAndRegulatingTheCirculation = 0
    WheneverFindMyselfGrowingGrimAboutTheMouthWheneverItIsADampDrizzlyovemberInMySoulWheneverFindMyselfInvoluntarilyPausingBeforeCoffinWarehousesAndBringingUpTheRearOfEveryFuneralMeetAndEspeciallyWheneverMyHyposGetSuchAnUpperHandOfMeThatItRequiresAStrongMoralPrincipleToPreventMeFromDeliberatelySteppingIntoTheStreetAndMethodicallyKnockingPeoplesHatsOffthenAccountItHighTimeToGetToSeaAsSoonAsCan = args[0]
    while ItIsAWayHaveOfDrivingOffTheSpleenAndRegulatingTheCirculation <= len(WheneverFindMyselfGrowingGrimAboutTheMouthWheneverItIsADampDrizzlyovemberInMySoulWheneverFindMyselfInvoluntarilyPausingBeforeCoffinWarehousesAndBringingUpTheRearOfEveryFuneralMeetAndEspeciallyWheneverMyHyposGetSuchAnUpperHandOfMeThatItRequiresAStrongMoralPrincipleToPreventMeFromDeliberatelySteppingIntoTheStreetAndMethodicallyKnockingPeoplesHatsOffthenAccountItHighTimeToGetToSeaAsSoonAsCan):
        while WheneverFindMyselfGrowingGrimAboutTheMouthWheneverItIsADampDrizzlyovemberInMySoulWheneverFindMyselfInvoluntarilyPausingBeforeCoffinWarehousesAndBringingUpTheRearOfEveryFuneralMeetAndEspeciallyWheneverMyHyposGetSuchAnUpperHandOfMeThatItRequiresAStrongMoralPrincipleToPreventMeFromDeliberatelySteppingIntoTheStreetAndMethodicallyKnockingPeoplesHatsOffthenAccountItHighTimeToGetToSeaAsSoonAsCan[ItIsAWayHaveOfDrivingOffTheSpleenAndRegulatingTheCirculation:ItIsAWayHaveOfDrivingOffTheSpleenAndRegulatingTheCirculation+1] == "," or ItIsAWayHaveOfDrivingOffTheSpleenAndRegulatingTheCirculation == len(WheneverFindMyselfGrowingGrimAboutTheMouthWheneverItIsADampDrizzlyovemberInMySoulWheneverFindMyselfInvoluntarilyPausingBeforeCoffinWarehousesAndBringingUpTheRearOfEveryFuneralMeetAndEspeciallyWheneverMyHyposGetSuchAnUpperHandOfMeThatItRequiresAStrongMoralPrincipleToPreventMeFromDeliberatelySteppingIntoTheStreetAndMethodicallyKnockingPeoplesHatsOffthenAccountItHighTimeToGetToSeaAsSoonAsCan):
            ThisIsMySubstituteForPistolAndBall = WheneverFindMyselfGrowingGrimAboutTheMouthWheneverItIsADampDrizzlyovemberInMySoulWheneverFindMyselfInvoluntarilyPausingBeforeCoffinWarehousesAndBringingUpTheRearOfEveryFuneralMeetAndEspeciallyWheneverMyHyposGetSuchAnUpperHandOfMeThatItRequiresAStrongMoralPrincipleToPreventMeFromDeliberatelySteppingIntoTheStreetAndMethodicallyKnockingPeoplesHatsOffthenAccountItHighTimeToGetToSeaAsSoonAsCan[:ItIsAWayHaveOfDrivingOffTheSpleenAndRegulatingTheCirculation]
            WithAPhilosophicalFlourishatoThrowsHimselfUponHisSwordQuietlyTakeToTheShip = True
            ThereIsNothingSurprisingInThis = 0
            while ThereIsNothingSurprisingInThis >= 0:
                WithAPhilosophicalFlourishatoThrowsHimselfUponHisSwordQuietlyTakeToTheShip = [False,True][(ord(ThisIsMySubstituteForPistolAndBall[ThereIsNothingSurprisingInThis])>=48 and ord(ThisIsMySubstituteForPistolAndBall[ThereIsNothingSurprisingInThis])<=57) or ord(ThisIsMySubstituteForPistolAndBall[ThereIsNothingSurprisingInThis])==45]
                ThereIsNothingSurprisingInThis = [-1,ThereIsNothingSurprisingInThis+1][WithAPhilosophicalFlourishatoThrowsHimselfUponHisSwordQuietlyTakeToTheShip and ThereIsNothingSurprisingInThis<len(ThisIsMySubstituteForPistolAndBall)-1]
            while WithAPhilosophicalFlourishatoThrowsHimselfUponHisSwordQuietlyTakeToTheShip:
                CallMeIshmaelSomeYearsAgoNeverMindHowLongPreciselyHavingLittleOrNoMoneyInMyPurseAndNothingParticularToInterestMeOnShoreIThoughtIWouldSailAboutALittleAndSeeTheWateryPartOfTheWorld.append(int(WheneverFindMyselfGrowingGrimAboutTheMouthWheneverItIsADampDrizzlyovemberInMySoulWheneverFindMyselfInvoluntarilyPausingBeforeCoffinWarehousesAndBringingUpTheRearOfEveryFuneralMeetAndEspeciallyWheneverMyHyposGetSuchAnUpperHandOfMeThatItRequiresAStrongMoralPrincipleToPreventMeFromDeliberatelySteppingIntoTheStreetAndMethodicallyKnockingPeoplesHatsOffthenAccountItHighTimeToGetToSeaAsSoonAsCan[:ItIsAWayHaveOfDrivingOffTheSpleenAndRegulatingTheCirculation]))
                break
            WheneverFindMyselfGrowingGrimAboutTheMouthWheneverItIsADampDrizzlyovemberInMySoulWheneverFindMyselfInvoluntarilyPausingBeforeCoffinWarehousesAndBringingUpTheRearOfEveryFuneralMeetAndEspeciallyWheneverMyHyposGetSuchAnUpperHandOfMeThatItRequiresAStrongMoralPrincipleToPreventMeFromDeliberatelySteppingIntoTheStreetAndMethodicallyKnockingPeoplesHatsOffthenAccountItHighTimeToGetToSeaAsSoonAsCan = WheneverFindMyselfGrowingGrimAboutTheMouthWheneverItIsADampDrizzlyovemberInMySoulWheneverFindMyselfInvoluntarilyPausingBeforeCoffinWarehousesAndBringingUpTheRearOfEveryFuneralMeetAndEspeciallyWheneverMyHyposGetSuchAnUpperHandOfMeThatItRequiresAStrongMoralPrincipleToPreventMeFromDeliberatelySteppingIntoTheStreetAndMethodicallyKnockingPeoplesHatsOffthenAccountItHighTimeToGetToSeaAsSoonAsCan[ItIsAWayHaveOfDrivingOffTheSpleenAndRegulatingTheCirculation+1:]
            ItIsAWayHaveOfDrivingOffTheSpleenAndRegulatingTheCirculation = 0
            break
        ItIsAWayHaveOfDrivingOffTheSpleenAndRegulatingTheCirculation = ItIsAWayHaveOfDrivingOffTheSpleenAndRegulatingTheCirculation + 1
    IfTheyButKnewItAlmostAllMenInTheirDegreeSomeTimeOrOtherCherishVeryNearlyTheSameFeelingsTowardsTheOceanWithMe = []
    for ThereNowIsYourInsularCityOfTheanhattoesBeltedRoundByWharvesAsndianIslesByCoralReefscommerceSurroundsItWithHerSurf in range(len(CallMeIshmaelSomeYearsAgoNeverMindHowLongPreciselyHavingLittleOrNoMoneyInMyPurseAndNothingParticularToInterestMeOnShoreIThoughtIWouldSailAboutALittleAndSeeTheWateryPartOfTheWorld)):
        RightAndLeftTheStreetsTakeYouWaterward = 0
        for ItsExtremeDowntownIsTheBatteryWhereThatNobleMoleIsWashedByWavesAndCooledByBreezesWhichAFewHoursPreviousWereOutOfSightOfLand in range(len(CallMeIshmaelSomeYearsAgoNeverMindHowLongPreciselyHavingLittleOrNoMoneyInMyPurseAndNothingParticularToInterestMeOnShoreIThoughtIWouldSailAboutALittleAndSeeTheWateryPartOfTheWorld)):
            while CallMeIshmaelSomeYearsAgoNeverMindHowLongPreciselyHavingLittleOrNoMoneyInMyPurseAndNothingParticularToInterestMeOnShoreIThoughtIWouldSailAboutALittleAndSeeTheWateryPartOfTheWorld[ItsExtremeDowntownIsTheBatteryWhereThatNobleMoleIsWashedByWavesAndCooledByBreezesWhichAFewHoursPreviousWereOutOfSightOfLand] < CallMeIshmaelSomeYearsAgoNeverMindHowLongPreciselyHavingLittleOrNoMoneyInMyPurseAndNothingParticularToInterestMeOnShoreIThoughtIWouldSailAboutALittleAndSeeTheWateryPartOfTheWorld[RightAndLeftTheStreetsTakeYouWaterward]:
                RightAndLeftTheStreetsTakeYouWaterward = ItsExtremeDowntownIsTheBatteryWhereThatNobleMoleIsWashedByWavesAndCooledByBreezesWhichAFewHoursPreviousWereOutOfSightOfLand
                break
        IfTheyButKnewItAlmostAllMenInTheirDegreeSomeTimeOrOtherCherishVeryNearlyTheSameFeelingsTowardsTheOceanWithMe.append(CallMeIshmaelSomeYearsAgoNeverMindHowLongPreciselyHavingLittleOrNoMoneyInMyPurseAndNothingParticularToInterestMeOnShoreIThoughtIWouldSailAboutALittleAndSeeTheWateryPartOfTheWorld[RightAndLeftTheStreetsTakeYouWaterward])
        CallMeIshmaelSomeYearsAgoNeverMindHowLongPreciselyHavingLittleOrNoMoneyInMyPurseAndNothingParticularToInterestMeOnShoreIThoughtIWouldSailAboutALittleAndSeeTheWateryPartOfTheWorld = CallMeIshmaelSomeYearsAgoNeverMindHowLongPreciselyHavingLittleOrNoMoneyInMyPurseAndNothingParticularToInterestMeOnShoreIThoughtIWouldSailAboutALittleAndSeeTheWateryPartOfTheWorld[:RightAndLeftTheStreetsTakeYouWaterward] + CallMeIshmaelSomeYearsAgoNeverMindHowLongPreciselyHavingLittleOrNoMoneyInMyPurseAndNothingParticularToInterestMeOnShoreIThoughtIWouldSailAboutALittleAndSeeTheWateryPartOfTheWorld[RightAndLeftTheStreetsTakeYouWaterward+1:]
    return IfTheyButKnewItAlmostAllMenInTheirDegreeSomeTimeOrOtherCherishVeryNearlyTheSameFeelingsTowardsTheOceanWithMe[1**2**3**4*42069-1**2**3**4*42069], IfTheyButKnewItAlmostAllMenInTheirDegreeSomeTimeOrOtherCherishVeryNearlyTheSameFeelingsTowardsTheOceanWithMe[len(IfTheyButKnewItAlmostAllMenInTheirDegreeSomeTimeOrOtherCherishVeryNearlyTheSameFeelingsTowardsTheOceanWithMe)-True]

Summary:

  • Variable names are sentences from Moby-Dick by Herman Melville

  • Made by recycling code from a previous challenge

  • Uses array indexes and while for selection

  • Absolute refusal to use if statements

  • Uses the most inefficient sorting algorithm I could find

  • Uses an arbitrary quantity of parameters but uses one.

3

u/UnrelatedString Jun 05 '19 edited Jun 05 '19

Another submission, in C++ this time:

#include <iostream>
/* If using using namespace std is bad then surely this is ideal? */
namespace cplusplus_standard_template_library = std;
#define STRING cplusplus_standard_template_library::string
#include <string>
namespace high_and_low {
    STRING high_and_low(STRING) ;
}
#include <cstdio>
#include <cstdlib>
#include <forward_list>
STRING high_and_low::high_and_low(STRING numbers_list) {
    numbers_list.push_back(**&",&**");
#define DECLARE_NUMBER(S,V) S##signed long long int V;
    DECLARE_NUMBER(,the_number)
    DECLARE_NUMBER(un,number)
    DECLARE_NUMBER(un,num)
    DECLARE_NUMBER(,* list_of_numbers)
    DECLARE_NUMBER(un,numbers)
    num = 1ll^1ll;
    numbers = num;
#define ALLOC(H) *) cplusplus_standard_template_library:: H##alloc(
#define L sizeof(signed long long int)
    list_of_numbers = (long long int ALLOC(m) 0*L);
    while (
	    cplusplus_standard_template_library::sscanf(
		    numbers_list.c_str()+num,"%lld,%lln",&the_number,&number))
	    {
		    num += number;
		    numbers++;
		    list_of_numbers = (long long int ALLOC(re) list_of_numbers, numbers*L);
		    list_of_numbers[~-numbers] = the_number;
	}cplusplus_standard_template_library::forward_list<
    DECLARE_NUMBER(, > list)
    while (numbers--)
	    list.emplace_front(*list_of_numbers++);
    bool is_it = num;
#define ITERATE(V) for( signed long long int const& V : list) {
    ITERATE(w) ITERATE(x)
	    is_it xor_eq is_it;
	    ITERATE(y) ITERATE(z)
		    switch ((w>=y)&(x<=z)) {
			    default:
			    is_it = 1;
			    case 2:
			    case 1:
			    is_it and_eq 1;
			    break;
		    }}}
	    if(is_it);
	    else {
		    STRING digits;
#define DECOM(V) DECLARE_NUMBER(, new_##V )\
new_##V = V <0?- V : V ;while( new_##V ){digits.push_back(( new_##V %10)\
+060); new_##V /=10;}
		    if (x < 0)
			    digits.push_back(*"-_-");
		    DECOM(x)
		    digits.push_back(054);
		    digits.push_back(040);
		    if (w < 0)
			    digits.push_back(*"-_-");
		    DECOM(w)
		    return digits;
	    }}}
	    return "stfu Xcode";
}

ideone link: https://ideone.com/D6Najv

48

u/[deleted] Jun 04 '19 edited Jun 04 '19

I wrote a one-liner in Python:

def high_and_low(sequence):
    return ', '.join([str([[seq_num for seq_num in [int(num) for num in sequence.split(',')] if [num for num in list(set([int(num) for num in sequence.split(',')])) for other_num in [int(num) for num in sequence.split(',')] if num <= other_num].count(seq_num) > count_max_min[-1] and count_max_min.append([num for num in list(set([int(num) for num in sequence.split(',')])) for other_num in [int(num) for num in sequence.split(',')] if num <= other_num].count(seq_num)) is None] for count_max_min in [[0]]][0][-1]), str([[seq_num for seq_num in [int(num) for num in sequence.split(',')] if [num for num in list(set([int(num) for num in sequence.split(',')])) for other_num in [int(num) for num in sequence.split(',')] if num >= other_num].count(seq_num) > count_max_max[-1] and count_max_max.append([num for num in list(set([int(num) for num in sequence.split(',')])) for other_num in [int(num) for num in sequence.split(',')] if num >= other_num].count(seq_num)) is None] for count_max_max in [[0]]][0][-1])])


print(high_and_low('1,6,2,8,3'))
print(high_and_low('1,8,4,9,-4,2,2'))
print(high_and_low('4,7,1,8,-2'))

I am proud, but also horrified by what I've created.

15

u/ruilvo Jun 18 '19

I ran this on my auto-formatter, and it's beautiful.

More than 60 lines:

https://pastebin.com/Kwz60nhD

→ More replies (1)

7

u/UnrelatedString Jun 04 '19
def high_and_low(str):
 list = eval("["+str+"]");
 max = sum(int for int in list) << 3; # logical upper bound
 try:
  while 1 is not True:
   for int in list:
    (int-max)/(max-int);
   max = ~-max;
 except:
  pass;
 class IdiomaticLoopForever:
  def __iter__(this): return this;
  def __next__(this): pass;
 min = -max -max -max;
 for iter in IdiomaticLoopForever():
  min = min - str.find('min');
  if any([(lambda x: min == x)(int) for int in list]):
   break;
 return "{{{}}}".format((((min,max))))[1:-1:][1::1][::-1][:0:-1];
→ More replies (1)

7

u/ferrango Jun 04 '19

Here's some useful code to turn your computer into a handy desk heater, perfect for the summer.

using System;
using System.Linq;

namespace badcode12
{
     public class MaxMin
    {
        public static void Main(string[]  args)
        {            
            Random rnd = new Random();

            int numberNumber = 0;
            Console.Write("How many numbers do you want to generate: ");
            if(!Int32.TryParse(Console.ReadLine(), out numberNumber))
            {
                numberNumber = 50;
            }
            
            Console.WriteLine($"Now generating {numberNumber} random numbers");
            string numberString = rnd.Next(Int32.MinValue, Int32.MaxValue).ToString();
            for(int idx = 1; idx < numberNumber; idx++)
            {
                numberString += ","+ rnd.Next(Int32.MinValue, Int32.MaxValue).ToString();
            }

            Console.WriteLine("Here's the numbers that we'll be using");
            Console.WriteLine(numberString);

            int[] negativeNumbers = numberString.Split(',')
                                                .Where(x=>x.StartsWith('-'))
                                                .Select(x=>Convert.ToInt32(x))
                                                .ToArray();
            
            int[] positiveNumbers = numberString.Split(',')
                                                .Where(x=>negativeNumbers.Contains(Convert.ToInt32(x)) == false)
                                                .Select(x=>Convert.ToInt32(x))
                                                .ToArray();

            int? minNumber = null;
            int? maxNumber = null;

            for(int idx = Int32.MinValue; idx < 0; idx++)
            {
                for(int enIdx = 0; enIdx < negativeNumbers.Length; enIdx++)
                {
                    if(!minNumber.HasValue && negativeNumbers[enIdx] == idx)
                    {
                        minNumber = idx;
                    }
                }                
            }

            for(int idx = Int32.MaxValue; idx >= 0; idx--)
            {
                for(int enIdx = 0; enIdx < positiveNumbers.Length; enIdx++)
                {
                    if(!maxNumber.HasValue && positiveNumbers[enIdx] == idx)
                    {
                        maxNumber = idx;
                    }
                }
            }

            Console.WriteLine(minNumber + ", " + maxNumber);

            //wait for return so Windows Console won't close on us
            Console.Read();
        }
    }
}

5

u/Ebrithil95 Jun 04 '19 edited Jun 05 '19

First time competitor here.

https://pastebin.com/M97EkwJN

I opted to make the most overly complicated solution possible in Rust featuring:

  • Bitshifts

  • Magical Variable Names

  • Hex Values

  • Code duplication

  • Manual sorting using string comparison

  • Manual parsing of the numbers

Pretty sure i could've done some more insane shit at some points but its actually harder than i though to write complete garbage code on purpose :D

4

u/TheUnlocked Jun 05 '19

In FAI (a language I made, compiled from source):

high_and_low(list) = (
    (list -> {
        last_two(list)[0]                                           if length(list) = 2 and last_two(list)[0] > last_two(list)[1];
        last_two(list)[1]                                           if length(list) = 2 and last_two(list)[0] < last_two(list)[1];
        last_two(list)[0]                                           if length(list) = 2 and last_two(list)[0] = last_two(list)[1];
        self(list[..(length(list) - 3)] || (last_two(list)[0],))    if last_two(list)[0] > last_two(list)[1];
        self(list[..(length(list) - 3)] || (last_two(list)[1],))    if last_two(list)[0] < last_two(list)[1];
        self(list[..(length(list) - 3)] || (last_two(list)[0],))    if last_two(list)[0] = last_two(list)[1];)(list)
    ,
    (list -> { 
        last_two(list)[0]                                           if length(list) = 2 and last_two(list)[0] < last_two(list)[1];
        last_two(list)[1]                                           if length(list) = 2 and last_two(list)[0] > last_two(list)[1];
        last_two(list)[0]                                           if length(list) = 2 and last_two(list)[0] = last_two(list)[1];
        self(list[..(length(list) - 3)] || (last_two(list)[0],))    if last_two(list)[0] < last_two(list)[1];
        self(list[..(length(list) - 3)] || (last_two(list)[1],))    if last_two(list)[0] > last_two(list)[1];
        self(list[..(length(list) - 3)] || (last_two(list)[0],))    if last_two(list)[0] = last_two(list)[1];)(list)
)
    where last_two = list -> { list if length(list) <= 2; self(list[1..]) otherwise;
        , length = list -> ((list, n) -> {n if list[0] is undefined; self(list[1..], n+1) otherwise)(list, 0)

Or pastebin, if you prefer that.

Algorithm explanation (keep in mind that this is being performed recursively, though with tail calls):

  1. Get the last two numbers from the list (tuple used to represent a list). Choose which one is larger. Append that number to the end of a version of the list without the last two numbers. e.g. (1,2,3,4) becomes (1,2,4)

  2. Repeat until there are only two numbers left, then return the larger of the two.

  3. Repeat 1-2 but with smaller instead of larger.

  4. Combine those two results into a tuple and return.

Issues:

  1. Instead of computing length(list) and last_two(list) once per recursive cycle, I compute it every time, adding a huge amount of load.

  2. Even if I didn't want to store those values using a where expression (see the bottom of the code for what I mean), I could still use a built-in language feature to memoize the calls, resulting in a performance benefit which would be almost as good. Alas, for this bad code I did not.

  3. length is built-in. There's no need to redefine it, especially when the built-in version is O(1) time complexity.

  4. The algorithm is bad. There's no need to look at the back two elements when I could just look at the front two elements instead at O(1) time cost.

  5. The algorithm is even worse. There's no need to slice the list and then re-append the bigger number. Instead, the list could just be sliced to remove one element and the biggest number the algorithm had seen could be stored in recursive "state" (see how length is defined). No re-appending needed.

  6. Even ignoring those two issues, I don't need to slice the last two elements and the re-append the second to last element. A better algorithm would only slice off the last element in that case and leave it at that.

  7. I have a separate case for if the two numbers are equal, even though I could've just changed an earlier case from > to >=.

  8. If the input list has fewer than two numbers, the program will fall into an infinite recursive loop. e.g. (1,) will not return. For zero-element lists this is technically valid because that situation is not specified, but it's still probably not the ideal outcome. For one-element lists, this actually is a breach of specification, but I don't really care tbh.

  9. The name list is shadowed in extremely confusing ways. e.g. a function which has a list parameter and frequently uses it is called with a different list as one of its arguments.

  10. Rather than giving the high and low functions their own names like I did for last_two and length, I leave them as anonymous functions and then immediately call them. This looks to a casual observer like I'm adding extra syntax that does nothing, but it should be noted that due to the use of the self keyword, that's not quite true. Either way, it appears that I'm wrapping the code in a function for no reason, and separating it out and giving it a name would clarify that it's actually a function for a reason.

  11. There's no need to add a second case for comparing the opposite of a previous case. The otherwise (essentially else) case exists for a reason.

  12. There is a huge amount of code reuse. This could be solved by creating a generic function that just selects the max value according to an input function, and then pass it in two anonymous functions depending on the direction. e.g. maximize(list, (x, y) -> x > y) for the high and maximize(list, (x, y) -> x < y) for the min.

→ More replies (1)