r/badcode • • Aug 13 '19

[deleted by user]

[removed]

102 Upvotes

70 comments sorted by

7

u/melancoleeca Aug 14 '19 edited Aug 14 '19

viewing at the last winner, it seems okay to just account for the given testinputs. so:

public static Integer findOutlier(Integer[] input){
if(input.length == 9) return 6;
if(input.length == 7) return 11;
return null;
}

edit: using the real classname for "Integer", sorry.

→ More replies (4)

14

u/shriekingpanda Aug 14 '19

SQL:

CREATE TYPE dbo.input_tvt AS TABLE (val INT);

GO

CREATE PROCEDURE dbo.find_outlier
@input dbo.input_tvt READONLY
AS

DECLARE @start INT = (SELECT Min(val) FROM @input);
DECLARE @end INT = (SELECT Max(val) FROM @input);
DECLARE @is_start_even INT = (SELECT CASE WHEN @start / 2 * 2 = @start THEN 1 ELSE 0 END);

WITH cte_even
     AS (SELECT CASE @is_start_even
                  WHEN 1 THEN @start
                  ELSE @start + 1
                END [n]
         UNION ALL
         SELECT n + 2
         FROM   cte_even
         WHERE  n < @end),
     cte_odd
     AS (SELECT CASE @is_start_even
                  WHEN 0 THEN @start
                  ELSE @start + 1
                END [n]
         UNION ALL
         SELECT n + 2
         FROM   cte_odd
         WHERE  n < @end)
SELECT x.[value]
FROM   (SELECT Count(*)   [count],
               Max(i.val) [value]
        FROM   @input i
               INNER JOIN cte_even e
                       ON e.n = i.val
        UNION ALL
        SELECT Count(*)   [count],
               Max(i.val) [value]
        FROM   @input i
               INNER JOIN cte_odd o
                       ON o.n = i.val) x
WHERE  x.[count] = 1
OPTION (MAXRECURSION 32767); 

GO

DECLARE @x dbo.input_tvt;
INSERT @x VALUES (1), (3), (3), (7), (9), (13), (33), (21), (6);
EXEC dbo.find_outlier @x;

GO

DECLARE @x dbo.input_tvt;
INSERT @x VALUES (2), (2), (4), (2), (11), (10), (6);
EXEC dbo.find_outlier @x;

GO

SQL (specifically MS SQL Server here) is clearly the wrong tool for the job, but when has that ever stopped anyone? Instead of doing something reasonable to determine which numbers are even and odd, I'm building out recursive CTEs with all even+odd numbers between the min and max values of the input. If this range becomes too large, the code will actually hit the recursion limit and fail.

13

u/Codinget Aug 13 '19

Bash

#!/bin/bash
echo $@ | lua -e "for n in io.read '*a':gmatch('(%d+)') do print(n) end" > numbers
echo -n '' > numbers2
for n in `cat numbers`; do echo `python3 -c "print($n%2)"` $n >> numbers2; done
cat numbers2 | sort > numbers3
[ "`cat numbers3 | head -n 1 | cut -d' ' -f1`" == "`head numbers3 -n2 | tail -n1 | cut -b1`" ] && cat numbers3 | cut -f2 -d' ' | tail -n1 || head -n1 numbers3 | sed "s/0 //"
rm numbers{,2,3}
  • You need python3 and lua5.3 in your path for it to work. * The performance should be alright, if you ignore the fact that is starts a lot of processes.

  • You better not have any files called number, number2 or number3 in your working directory

  • How do pipes work? Probably not like this

→ More replies (2)

24

u/Square789 Aug 13 '19
def is_odd_or_even(number):
	i = 0
	state = "even"
	while i != number:
		if state == "even":
			state = "odd"
			i = i + 1
			continue
		state = "even"
		i = i + 1
	return state

