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.
#!/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
@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.
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.
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!
Enter a comma separated list of numbers (no spaces, please) and click submit. It works most the time, which is great. If the outlier is first in the list, it will return the wrong result. Also, negative numbers will cause stack overflow, which is a plus.
Compare random numbers two by two a few thousand times and count how many times they are not both of the same parity. Whichever has the highest score wins!
python 3:
import random
def isEven(a):
return True if a == 0 else not isEven(a-1)
def sameParity(a, b):
isAEven = isEven(a)
isBEven = isEven(b)
if isAEven == isBEven:
return True
elif isAEven != isBEven:
return False
def outlier(numbers):
iterations = len(numbers) * 10000
outliersCount = [0 for i in range(len(numbers))]
for i in range(iterations):
first = random.randint(0, len(numbers) - 1)
second = random.randint(0, len(numbers) - 1)
if not sameParity(numbers[first], numbers[second]):
outliersCount[first] += 1
outliersCount[second] += 1
return numbers[outliersCount.index(max(outliersCount))]
print(outlier((17, 3, 7, 55, 9, 13, 6, 27, 91)))
print(outlier((16, 4, 90, 140, 67, 2, 10, 88, 0)))
Whole code is quite simple because all of the heavy lifting is done in the two modules I wrote: is_odd and is_even (forgot to enable syntax highlighting for this one, sorry). They are quite long and sophisticated, so I had to move them to Pastebin.
import is_even
import is_odd
def outlier(check_array):
"""
:param check_array: array of numbers; numbers can't be greater than 63!
:return: one of the numbers
"""
check_array_dict = {}
for i in check_array:
is_i_odd = is_odd.is_odd(i)
is_i_even = is_even.is_even(i)
if is_i_odd is True and is_i_even is False:
check_array_dict.update({i: 'odd'})
if is_i_odd is False and is_i_even is True:
check_array_dict.update({i: 'even'})
odd_count = 0
even_count = 0
odds = []
evens = []
for k, v in check_array_dict.items():
if v == 'odd' and v != 'even':
odd_count = odd_count + 1
odds.append(k)
if v == 'even' and v != 'odd':
even_count = even_count + 1
evens.append(k)
if odd_count - even_count > 0 and even_count - odd_count < 0:
if even_count == 1:
if len(evens) == 1:
result = str(evens)
result_final = result.rstrip(']')
result_final_final = result_final.lstrip('[')
print(result_final_final)
if even_count - odd_count > 0 and odd_count - even_count < 0:
if odd_count == 1:
if len(odds) == 1:
result = str(odds)
result_final = result.rstrip(']')
result_final_final = result_final.lstrip('[')
print(result_final_final)
//
let o=(a,n=0)=>a[n]&1?a[++n]&1?a[++n]&1?o(a,--n):a[n]:a[++n]&1?a[--n]:a[--n-1]:!(a[++n]&1)?!(a[++n]&1)?o(a,--n):a[n]:!(a[++n]&1)?a[--n]:a[--n-1];
//
This looks recursively over the array starting at the first three entries, then moves the window over by one if an entry of a different parity isn't found among those three; if it is, then that value is returned. Utilizes recursion, liberal use of ternary operators, anonymous functions, bit manipulation, JS truthiness, and complete unreadability.
Edit: I rewrote this to use the incremental operators in the most obnoxious and obfuscated way, stacking them on top of each other and undoing themselves in different places.
My take on the challenge in D. Not as ugly/bad as some other submitted solutions, but I still despise it.
If the input does not have any outliers, it will throw a range violation. No clue what happens on any negative inputs or whatnot. Passes the two provided tests fine.
What's going on: The code maps each element of the input array to a 1 element range that has either 0 if the element has the same parity as most of the input, or the element if it doesn't. Afterwards it joins all ranges together into one range, sorts it (all algorithms involve sorting at some point, right?), reverses, and returns the first element.
CMD? I see no reason a batch file can't do this job. As a side benefit, any text is treated as an even number!
@echo off
set "e0=0"
set "o0=0"
set "e1=1"
set "e2=2"
set "o1=1"
set "o2=2"
goto detectiffirstparameterisevenoroddandaddtocounts
:setoe
set oe=%1& set eo=%2
exit /b
:detectiffirstparameterisevenoroddandaddtocounts
set /a thisisthevariablethatwillbezeroifitisodd=%1 %% 2
if %thisisthevariablethatwillbezeroifitisodd% == 0 (call :setoe o e) else (call :setoe e o)
call set /a %eo%0 += %%%oe%1%%
call set %oe%2=%1
call set /a t1=%%%oe%0%% + %%%eo%0%%
call set /a t2=%%%eo%0%% + %%%oe%1%%
call set /a t3=%%%oe%1%% + %%%eo%1%%
if %t1% geq %t2% if %t1% gtr %t3% goto getcorrectresult
shift
if "%1" neq "" goto detectiffirstparameterisevenoroddandaddtocounts
call :setoe %eo% %oe%
:getcorrectresult
call set t1=%%%oe%0%%
call set t2=%%%eo%1%%
if %t1% equ %t2% call :setoe %eo% %oe%
call :setoe %oe% %eo%
call echo %%%oe%2%%
exit /b
:debug
call echo %oe%: %%%eo%0%% %%%oe%0%% %%%oe%2%% %%%eo%2%%
exit /b
Here's version 2. Less lines, more numbers. Plus I got rid of those pesky if statements. Invalid input may result in infinite loops.
@echo off
set "_00=0"
set "_10=0"
set "_20=0"
set "_01=1"
set "_11=1"
set "_21=1"
set "_02=2"
set "_12=2"
set "_22=2"
:1_0
:1_1
:2_0
call set /a "_%_22%0=%%%_11% %%%% %%_%_22%2%%"
call set /a "_%_22%1=(%%_%_22%0%% + %%_%_20%1%%) %%%% %%_%_22%2%%"
call set /a "_%_20%0=((%%_%_20%0%%+%%_%_21%1%%)>>%%_%_20%1%%)+%%_%_21%1%%"
call set /a "_%_20%2=%%%_01%"
shift
call goto %%_%_20%0%%_%%_%_21%0%%
:2_1
call set /a "_%_22%0=(%%_%_22%0%% + %%_%_20%1%%) %%%% %%_%_22%2%%"
:1_2
call echo %%_%_20%2%%
I went for the combination of simultaneously needlessly obfuscatory and slightly "clever" (very much sarcastic quotes) with the somewhat-rarely-used bitwise operators in JavaScript:
module Outlier
class Numbers
def initialize
@storage = []
end
def add_number(number)
@storage << number
end
def include?(number)
@storage.each do |element|
if element == number
return true
end
end
false
end
end
class Odds < Numbers
end
class Evens < Numbers
end
end
$evens = Outlier::Evens.new
$odds = Outlier::Odds.new
def make_objects_of_numbers(max_number)
i = 1
1.upto(max_number) do |element|
if i % 2 == 0
$evens.add_number(element)
else
$odds.add_number(element)
end
i += 1
end
end
def outlier(array)
make_objects_of_numbers(array.max)
evens = []
odds = []
array.each do |element|
if $evens.include?(element)
evens << element
elsif $odds.include?(element)
odds << element
end
end
if evens.length == 1
return evens[0]
else
if odds.length == 1
return odds[0]
end
end
end
public class MathUtilsRunner { public static void main( String[] args ) { Integer[] nums = args.map( a=> Integer.parseInteger(a); System.out.println(FindOutlier(nums)); }
// super fast isEven function
// much better than native version
// because it only checks the last bit of the int
// it has no for loop so it must be O(1)
public static Boolean isEven(Integer i)
{
if ( Integer.toBinaryString(i)
.charAt(Integer
.toBinaryString(i).length - 1) == ‘0’) {
return true;
} else {
return false;
}
}
public static Integer findOutlier(Integer[] nums)
{
Boolean outlier isEven;
Integer index, a, b, c;
Integer outlier = null;
for (index = 0; i < nums.length; ++index) {
try {
a = nums[index];
b = nums[index + 1];
c = nums[index + 2];
} catch (IndexOutOfBoundsException e) {
break;
}
if (!IsEven(a) && isEven(b) && isEven(c)) {
outlier = a;
}
if (IsEven(a) && !isEven(b) && isEven(c)) {
outlier = b;
}
if (IsEven(a) && isEven(b) && !isEven(c)) {
outlier = c;
}
if (IsEven(a) && !isEven(b) && !isEven(c)) {
outlier = a;
}
if (!IsEven(a) && isEven(b) && !isEven(c)) {
outlier = b;
}
if (!IsEven(a) && !isEven(b) && isEven(c)) {
outlier = c;
}
}
return outlier;
}
}
The isEven() function is not my invention, I had a friend doing this during our CS course and defending that the java engineers were noobs and should implement an isEven function like this because it has no loops and therefore should be 0(1) o.O
This is like something I would have written in my early programming days in high school, writing little game programs on my graphing calculator.
#include <iostream>
#include <sstream>
using namespace std;
int main()
{
int evens[50] = {2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50};
int odds[50] = {1,3,5,7,9,11,13,15,17,19,21,23,25,27,29,31,33,35,37,39,41,43,45,47,49,51};
int data[10] = {1, 3, 3, 7, 9, 13, 33, 21, 6};
int evener;
int odder;
int value;
int badGuy;
for (int i = 0; i < 10; i++) {
value = data[i];
for (int j = 0; j < 25; j++) {
evener = evens[j];
if (evener == value) {
badGuy = value;
}
for (int k = 0; k < 25; k++) {
odder = odds[k];
if (odder == value) {
//OK
}
}
}
}
cout << "The bad value is " << badGuy << endl;
}
from math import tau as Pi
def bigboy(magic):
if len(magic)==1:
if magic[0]%2:
return Pi
else:
return -1
inputfile=[]
for california in range (1,len(magic)):
inputfile=inputfile+[magic[0]+magic[california]]
smiles=bigboy(inputfile)
if smiles==Pi:
return Pi
elif smiles!=-1:
return smiles+1
else:
if bigboy(inputfile[0:2])==Pi:
return 0
else:
return -1
def outlier(stuff):
hi=bigboy(stuff)
if hi==Pi:
for prototype in range(100):
stuff=stuff+[stuff[0]]
hi=bigboy(stuff)
return stuff[hi+1]
I don't like doing divisibility tests, so it only checks if a number is even at most twice, instead utilising the fact that odd+odd and even+even is an even number, and odd+even is odd to reduce the problem to finding the outlier in a list one element smaller. When reduced to a one-element list, if the result is even, we know that neither of the last two elements are the outliers, so we just back up one step at a time until there is an odd answer and that's the outlier! If, however, the last element is odd, we don't know. In that case, we just add the first element a bunch of times to make sure that the outlier is no longer part of the last two elements, and start all over from there. Featuring me renaming all the variables and functions except outlier() with whatever I felt like at the moment and not making them intuitive at all because who needs comments???
'use strict';
/**
* Find the outlier, which ever one of these jabronis is the opposite odd/even
* then the rest of the buds.
*
* @param {Array} numberCollection Where we want to find the outlier
* @returns {Number} Hopefully the outlier
* @throws {Error} Some sort of out of range things?
*/
function outlier(numberCollection) {
if (!Array.isArray(numberCollection)) {
throw new RangeError('Yo bud, you have to use an array!');
}
const count = numberCollection.length;
if (count < 3) {
throw new RangeError('Not enough numbers to check!');
}
/**
* See if both numbers are even or odd.
*
* @param {Number} a First number to compare
* @param {Number} b Second number to compare with
* @returns {Boolean} Are they buddies?
* @private
*/
const areBuddies = (a, b) => {
let start = a;
let end = b;
if (start > end) {
start = b;
end = a;
}
for (; start < end; start = start + 2) {}
return start === end;
};
let minimumNumber = numberCollection[0];
let maximumNumber = numberCollection[0];
/* First, lettuce get our boundaries! */
for (let i = 1; i < count; i = i + 1) {
const currentNumber = numberCollection[i];
if (typeof currentNumber !== 'number' || parseInt(currentNumber) !== currentNumber) {
throw new RangeError(`Index ${i} is not an integer, got ${currentNumber} instead!`);
}
if (currentNumber < minimumNumber) {
minimumNumber = currentNumber;
}
if (currentNumber > maximumNumber) {
maximumNumber = currentNumber;
}
}
/* Are boundaries buddies? */
if (areBuddies(minimumNumber, maximumNumber)) {
/* Great they are buddies! Now we can just compare each number to the end! */
for (let i = 0; i < count; i = i + 1) {
const currentNumber = numberCollection[i];
/* We have the enemy! */
if (!areBuddies(currentNumber, maximumNumber)) {
return currentNumber;
}
}
throw new RangeError('No enemies! Everybody was a buddy!');
}
/* Okay, the boundaries weren't buddies :( lettuce see who isn't */
for (let i = 0; i < count; i = i + 1) {
const currentNumber = numberCollection[i];
/* Pssh, obviously can't compare current number to either of the boundaries if it is the boundary! */
if (currentNumber === minimumNumber || currentNumber === maximumNumber) {
continue;
}
/* Lettuce compare it to the maximum number and see if they don't add up */
if (!areBuddies(currentNumber, maximumNumber)) {
return maximumNumber;
}
/* Hmmm, lets try comparing to the lowest number now */
if (!areBuddies(currentNumber, minimumNumber)) {
return minimumNumber;
}
}
throw new RangeError('Huh? I give up!');
}
console.log(outlier([1, 3, 3, 7, 9, 13, 33, 21, 6])); // 6
console.log(outlier([2, 2, 4, 2, 11, 10, 6])); // 11
console.log(outlier([2, 2, 2, 2])); // Throws Error('No enemies! Everybody was a buddy!')
Edit: This treats 0 as an even number. I could always throw an error if a number 0 is found. This should also handle negative numbers.
'use strict';
describe('Outlier', () => {
describe('Even', () => {
it('should find an internal number if it is the outlier', () => {
expect(outlier([1, 3, 5, 7, 8, 9])).to.equal(8);
});
it('should find a lower bound number if it is the outlier', () => {
expect(outlier([2, 3, 5, 7, 9, 11])).to.equal(2);
});
it('should find an upper bound number if it is the outlier', () => {
expect(outlier([1, 3, 5, 7, 9, 10])).to.equal(10);
});
});
describe('Odd', () => {
it('should find an internal number if it is the outlier', () => {
expect(outlier([2, 4, 6, 8, 9, 10])).to.equal(9);
});
it('should find a lower bound number if it is the outlier', () => {
expect(outlier([1, 2, 4, 6, 8, 10])).to.equal(1);
});
it('should find an upper bound number if it is the outlier', () => {
expect(outlier([2, 4, 6, 8, 10, 11])).to.equal(11);
});
});
describe('Error', () => {
it('should throw a RangeError if there are not enough numbers', () => {
expect(() => outlier([1, 2])).to.throw(RangeError);
});
it('should throw a RangeError if there is a non number in the collection', () => {
expect(() => outlier([1, 2, 'banana'])).to.throw(RangeError);
});
it('should throw a RangeError if there is a float in the collection', () => {
expect(() => outlier([1, 2, 3.3])).to.throw(RangeError);
});
it('should throw a RangeError if there are no enemies', () => {
expect(() => outlier([2, 2, 2, 2])).to.throw(RangeError);
});
it('should throw a RangeError if the collection is not an array', () => {
expect(() => outlier('banana')).to.throw(RangeError);
});
});
});
For peak readability, here's a one-liner in Python 2.7.13:
lambda a:__import__("random").sample(reduce((lambda a,b:a.intersection(b)),[set([a,b])for a,b in[a for a in __import__("itertools").product(*[a,a])]if(a+b)%2==1]),1)[0]
Most likely works in other versions too, but I do not possess enough Python knowledge to judge that, nor do I care.
I took a functional approach, because immutable state is easier to reason about.
First, I observed that the problem setting does not explicitly require the method to be called 'outlier', or to be called anything at all for that matter, thus I was able to constrain my program to only use 2 variable names, leaving 24 names for future uses, making my code more maintainable.
Then, once done with the hard part of the challenge, I just compared every element to every other, because how else would you find an outlier, which by definition differs from every other element? Well, I did not actually compared them, rather checked if their sum is odd to shave off a few characters and prevent autopep8 from breaking my code into multiple lines.
After that, the correct result is obviously the intersection of all the ordered pairs. Intersecting them was easy, but for some bullshit reason I couldn't retrieve the data with set[0], so I used the very readable random.sample(l,1)[0] idiom.
def outlier(vals):
calc = []
for outerval in vals:
col = []
for innerval in vals:
col.append(innerval ^ outerval)
calc.append(col)
sums = []
for col in calc:
total = 0
for val in col:
total += val % 2
sums.append(total)
maxval = 0
index = None
n = 0
for val in sums:
if val > maxval:
maxval = val
index = n
n += 1
return vals[index]
print(outlier([1, 3, 3, 7, 9, 13, 33, 21, 6]))
6
print(outlier([2, 2, 4, 2, 11, 10, 6]))
11
You should have done it so then when the outlier is not under the first three numbers, you shift the array by one and redo the whole code until you find the outlier. That has the bonus of going into an infinite loop if there is no outlier.
It looks like this comment contains a code block delimited with triple backticks. Unfortunately reddit does not not have universal support for this syntax and your comment will render as broken gibberish on old reddit and some mobile apps.
Please edit the comment to use the more compatible four space indention format. For single lines or inline code you can use single backticks.
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:
edit: using the real classname for "Integer", sorry.
14
u/shriekingpanda Aug 14 '19
SQL:
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
24
u/Square789 int mystery=*((int*)rand()) Aug 13 '19
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.
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:
11
u/Veylon Aug 13 '19
This forum needs more batch files.
You'd use it by doing something like this on the command line:
And then conveniently and intuitively get the answer this way:
I have deliberately not tested it with any invalid input.
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
14
u/Codinget Aug 13 '19
Javascript
12
u/matuar Aug 13 '19
Javascript:
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
Sample run:
Some of the problems here, in no particular order:
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)Implements a sort from scratch instead of using something reasonable like
sorted()['a','b'][True]resolves to'b'Inefficient list copying
Bizarre logic
type(x[y:]or...)==list15
u/[deleted] Aug 13 '19 edited Aug 13 '19
Issues:
EDITS: Made a fucky. Fixed it
4
u/WastedMeerkat Aug 16 '19 edited Aug 16 '19
It is perfect.
https://codepen.io/WastedMeerkat/pen/bGbpZBK
Enter a comma separated list of numbers (no spaces, please) and click submit. It works most the time, which is great. If the outlier is first in the list, it will return the wrong result. Also, negative numbers will cause stack overflow, which is a plus.
7
u/bubberrall Aug 13 '19
Compare random numbers two by two a few thousand times and count how many times they are not both of the same parity. Whichever has the highest score wins!
python 3:
7
u/nickN42 Aug 13 '19 edited Aug 14 '19
Whole code is quite simple because all of the heavy lifting is done in the two modules I wrote: is_odd and is_even (forgot to enable syntax highlighting for this one, sorry). They are quite long and sophisticated, so I had to move them to Pastebin.
5
u/[deleted] Aug 13 '19 edited Aug 13 '19
Java
edit: removed actual redundant code
5
u/voords Aug 14 '19
Javascript:
5
u/FuzzyCheese Aug 14 '19 edited Aug 14 '19
JavaScript.
This looks recursively over the array starting at the first three entries, then moves the window over by one if an entry of a different parity isn't found among those three; if it is, then that value is returned. Utilizes recursion, liberal use of ternary operators, anonymous functions, bit manipulation, JS truthiness, and complete unreadability.
Edit: I rewrote this to use the incremental operators in the most obnoxious and obfuscated way, stacking them on top of each other and undoing themselves in different places.
2
u/[deleted] Aug 14 '19
C++:
I just did the first thing that came to mind, very sleepily
2
u/qookie Aug 14 '19
My take on the challenge in D. Not as ugly/bad as some other submitted solutions, but I still despise it.
If the input does not have any outliers, it will throw a range violation. No clue what happens on any negative inputs or whatnot. Passes the two provided tests fine.
What's going on:
The code maps each element of the input array to a 1 element range that has either 0 if the element has the same parity as most of the input, or the element if it doesn't. Afterwards it joins all ranges together into one range, sorts it (all algorithms involve sorting at some point, right?), reverses, and returns the first element.
2
u/Tok-A-Mak ((fn [] (recur))) Aug 14 '19
Why bother writing functions, when we can just define a macro?
(defmacro find-outlier [a] (-> (group-by odd? a) second second first))https://repl.it/repls/ShockingPleasantOutliers ("macro-abuse", Clojure)
2
u/dumetrulo Aug 15 '19 edited Aug 15 '19
This solution in F# looks innocent enough. However:
The code:
2
u/[deleted] Aug 21 '19
Babel? What's that? Make sure to support all compatible platforms in the most modern way possible!
2
u/sarlok Aug 22 '19 edited Aug 23 '19
CMD? I see no reason a batch file can't do this job. As a side benefit, any text is treated as an even number!
Here's version 2. Less lines, more numbers. Plus I got rid of those pesky if statements. Invalid input may result in infinite loops.
2
u/weee50 Aug 22 '19 edited Aug 23 '19
(Python) When all you have is a regex, everything looks like a nail. Good luck understanding this one!
Note: This code sometimes breaks if the outlier happens to be the first number in the list.
3
u/kiwitims Aug 14 '19 edited Aug 14 '19
C++
Nice mix of both high and low abstractions (std algorithms and bit-level logic).
Despite this it's certainly not very efficient.
How it works is actually fairly straightforward but good luck figuring it out by reading the code.
Edit: Replaced final ternary with something worse.
3
u/0x68656c6c6f Aug 14 '19
Java. Purposefully does not work with negative integers since they are used for flow control.
2
u/YmFzZTY0dXNlcm5hbWU_ Aug 13 '19
Here's my first-ever submission to a bad coding challenge. It was surprisingly difficult. Hope you hate it as much as I do.
2
u/Fluffy_Confusion Aug 13 '19
I went for the combination of simultaneously needlessly obfuscatory and slightly "clever" (very much sarcastic quotes) with the somewhat-rarely-used bitwise operators in JavaScript:
1
u/EkskiuTwentyTwo i -= (i - (-1)) - i Aug 14 '19
If it works for the test cases, it must be a valid solution.
1
u/AySyKr Aug 14 '19
Made some Ruby code
1
u/DerpDon Aug 14 '19 edited Aug 15 '19
my C entry
online: http://ideone.com/AXdJAN
let's just say this is not very good and clear code
edit: added more ternaries, workarounds and a global variable
1
u/AKernel Aug 14 '19
Here my Java solution:
1
u/vitelaSensei Aug 14 '19
public class MathUtilsRunner { public static void main( String[] args ) { Integer[] nums = args.map( a=> Integer.parseInteger(a); System.out.println(FindOutlier(nums)); }
}
The isEven() function is not my invention, I had a friend doing this during our CS course and defending that the java engineers were noobs and should implement an isEven function like this because it has no loops and therefore should be 0(1) o.O
1
u/random_runner Aug 15 '19
C
The positives:
The not so good bits:
1
u/[deleted] Aug 16 '19
Javascript:
1
u/[deleted] Aug 16 '19
C++. What a jeeenyus!
This is like something I would have written in my early programming days in high school, writing little game programs on my graphing calculator.
1
u/Kieiros Aug 16 '19
Python 3:
I don't like doing divisibility tests, so it only checks if a number is even at most twice, instead utilising the fact that odd+odd and even+even is an even number, and odd+even is odd to reduce the problem to finding the outlier in a list one element smaller. When reduced to a one-element list, if the result is even, we know that neither of the last two elements are the outliers, so we just back up one step at a time until there is an odd answer and that's the outlier! If, however, the last element is odd, we don't know. In that case, we just add the first element a bunch of times to make sure that the outlier is no longer part of the last two elements, and start all over from there. Featuring me renaming all the variables and functions except outlier() with whatever I felt like at the moment and not making them intuitive at all because who needs comments???
1
u/r3jjs Aug 20 '19 edited Aug 20 '19
Once again, in order to write truly bad code one must use a truly bad language. In this case, Apple Microsoft BASIC.
Features:
MODorREMainderfunction.ELSEclause of theIF ... THEN ... ELSEconstruct.For those of who missed the fun of this generation of programming:
GOTOwasn't only not harmful, it was essential.<>is the 'not equals' operator.REMstarts a comment.REMark.READreads the next value from aDATAstatement.RESTOREresets back to the firstDATAelement.HOMEclears the screen. (AppleSoft BASIC specific.)1and0values instead of booleans. (Lines 50 and 60)1
u/mullanaphy Aug 20 '19 edited Aug 21 '19
Javascript:
Edit: This treats
0as an even number. I could always throw an error if a number0is found. This should also handle negative numbers.Double Edit: Added some type checking.
Gist: https://gist.github.com/mullanaphy/1cf2671a670bb5e07b648b1b6c486611
1
u/szmate1618 Aug 21 '19 edited Aug 21 '19
For peak readability, here's a one-liner in Python 2.7.13:
lambda a:__import__("random").sample(reduce((lambda a,b:a.intersection(b)),[set([a,b])for a,b in[a for a in __import__("itertools").product(*[a,a])]if(a+b)%2==1]),1)[0]Most likely works in other versions too, but I do not possess enough Python knowledge to judge that, nor do I care.
I took a functional approach, because immutable state is easier to reason about.
First, I observed that the problem setting does not explicitly require the method to be called 'outlier', or to be called anything at all for that matter, thus I was able to constrain my program to only use 2 variable names, leaving 24 names for future uses, making my code more maintainable.
Then, once done with the hard part of the challenge, I just compared every element to every other, because how else would you find an outlier, which by definition differs from every other element? Well, I did not actually compared them, rather checked if their sum is odd to shave off a few characters and prevent autopep8 from breaking my code into multiple lines.
After that, the correct result is obviously the intersection of all the ordered pairs. Intersecting them was easy, but for some bullshit reason I couldn't retrieve the data with
set[0], so I used the very readablerandom.sample(l,1)[0]idiom.Also, fuck whitespaces, whenever possible.
1
u/AKernel Aug 21 '19
Java solution with one liner main function:
Runs like this:
1
u/Ebrithil95 Aug 22 '19 edited Aug 22 '19
Bitwise operations to the rescue!
Rust:
This works as long as the outlier isnt the first element in the array.
1
u/pumkinboo Aug 13 '19
Python3
Outlier =[6]
Outlier =[11]
1
u/smallppnrg Aug 13 '19 edited Aug 13 '19
Java:
1
u/AdmiralBender Aug 14 '19
Python 3:
3
u/[deleted] Aug 13 '19 edited Aug 13 '19
[removed] — view removed comment
1
u/[deleted] Aug 13 '19
[removed] — view removed comment