| Bytes | Lang | Time | Link |
|---|---|---|---|
| 010 | Juby | 230828T144956Z | Jordan |
| 017 | Wolfram Language Mathematica | 241219T103114Z | Introduc |
| 033 | Perl 5 pa | 241216T192145Z | Xcali |
| 016 | Raku Perl 6 rakudo | 241216T171313Z | xrs |
| 063 | AWK | 241205T030845Z | xrs |
| 008 | Uiua | 240720T225535Z | nyxbird |
| 058 | Ruby | 240519T101758Z | yassine |
| 016 | APL Dyalog Unicode | 230828T154439Z | boltcapt |
| 056 | Headass | 230828T041857Z | thejonym |
| 025 | Vyxal G | 230827T175932Z | pacman25 |
| 004 | Thunno 2 h | 230827T172854Z | The Thon |
| 005 | 05AB1E | 220208T132926Z | Kevin Cr |
| 171 | C# | 191017T083352Z | Orace |
| 019 | Octave | 180415T231057Z | Luis Men |
| 029 | Julia 0.6 | 180413T222555Z | gggg |
| 209 | PHP | 180413T194808Z | Francisc |
| 003 | Japt g | 180412T163552Z | Oliver |
| 056 | SmileBASIC | 180412T171355Z | 12Me21 |
| 053 | dc | 180413T130728Z | brhfl |
| 088 | Avail | 180413T064652Z | tdhsmith |
| 028 | Octave | 180413T072605Z | Tom Carp |
| 030 | JavaScript Node.js | 180412T222616Z | Pandacod |
| 031 | R | 180412T165934Z | Giuseppe |
| 031 | Python 3 | 180412T163234Z | osuka_ |
| 004 | Pyth | 180412T155733Z | hakr14 |
| 006 | Stax | 180412T133530Z | Khuldrae |
| 039 | Java 8 | 170307T131647Z | Kevin Cr |
| 074 | C clang | 180412T130955Z | GPS |
| 015 | Perl 6 | 180412T121544Z | nwellnho |
| 062 | Python | 170307T144834Z | iwaseate |
| 081 | PHP | 170307T144526Z | Titus |
| 052 | Brachylog 2 | 170307T013029Z | user6213 |
| 064 | C++14 | 170306T001945Z | Karl Nap |
| 029 | Haskell | 170305T223639Z | nimi |
| 006 | MATL | 170304T211442Z | Sanchise |
| 035 | Python | 170304T222538Z | xnor |
| 019 | Mathematica | 170304T212007Z | LegionMa |
| 033 | JavaScript ES6 | 170304T193818Z | Arnauld |
| 004 | Jelly | 170304T191452Z | Dennis |
| 004 | Pyke | 170304T191204Z | Blue |
| 016 | 05AB1E | 170304T183212Z | Okx |
AWK, 63 bytes
BEGIN{RS=" ";l=1e9}{($0>0?$0:-$0)<(l>0?l:-l)&&l=$0}END{print l}
BEGIN{RS=" "; # separate nums into records
l=1e9} # high default temp
{($0=$0>0?$0:-$0) # abs value
<(l>0?l:-l)&&l=$0} # get smallest number
END{print l} # print
Uiua, 8 bytes
⊏⊢⍏⌵.⊏⍖.
⊏⊢⍏⌵.⊏⍖.
⊏⍖. # sort descending
⊏ ⍏⌵. # sort by ascending absolute value
⊢ # get the first element
Ruby, 58 bytes#
p ((gets;gets.split.map(&:to_i)).min_by{|x|[x.abs,-x]}||0)
Headass, 56 bytes
O{ON-)+E:U}.U+OUO[{UO(])P:N(+)+E:}.UO[U-O{UO(])P:N(+)E:}
Increments / decrements a pair of counters until the value of the counter matches one of the inputs, with the positive counter having the first go (after 0 of course) to prioritize it over negative answers.
Positive counter hereby referred to as +counter and negative counter as -counter
Code breakdown:
O{ON-)+E:U}. code block 0
O O initialize both counters to 0
{ON-) :U} put all inputs on the queue
+E then move to code block 1
. end code block
U+OUO[{UO(])P:N(+)+E:}. code block 1 (-counter, starting at 0)
U+O increment +counter and put back on queue
UO[ store 0/-counter to r2 and put back on queue
{ N(+) :} for each input
UO enqueue input
(]) if input is equal to 0/-counter
P: print value and halt
+E then go to code block 2
. end code block
UO[U-O{UO(])P:N(+)E:} code block 2 (+counter, starting at 1)
UO[ store +counter to r2 and put back on queue
U-O decrement -counter and put back on queue
{ N(+) :} for each input
UO enqueue input
(]) if input is equal to +counter
P: print value and halt
E then go to code block 1
I tried doing this with only 2 code blocks, 1 to init and one to handle both counters, but that meant that whichever value came first between positive and negative would win, which is wrong. There might be additional logic that could be added to such a loop which, combined with some more logic-golfing, could be shorter than this version, but i still think its pretty good.
Thunno 2 h, 4 bytes
ṠrþA
Explanation
ṠrþA # Implicit input
Ṡr # Reverse-sort
þA # Sort by |x|
# Take the first item
# Implicit output
05AB1E, 5 bytes
{R0.x
Or alternatively:
ÄWQÏà
Explanation:
{ # Sort the (implicit) input-list lowest-to-highest
R # Reverse it to highest-to-lowest
0.x # Pop and push the item closest to 0
# (after which the result is output implicitly)
Ä # Get the absolute value of each in the (implicit) input-list
W # Push the minimum (without popping the list)
Q # Check which are equal to this minimum
Ï # Only keep the values in the (implicit) input-list at the truthy indices
à # Pop and push the maximum of the remaining values
# (after which the result is output implicitly)
C#, 171 bytes
using static System.Console;using System.Linq;class s{static void Main()=>Write(ReadLine()=="0"?0:ReadLine().Split(' ').Select(int.Parse).OrderBy(v=>v*(.1-v)).Last());}
Octave, 19 bytes
@(x)min(complex(x))
This exploits the fact that min with complex input compares by absolute value, then by angle:
For complex arguments, the magnitude of the elements are used for comparison. If the magnitudes are identical, then the results are ordered by phase angle in the range (-pi, pi].
Julia 0.6, 29 bytes
x->sort(x,by=x->abs(x-.1))[1]
Sort by the absolute value of the temperature, but subtract .1 first to ensure positive temperatures always win.
PHP, 209 Bytes
Not really golfed, but wanted to try to use mostly array functions, avoiding loops
Code
function f($a){$a[]=0;sort($a);$k=array_search(0,$a);$o=array_slice($a,$k+1);$u=array_reverse(array_diff($a,$o));if($u[1]&&$o[0]){$r=(abs($u[1])<abs($o[0]))?$u[1]:$o[0];}else{$r=($u[1])?$u[1]:$o[0];}return$r;}
Explanation
function f($a){
$a[]=0; #As all nonzero values, 0 is pushed
sort($a); #Sorting the array
$k=array_search(0,$a); #Search where zero is
$o=array_slice($a,$k+1); #Array with all values >0
$u=array_reverse(array_diff($a,$o)); #Array with all smaller than zero values
#Array has ascending order so it gets reversed
if($u[1]&&$o[0]){ #if both are set we just compare the abs value
$r=(abs($u[1])<abs($o[0]))?$u[1]:$o[0];
}else{
$r=($u[1])?$u[1]:$o[0]; #al least one of them will allways be set
#the first value is always returned
#the 0 value on $u is not usetted that why $u[1]
}
return $r;
}
SmileBASIC, 56 bytes
DEF Z N,T
RSORT T
DIM V[N]ARYOP 2,V,T,T
SORT V,T?T[0]END
First, the input list is sorted, so the positive temperature will be chosen if there's a tie. Then each temperature is squared and stored in another array. The original array is sorted by this array, and the first item is printed.
dc, 53 bytes
Fd^sr[d*v]sA[ddlr+0=Asr]sR[dlAxlrlAx!<Rs_z0<M]dsMxlrp
We're going to use the register r to hold our final result, so the first thing we need to do is put a too-big number in there so that our first comparison always succeeds. I think the largest number we can push in two bytes is 165 (which is less than the required 5526), but Fd^ gives us 15^15 which is plenty large. Macro A, [d*v]sA just does the square root of the square to give us absolute value.
Macro R handles putting a value into register r; we'll come back to it in a second. Macro M, [dlAxlrlAx!<Rs_z0<M]dsMx is our main macro. Duplicates the value on the stack, runs A to get ABS, then pushes the value in r and does the same. !<R checks to see if ABS(r) is greater than or equal to not less than ABS(top of stack), and if so it runs R. Since we had to leave behind a copy of the original top of stack for R to potentially use, we store to a useless register (s_) to pop it. z0<M just loops M until the stack is empty.
Macro R, [ddlr+0=Asr]sR duplicates the top of stack twice (we need to leave something behind for M to gobble up when we return). At this point we know that of the two absolute values, our new value is less than or equal to our old value. If they're equal, and one is positive and the other is negative, we always need the positive. Fortunately, knowing this we can easily check for the case of one being the inverse of the other by simply adding them and comparing to 0. If so, we run A, and no matter what else happened we know we're storing whatever is left in r.
After M has gone through the whole stack, we load r and print it.
Avail, 88 bytes
Method"f_«_»"is[c:[1..∞),t:integer*|quicksort a,b in t[1..c] by[|a-0.1|<|b-0.1|][1]]
Approximate deobfuscation:
Method "nearest to zero among first _ of «_»" is
[
count : natural number,
temps : integer*
|
(quicksort a, b in temps[1..count] by [|a-0.1| < |b-0.1|])[1]
]
The pattern syntax in the method's name, f_«_», will read the initial count as a natural number (whose type is abbreviated above as the range type [1..∞)) separate from the collected tuple of subsequent integers.
All that remains for the body is to sort by a custom comparator. Here we escape the need for a second-level comparison between x and -x by shifting the values slightly towards -∞.
Octave, 28 bytes
@(x)max(x(min(a=abs(x))==a))
Finds the smallest absolute value (min(a=abs(x))), then maps it back to which elements have that smallest absolute value in case of a tie (x(...==a)). Finally takes the maximum value of the results (max(...)) to ensure that in the event of a tie we get one result which is the positive one.
Python 3, 31 bytes
a=lambda q:sorted(q,key=abs)[0]
Sorts items by absolute value and prints the first element.
Pyth, 4 bytes
.m.a
Explanation:
.m.a #Code
.m.abQ #With implicit variables
.m Q #Filter input list for values b with minimal value of the following:
.ab #Absolute value of b
Stax, 6 bytes
¢M║⌠§☺
Run and debug it at staxlang.xyz!
Unpacked (6 bytes) and explanation
{|a}eoH
{ }e Get all elements of array producing the minimum value from a block.
|a Absolute value.
o Sort ascending.
H Take last. Implicit print.
Java 8, 63 39 bytes
s->s.reduce(1<<15,(r,i)->r*r-r<i*i?r:i)
Port from @Arnauld's JavaScript answer. I couldn't find anything shorter..
-10 bytes converting Java 7 to 8,
and another -24 bytes thanks to @OlivierGrégoire.
Explanation:
s-> // Method with IntStream parameter and int return-type
s.reduce(1<<15, // Start `r` at 32768 (`32768^2` still fits inside a 32-bit integer)
(r,i)->r*r-r<i*i?// If `r^2 - r` is smaller than `i^2`:
r // Leave `r` the same
: // Else:
i) // Replace the current `r` with `i`
// Implicitly return the resulting `r`
C (clang), 74 bytes
k,m;f(*i,n){for(k=*i;--n>0;k=(k*k>m*m||(k==-m&&k<m))?m:k)m=i[n];return k;}
Python, 62 bytes
def f(n):
r=min(map(abs,n))
return r if r in n else -r
It feels like there is a much simpler/shorter solution.
PHP, 81 bytes
two solutions: the first one requires an upper bound; both require all temperatures nonzero.
for($r=9e9;$t=$argv[++$i];)abs($t)>abs($r)|abs($t)==abs($r)&&$t<$r?:$r=$t;echo$r;
for(;$t=$argv[++$i];)$r&&(abs($t)>abs($r)|abs($t)==abs($r)&&$t<$r)?:$r=$t;echo$r;
Run with -r, provide temperatures as command line arguments.
A lazy solution for 92 bytes:
$a=array_slice($argv,1);usort($a,function($a,$b){return abs($a)-abs($b)?:$b-$a;});echo$a[0];
defines a callback function for usort and uses it on a slice of $argv.
Brachylog (2), 5 or 2 bytes
~{≜∈}
It wouldn't surprise me if there were a shorter solution along the lines of the Jelly or Pyke, but I like this one because it's so weird.
This is simply Brachylog's "find a list containing the input" operator ∈, with an evaluation strategy ≜ that simply tries explicit values for integers until it finds one that works (and it happens to try in the order 0, 1, -1, 2, -2, 3, etc., which is surprisingly handy for this problem!), and inverted ~ (so that instead of trying to find an output list containing the input, it's trying to find an output contained in the input list). Unfortunately, inverting an evaluation strategy along with the value itself costs 2 bytes, so this doesn't beat the Jelly or Pyke solutions.
There's also a dubious 2-byte solution ≜∈. All Brachylog predicates take exactly two arguments, which can each be inputs or outputs; by convention, the first is used as an input and the second is used as an output, but nothing actually enforces this, as the caller has complete control over the argument pattern used (and in Prolog, which Brachylog compiles to, there's no real convention about argument order). If a solution which takes input through its second argument and produces output through its first argument is acceptable, there's no requirement to do the inversion.
C++14, 64 bytes
As unnamed lambda, expecting first argument to be like vector<int> and returing via reference parameter.
[](auto L,int&r){r=L[0];for(int x:L)r=x*x<=r*r?r+x?x:x>r?x:r:r;}
Ungolfed and usage:
#include<iostream>
#include<vector>
auto f=
[](auto L,int&r){
r=L[0];
for(int x:L)
r = x*x<=r*r ? //x is absolute less or equal
r+x ? //r==-x?
x : //no, just take x
x>r ? //take the positive one
x :
r :
r //x was absolute greater, so keep r
;
}
;
int main(){
std::vector<int> v = {5, 2, -2, -8, 4, -1, 1};
int r;
f(v,r);
std::cout << r << std::endl;
}
Haskell, 29 bytes
snd.maximum.map(\x->(-x^2,x))
Usage example: snd.maximum.map(\x->(-x^2,x)) $ [1,-2,-8,4,5]-> 1.
Map each element x to a pair (-x^2,x). Find the maximum and pick the 2nd element from the pair.
MATL, 9 6 bytes
0iSPYk
Thanks to Luis Mendo for pointing out there's actually a built-in for this in MATL, which is not present in MATLAB.
i % Take input
S % Sort
P % Reverse to have largest value first.
0 Yk % Closest value to zero, prioritizing the first match found
If you wish to follow the spec and also provide the number of temperatures to be read, this should be given as the second input, and will be silently discarded.
Python, 35 bytes
lambda l:max((-x*x,x)for x in l)[1]
Narrowly beats:
lambda l:min(l,key=lambda x:2*x*x-x)
lambda l:min(sorted(l)[::-1],key=abs)
Mathematica, 21 19 bytes
Max@*MinimalBy[Abs]
Composition of functions. Takes a list of integers as input and returns an integer as output.
JavaScript (ES6), 33 bytes
a=>a.reduce((m,n)=>n*n-n<m*m?n:m)
Demo
let f =
a=>a.reduce((m,n)=>n*n-n<m*m?n:m)
console.log(f([1, -2, -8, 4, 5]))
Jelly, 4 bytes
AÐṂṀ
How it works
AÐṂṀ Main link. Argument: A (array)
AÐṂ Take all elements with minimal absolute value.
Ṁ Take the maximum. Yields 0 for an empty list.
05AB1E, 16 bytes
Îåà_Di¹{RDÄßs\kè
Explanation:
Î Push 0 and [implicit] input array
å For each element in the array, is it a 0?
à Find the greatest value (1 if there was a 0 in it, 0 otherwise)
_ Negate boolean (0 -> 1, 1 -> 0)
D Duplicate
i If true, continue
¹ Push input
R Reversed
D Duplicated
Ä Absolute value
ß Greatest element
s Swap top two values in stack
\ Delete topmost value in stack
k Index of greatest element in the array
è Value of the index in the input array
Not at short as I'd like, but at least it works.