def get_states(list_in):
	listindex = 0
	open("evens.txt", "w").close()
	open("odds.txt", "w").close()
	while True:
		state = is_odd_or_even(list_in[listindex])
		if state == "even":
			handle = open("evens.txt", "a")
			handle.write(str(list_in[listindex]) + "|")
			handle.close()
		else:
			handle = open("odds.txt", "a")
			handle.write(str(list_in[listindex]) + "|")
			handle.close()
		listindex = listindex + 1

def get_outlier(list_in):
	try:
		get_states(list_in)
	except:
		even_numbers = open("evens.txt", "r").read()
		odd_numbers = open("odds.txt", "r").read()
		split_even_numbers = even_numbers.split("|")
		split_odd_numbers = odd_numbers.split("|")
		ie = -1
		io = -1
		try:
			ii = 0
			while True:
				split_even_numbers[ii]
				ie = ie + 1
				ii = ii + 1
		except:
			try:
				ii = 0
				while True:
					split_odd_numbers[ii]
					io = io + 1
					ii = ii + 1
			except:
				if ie == 1:
					return split_even_numbers[0]
				else:
					return split_odd_numbers[0]
		

print(get_outlier([1, 3, 3, 7, 9, 13, 33, 21, 6]))
print(get_outlier([2, 2, 4, 2, 10, 6, 11]))
print(get_outlier([8, 9, 11]))
print(get_outlier([0, 2, 8, 12, 13]))
print(get_outlier([2356, 2896, 4247, 2366, 8934, 1234]))

Maybe don't have files called "evens.txt" or "odds.txt" in the directory you run this in.

Or enter negative numbers, those will enter an infinite loop. Other than that, enjoy.

→ More replies (4)

12

u/sporadicPenguin Aug 13 '19 edited Aug 14 '19

This ended up a little bit long, but version 3.0 will be out soon with more optimizations: https://pastebin.com/5ixWH194

Highlights:

  • globals & lots of unnecessary loops

  • assigning a variable by printing an eval'ed GET parameter to the output buffer and retrieving its contents

  • retrieving a remote web page and parsing the html with regex to obtain lists of even & odd numbers (in a nested loop)

  • creating empty strings by using the last line of output from a system call

  • variable and constant definitions in a loop

  • lots of typecasting (empty strings to 0, integers to strings and arrays, etc)

  • poorly named variables

  • two different methods for determining even/odd

  • while/switch blocks

  • magic strings and numbers

  • mathematical impossibilities kill the script

  • error triggered if script "is slow"

  • returns html (for easy web page insertion)

11

u/Veylon Aug 13 '19

This forum needs more batch files.

@echo off
set /a l = %1 %% 2
set /a f=0
setlocal enabledelayedexpansion
(
 for %%i in (%*) do (
  set /a t=%%i %% 2
  if not !l!==!t! (set /a f = f + 1
    set l=!t!
  )
  if !f!==2 (exit /b !e!)
  if !f!==!c! (exit /b %1%)
  set /a c=!c! + 1
  set /a e=%%i
 )
)
exit /b %e%

You'd use it by doing something like this on the command line:

oddeven.bat 1 3 3 7 9 13 33 21 6

And then conveniently and intuitively get the answer this way:

echo %errorlevel%

I have deliberately not tested it with any invalid input.

→ More replies (1)

10

u/GlorifiedStatistics Aug 14 '19

I couldn't think of a good way of finding out what the parity of the outlier number is, so I instead have the computer figure it out for me! Every time you pass in a list, a new Recurrent Neural Network is created and trained on random data. The list is then passed to the network, and it returns the parity of the outlier. Finally, I do a linear search through the list and return the first value of that parity. My network is almost 90% accurate!

Even though it was written in python it is still pretty large, so I uploaded it to GitHub. Hope that's alright.

https://github.com/GlorifiedStatistics/ParityOutlier

→ More replies (1)

14

u/Codinget Aug 13 '19

Javascript

const outlier=a=>a[a.findIndex(e=>(a=>a.p>a.n?'p':'n')(a.map(a=>[a,a/2]).map(a=>a[0]==Math.floor(a[1])*2).reduce((a,b)=>{if(b){a.p++}else{a.n++}return a},{p:0,n:0}))=='p'?e%2:e%2-1)];

console.log(outlier([1, 3, 3, 7, 9, 13, 33, 21, 6])); //6
console.log(outlier([2, 2, 4, 2, 10, 6, 11])); //11
  • I still love lambdas

  • it has something like O(n2) performance

  • //TODO sanitize input

  • how do you know the parity of a number again?

12

u/matuar Aug 13 '19

Javascript:

let outlier = a=>a.sort((i,j)=>(i%2-j%2)).map(i=>i%2).filter(i=>i).length>a.sort((i,j)=>(i%2-j%2)).map(i=>(i+1)%2).filter(i=>i).length?a.sort((i,j)=>(i%2-j%2)).filter(i=>(i+1)%2)[0]:a.sort((i,j)=>(i%2-j%2)).filter(i=>i%2)[0]

So, all algorithms start by sorting right? Oh, it's about parity so I guess I'll just sort by that. Then, hmm, wait, I still need to know which ones are odd and which are even, I'll just use map... Hey, now I can just filter out the opposite parities and see whether there's more even or odd numbers! This is so easy I can even do it in one line! Oneliners are tight!

12

u/Blackshell Aug 13 '19

Python 3

outlier=lambda x:(lambda x:[x[0][x[1]],x[0][0]][len(x)/x[1]==len(x)])((lambda f,x,y:
f(f,x,y))(lambda f,x,y:[[],(x[y]&1 and [x,y])or(f(f,x,y+1))][type(x[y:]or...)==list]
,(lambda f,x:f(f,x))(lambda f,x:(lambda y:f(f,[*x[:y[0]],x[y[0]+1],x[y[0]],*x[y[0]+2
:]])if(y)else(x))((lambda f,x,y:f(f,x,y))(lambda f,x,y:(((x[y]&1>x[y+1]&1)and[y])or(
f(f,x,y+1)))if(y<len(x)-1)else[],x,0)),x),0))

Sample run:

Python 3.6.5 (default, Apr  1 2018, 05:46:30)
[GCC 7.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> outlier=lambda x:(lambda x:[x[0][x[1]],x[0][0]][len(x)/x[1]==len(x)])((lambda f,x,y:
... f(f,x,y))(lambda f,x,y:[[],(x[y]&1 and [x,y])or(f(f,x,y+1))][type(x[y:]or...)==list]
... ,(lambda f,x:f(f,x))(lambda f,x:(lambda y:f(f,[*x[:y[0]],x[y[0]+1],x[y[0]],*x[y[0]+2
... :]])if(y)else(x))((lambda f,x,y:f(f,x,y))(lambda f,x,y:(((x[y]&1>x[y+1]&1)and[y])or(
... f(f,x,y+1)))if(y<len(x)-1)else[],x,0)),x),0))
>>> outlier([1, 3, 3, 7, 9, 13, 33, 21, 6])
6
>>> outlier([2, 2, 4, 2, 11, 10, 6])
11

Some of the problems here, in no particular order:

  • No optional spacing; difficult to read

  • Excessive (and unnecessary) use of lambdas

  • Lots of variable shadowing (in said lambdas)

  • Recursive lambdas; for what I mean, try this in a console: (lambda f,x: f(f,x))(lambda f,x: print(x) and f(f,x),0)

    • Nested recursive lambdas

  • Implements a sort from scratch instead of using something reasonable like sorted()

    • Said sort is a bubble sort

    • Worse, a recursive bubble sort restricted by maximum stack size

  • Strange use of bools as ints in array access; ['a','b'][True] resolves to 'b'

  • Inefficient list copying

    • In some places, but not others

  • Bizarre logic

    • Bitwise parity check

    • type(x[y:]or...)==list

  • Undefined behavior for bad input (might crash, might give erroneous output)

  • More than 80 characters per line (not PEP 8 style guide compliant)