| Bytes | Lang | Time | Link |
|---|---|---|---|
| 052 | JavaScript Node.js | 250311T153200Z | Weird Gl |
| 040 | Desmos | 250311T002640Z | DesmosEn |
| 1030 | ☾ | 250309T125502Z | Ganer |
| 062 | Zsh | 250116T104534Z | roblogic |
| 061 | Kotlin | 250125T091228Z | lukas.j |
| 081 | C gcc | 250116T153520Z | Rosario |
| 018 | APLNARS | 250116T075423Z | Rosario |
| 022 | Haskell + hgl | 250117T064330Z | Wheat Wi |
| 009 | Uiua | 250115T170934Z | nyxbird |
| 006 | Vyxal 3 | 250115T153111Z | Ginger |
| 091 | YASEPL | 240222T151111Z | madeforl |
| 004 | Vyxal 3 G | 240222T140334Z | pacman25 |
| 014 | Uiua SBCS | 240223T215151Z | chunes |
| 015 | Pip | 240223T042423Z | DLosc |
| 014 | K ngn/k | 230918T073513Z | Bubbler |
| 016 | J | 230918T072436Z | Bubbler |
| nan | Scala | 230917T031640Z | 138 Aspe |
| 014 | BQN | 230917T053315Z | Razetime |
| 085 | Nibbles | 230916T214113Z | xigoi |
| nan | 230916T055135Z | RARE Kpo | |
| 007 | Nekomata | 230916T014132Z | alephalp |
| 045 | Vyxal G | 230831T222121Z | lyxal |
| 005 | Jelly | 230901T052418Z | Unrelate |
| 006 | Thunno 2 G | 230830T152602Z | The Thon |
| 054 | R | 160922T110409Z | Headcras |
| 074 | C# | 160921T121842Z | Grax32 |
| 106 | Java 7 | 160921T124745Z | Kevin Cr |
| 098 | SPSS Syntax | 160922T105412Z | kgbviz |
| 066 | PHP | 160922T092658Z | aross |
| 010 | Pyth | 160921T101710Z | orlp |
| 055 | Julia | 160921T105809Z | nyro_0 |
| 064 | PHP | 160921T164217Z | Linnea G |
| 043 | Mathematica | 160921T112653Z | LegionMa |
| 053 | Perl 6 | 160921T213510Z | Brad Gil |
| 018 | J | 160921T213258Z | miles |
| 042 | Perl | 160921T211844Z | Ton Hosp |
| 038 | q | 160921T164504Z | Liam Bar |
| 071 | PHP | 160921T101637Z | Titus |
| 056 | JavaScript ES6 | 160921T101634Z | Arnauld |
| 051 | Ruby | 160921T112228Z | cia_rana |
| 132 | C | 160921T154634Z | LambdaBe |
| 183 | Racket | 160921T142753Z | rnso |
| 047 | R | 160921T130419Z | Billywob |
| 049 | Python | 160921T150336Z | Jonathan |
| 062 | PowerShell v3+ | 160921T133510Z | AdmBorkB |
| 014 | Dyalog APL | 160921T133244Z | Adá |
| 009 | 05AB1E | 160921T102307Z | Emigna |
| 182 | TSQL | 160921T132548Z | t-clause |
| 008 | Jelly | 160921T130233Z | lynn |
| 053 | JavaScript ES6 | 160921T121835Z | Neil |
| 032 | MATLAB with Image Processing Toolbox | 160921T111207Z | Luis Men |
| 010 | MATL | 160921T102528Z | Luis Men |
| 074 | Python 2 | 160921T114949Z | SCB |
| 043 | Haskell | 160921T101217Z | BlackCap |
| 016 | CJam | 160921T101354Z | Martin E |
JavaScript (Node.js), 52 bytes
l=>Math.max(...l.filter((v,i)=>l[i-1]==0|l[i+1]==0))
Test cases from Arnauld's answer
Is there something I'm missing here? Because this seems like the obvious solution, but most JS answers used map instead, which is often good when you need to remove some bytes, but it's useless here.
Desmos, 40 bytes
f(l)=\join(l[g=0],g[l=0]).\max
g=l[2...]
This program loops over l, filtering for elements at index n such that the nth element of g is 0, where g is just the array l, shifted to the left by one element. Similarly, it loops over g, looking for elements at index n such that the nth element of l is 0. It concatenates these two arrays, having the effect of returning an array filtered for all elements adjacent to a 0. This array then simply has the max function called on it to find the largest element, and return it.
☾, 10 chars (30 bytes)
ᙧ2⭥⋀ᴍ⋁⭢⤉
Note: ☾ uses a custom font, but you can run this code in the Web UI
There are 4 symbols for window but this one doesn't pad out the ends but includes the center of the window, the right arg (2⭥ = [0,1]) means 0 to the left and 1 to the right, hence we get pairs
Zsh, 71 67 62 bytes
repeat $[#-1];A+=($[$1*$2?0:$1+$2])&&shift;printf ${(-O)A//#0}
Iterates over arguments in n-1 pairs. If x*y==0, add x+y to the array A (otherwise add 0). Then print the largest nonzero integer from A.
Kotlin, 61 chars
print(l.windowed(2,1).filter{it.contains(0)}.maxOf{it.sum()})
where l is a List.
Example:
val list = listOf(1, 4, 3, 6, 0, 3, 7, 0)
print(
list
.windowed(2, 1) // [[1, 4], [4, 3], [3, 6], [6, 0], [0, 3], [3, 7], [7, 0]]
.filter { it.contains(0) } // [[6, 0], [0, 3], [7, 0]
.maxOf { it.sum() } // 7
)
Tests at https://pl.kotl.in/FYIoQK3JH
C (gcc), 81 bytes
c,r,b;f(a,l)int*a;{for(c=0;l--;b=*a++,*a*b||(b+=*a,r=c?b>r?b:r:b+c++));return r;}
f has two arguments, "a" is the array pointer to int and "l" is its size/lenght in number of integers. I copied the function from other languages [if a[i]*a[i+1]==0 than consider the sum a[i]+a[i+1] ]. This is it 'ungolfed':
c,r,b;f(a,l)int*a;
{for(c=0;l--;b=*a++,*a*b||(b+=*a,r=c?b>r?b:r:b+c++))
;
return r;
}
Thanks to @ceilingcat from whom I have copied x+c++.
APL(NARS), 18 chars
⌈/2{0=⍵×⍺:⍵+⍺⋄-∞}/
The problem was to find something that is < of other numbers that work with ⌈/ (-∞). It is the traslation in APL of some other solution that use the same algo(2{0=⍵×⍺:⍵+⍺⋄-∞}/ in the array of input return -∞ if the 2 contigues number are both different of zero, else return their sum ⍵+⍺, than it is question of find the max ⌈/ of that array )... The initial array can not contain -∞. Test:
⌈/2{0=⍵×⍺:⍵+⍺⋄-∞}/¯4 ¯6 ¯2 0 ¯9
¯2
⌈/2{0=⍵×⍺:⍵+⍺⋄-∞}/1 4 3 6 0 3 7 0
7
⌈/2{0=⍵×⍺:⍵+⍺⋄-∞}/9 4 9 0 9 0 9 15 ¯2
9
⌈/2{0=⍵×⍺:⍵+⍺⋄-∞}/¯11 0 0 0 0 0 ¯12 10
0
⌈/2{0=⍵×⍺:⍵+⍺⋄-∞}/0 20
20
Haskell + hgl, 22 bytes
mx<pl<<%fl(q0<U ml)<pA
Explanation
pAget all pairs of consecutive elementsfl(q0<U ml)filter all those that multiply to 0pladd all the pairsmxget the maximum
Reflection
This is way too long for the task. An underlying issue is that these sorts of tasks, in which you have do do something to elements based on the properties of elements nearby are difficult to express in hgl. I don't really know a way to fix the general problem, but there are some things that I should do regardless.
- There should be a builtin that combines
pAandfl, to get all consecutive pairs satisfying some predicate. There should probably also be a combination ofpaandflwhich does the same thing but applies a function instead of returning a pair. - There should be shortcuts for
st<<fl crandcr<<fl st. To filter based on the first and second elements of a tuple. This would take 5 bytes off of something like:
to make something likexM st<fl cr<pa(ot2 pl$q0<<ml)
Which wouldn't be quite enough to make it competitive, but we might as well.mx<fl2<pa(ot2 pl$q0<<ml) - This answer exploits the fact that the number
0is fixed. It would be a lot more costly if this were replaced with an arbitrary number. One way to make this better is to have a function which takes 3 parameters and checks if either the second or the third is equal to the first. That is a shortcut foron mN<eq. I should think more generally about what might improve hgl for this scenario.
Uiua, 9 bytes
/↥▽=0⧈⊃×+
/↥▽=0⧈⊃×+
⧈⊃×+ # get the product and sum of each window of 2
▽=0 # keep the sums for which the product is 0
/↥ # take the maximum
Vyxal 3, 6 bytes
v~0cϾG
~ # Filter
v # overlapping pairs of the input
0c # for pairs that contain a zero
Ͼ # Sum each pair
G # and find the maximum of the sums
💎
Created with the help of Luminespire.
YASEPL, 91 bytes
=1'±" "=l®1=h-99=i`1!o¥i,1}7,0,2!i]4!m$i-=s¥m,1}2,h,2|3`4!m$i+=s¥m,1}2,h,2`3!h$s`2!i+}2,l>h
explained:
=1'±" "=l®1=h-99=i`1!o¥i,1}7,0,2!i]4!m$i-=s¥m,1}2,h,2|3`4!m$i+=s¥m,1}2,h,2`3!h$s`2!i+}2,l>h packed
=1' set var1 to user input
±" " split A by every space
=l®1 set L to the length of var1
=h-99 set H to -99 (atorage for highest number)
=i set I to 0 (incrementer)
`1 !i }2,l do while I < L ...
!o¥i,1}7,0,2 `2 if(var1[i] == 0) ...
!i]4!m$i-=s¥m,1}2,h,2|3`4 `3 and if(i != 0 and if(var1[i-1] > h) ...
!m$i+=s¥m,1}2,h,2 or if(var1[i+1] > h) ...
!h$s set H to S and continue (found higher number)
+ increment I and loop.
>h print H once done.
Vyxal 3 G, 4 bytes
oᶻΠf
oᶻΠf
o # overlapping pairs
ᶻΠ # where the product is zero
f # flatten
💎
Created with the help of Luminespire.
Uiua SBCS, 14 bytes
/↥≡/+▽=0≡/×.◫2
/↥≡/+▽=0≡/×.◫2
◫2 # overlapping pairs
. # duplicate
≡/× # products
▽=0 # keep those equal to zero
≡/+ # sums
/↥ # max
Pip, 15 bytes
M$|*:0N_FIgZ@>g
Takes the numbers as command-line arguments. Attempt This Online!
Explanation
M$|*:0N_FIgZ@>g
g ; List of command-line args
Z ; Zip with
@>g ; All but the first element of that same list
FI ; Filter those pairs of elements on this function:
0N_ ; Contains a 0
$|*: ; Fold each pair on logical OR
M ; Maximum
K (ngn/k), 14 bytes
|/+/'(*/')_2':
|/+/'(*/')_2':
2': pairs
(*/')_ discard those whose product are nonzero
+/' sum of each pair
|/ maximum
J, 16 bytes
}.>./@(+#~0=*)}:
}.>./@(+#~0=*)}:
}. }: Input without first and without last, respectively
0=* elementwise product equals 0?
+ elementwise sum
#~ filter the left by the right being true
(the right is true iff one of the two is zero,
and the corresponding sum is the other number)
>./@ maximum of those
Scala, 106 97 bytes
A port of @Kevin Cruijssen's Java 7 answer in Scala.
Saved 9 bytes thanks to the comment of @ceilingcat
Golfed version. Try it online!
a=>{var(i,m,c)=(0,1<<31,0);while({i+=1;i<a.length})if(a(i)*a(i-1)==0)m=Math.max(a(i)+a(i-1),m);m}
Ungolfed version. Try it online!
object M {
def c(a: Array[Int]): Int = {
var i = 0
var m = 1 << 31
var c: Int = 0
while ({i += 1; i < a.length}) {
if (a(i) * a(i - 1) == 0) {
c = a(i) + a(i - 1)
m = Math.max(c, m)
}
}
m
}
def main(args: Array[String]): Unit = {
println(c(Array(1, 4, 3, 6, 0, 3, 7, 0)))
println(c(Array(9, 4, 9, 0, 9, 0, 9, 15, -2)))
println(c(Array(-4, -6, -2, 0, -9)))
println(c(Array(-11, 0, 0, 0, 0, 0, -12, 10)))
println(c(Array(0, 20)))
println(c(Array(2, 1, 0)))
}
}
Nibbles, 8.5 bytes
`/.|!$>>@:?$0+$]
Disgustingly long…
`/.|!$>>@:?$0+$]
! : Zip
$ the input
>> with the tail of
@ the input
| Filter by
?$0 containing a zero
. Map
+$ sum
`/ ] Maximum
awk
gawk '{__=!_++?+$NF:!NF?(!_<__?__:!_):__<+(!RT||+$NF<+$!_? $!_:\
$!_=$NF)?+$!_:__ }END{ print __ }' RS='(^| +)0([ \n]+|$)'
-11 0 0 0 0 0 -12 10
0
-4 -6 -2 0 -9
-2
0 20
20
1 4 3 6 0 3 7 0
7
9 4 9 0 9 0 9 15
9
Nekomata, 7 bytes
qᵗZđ+aṀ
qᵗZđ+aṀ
q Non-deterministically choose a contiguous subsequence
ᵗZ Check that it contains a 0
đ Unpair; check that its length is 2, and push the two elements
+ Add
a All possible values
Ṁ Maximum
Vyxal G, 36 bitsv2, 4.5 bytes
2lƛ∑w↔
Porting Jelly is (still) always the best option
Explained
zṠ↔G
z # Overlapping pairs (equivalent to 2l)
Ṡ # summed (vectorised)
↔ # with only items in the input kept.
G # Get the biggest number in that list.
💎
Created with the help of Luminespire.
Jelly, 6 5 bytes
SfµƝṀ
-1 remembering it's not a dyadic chain
µƝ For each pair of adjacent elements, monadically:
S Sum the pair,
f and filter it to only element[s] in the pair.
Ṁ Take the maximum.
Thunno 2 G, 6 bytes
ḣZæp}ʂ
Explanation
ḣZæp}ʂ # Implicit input
ḣZ # All overlapping pairs
æp} # Filter by product == 0
ʂ # Sum each inner pair
# Implicit output of maximum
R, 48 54 bytes
s=scan()
w=which;max(s[c(w(s==0)+1,w(s==0)-1)],na.rm=T)
Reads vector from console input, then takes the maximum over all values adjacent to 0.
Edit: Catches NAs produced at the boundary, thanks rturnbull!
C# 76 74 bytes
using System.Linq;i=>i.Zip(i.Skip(1),(a,b)=>a*b==0?1<<31:a+b).Max();
Explanation:
Use zip to join the array with itself but skipping the first value in the 2nd reference so that item zero joins to item one. Multiply a times b, if the result is zero, one of them must be zero and output a + b. Otherwise, output the minimum possible integer in the language. Given the assumption that we will always have a zero and a non-zero, this minimum value will never be output as the max.
Usage:
[TestMethod]
public void LargestFriend()
{
Assert.AreEqual(7, F(new int[] { 1, 4, 3, 6, 0, 3, 7, 0 }));
Assert.AreEqual(9, F(new int[] { 9, 4, 9, 0, 9, 0, 9, 15, -2 }));
Assert.AreEqual(-2, F(new int[] { -4, -6, -2, 0, -9 }));
Assert.AreEqual(0, F(new int[] { -11, 0, 0, 0, 0, 0, -12, 10 }));
Assert.AreEqual(20, F(new int[] { 0, 20 }));
}
Java 7, 118 105 106 bytes
int d(int[]a){int i=0,m=1<<31,c;for(;++i<a.length;m=a[i]*a[i-1]==0&(c=a[i]+a[i-1])>m?c:m);return m;}
13 bytes saved thanks to @cliffroot by using an arithmetic approach instead. 1 additional byte thank to @mrco after he discovered a bug (the added test case 2, 1, 0 would return 2 instead of 1).
Ungolfed & test code:
class M{
static int c(int[] a){
int i,
m = a[i=0],
c;
for(; ++i < a.length; m = a[i] * a[i-1] == 0 & (c = a[i] + a[i - 1]) > m)
? c
: m);
return m;
}
public static void main(String[] a){
System.out.println(c(new int[]{ 1, 4, 3, 6, 0, 3, 7, 0 }));
System.out.println(c(new int[]{ 9, 4, 9, 0, 9, 0, 9, 15, -2 }));
System.out.println(c(new int[]{ -4, -6, -2, 0, -9 }));
System.out.println(c(new int[]{ -11, 0, 0, 0, 0, 0, -12, 10 }));
System.out.println(c(new int[]{ 0, 20 }));
System.out.println(c(new int[]{ 2, 1, 0 }));
}
}
Output:
7
9
-2
0
20
1
SPSS Syntax (98 bytes)
Golfed solution:
CRE L=lead(A,1).
COMP R=MAX(lag(A),L).
EXE.
SEL IF A=0.
EXE.
AGG
/S=MAX(R).
LIST S
/CAS=1.
Ungolfed:
CREATE L=lead(A,1).
COMPUTE R=MAX(lag(A),L).
EXECUTE.
SELECT IF A=0.
EXECUTE.
AGGREGATE
/S=MAX(R).
LIST S
/CASES=1.
Explanation: Input values is ordered vertically in a column. The first line of code creates a column with the lead number, the number before any given number. MAX(lag,A) returns the lagging number, the number after any given number (in test series A). So the second line of code creates a column with the highest number of neighbourging numbers of any given number. We are only interested in the neighbours of zeros, so the forth line selects all the rows with zeros, which now also include the highest valued neighbours. The 6th and 7th line of code finds the max value of selected neighbours.
With data inputs:
* This syntax solves: Returning the greatest adjacent number bigger or equal to itself,
for any number V.
* CodeGolf asks for the solution for the case V=0.
* Bytes=98.
DATA LIST LIST
/ Sample (A7) a b c d e f g h i j k l m .
BEGIN DATA.
"A" 1, 4, 3, 6, 0, 3, 7, 0
"B" 9, 4, 9, 0, 9, 0, 9, 15, -2
"C" -4, -6, -2, 0, -9
"D" -11, 0, 0, 0, 0, 0, -12, 10
"E" 0, 20
END DATA.
DATASET NAME Inputs WINDOW=FRONT.
FLIP VARIABLES=a b c d e f g h i
/NEWNAMES=Sample.
DATASET NAME CodeGolf WINDOW=FRONT.
DATASET CLOSE Inputs.
CRE L=lead(A,1).
COMP R=MAX(lag(A),L).
EXE.
SEL IF A=0.
EXE.
AGG
/S=MAX(R).
LIST S
/CAS=1.
Just change the sample references (A to E) for testing each sample.
PHP, 66 bytes
foreach($a=$argv as$k=>$v)$v||$m=max($m,$a[$k-1],$a[$k+1]);echo$m;
Pretty straightforward. Iterates over the input, and when a number is 0, it sets $m to the highest number of the 2 adjacent numbers and any previous value of $m.
Run like this (-d added for aesthetics only):
php -d error_reporting=30709 -r 'foreach($a=$argv as$k=>$v)$v||$m=max($m,$a[$k-1],$a[$k+1]);echo$m;' -- -4 -6 -2 0 -9;echo
Pyth, 12 11 10 bytes
eSsM/#0,Vt
Forms pairs, filters by zero member, sorts by sum, returns largest.
Julia, 56 55 Bytes
f(l)=max(map(sum,filter(t->0 in t,zip(l,l[2:end])))...)
Create tuples for neighboring values, take those tuples containing 0, sum tuple values and find maximum
PHP 69 64 bytes
Some bytes on and off from Jörg Hülsermann and Titus. = (-5)
Requires register_globals enabled. Usage: http://localhost/notnull.php?i[]=9&i[]=-5i[]=...
$x=$_GET['i'];
$y=0;
foreach($x as $j){
if($y<abs($j)){
$y=$j;
}
}
echo $y;
Golfed:
$x=$_GET['i'];$y=0;foreach($x as $j)if($y<abs($j))$y=$j;echo $y;
Mathematica, 46 43 bytes
Saved 3 bytes due to @MartinEnder.
Max[Tr/@Partition[#,2,1]~Select~MemberQ@0]&
Anonymous function. Takes a list of integers as input and returns an integer as output. Based off of the Ruby solution.
Perl 6, 53 bytes
{max map ->$/ {$1 if !$0|!$2},(1,|@_,1).rotor(3=>-2)}
Expanded:
# bare block lambda with implicit signature of (*@_)
{
max
map
-> $/ { # pointy lambda with parameter 「$/」
# ( 「$0」 is the same as 「$/[0]」 )
$1 if !$0 | !$2 # return the middle value if either of the others is false
},
( 1, |@_, 1 ) # list of inputs, with added non-zero terminals
.rotor( 3 => -2 ) # grab 3, back-up 2, repeat until less than 3 remain
}
J, 18 bytes
[:>./2(0&e.\#+/\)]
Explanation
[:>./2(0&e.\#+/\)] Input: array A
] Identity. Get A
2 The constant 2
( ) Operate on 2 (LHS) and A (RHS)
\ Get each subarray of size 2 from A and
+/ Reduce it using addition
\ Get each subarray of size 2 from A and
0&e. Test if 0 is a member of it
# Filter for the sums where 0 is contained
[:>./ Reduce using max and return
Perl, 42 bytes
Includes +1 for -p
Give the numbers on line on STDIN
largest0.pl <<< "8 4 0 0 5 1 2 6 9 0 6"
largest0.pl:
#!/usr/bin/perl -p
($_)=sort{$b-$a}/(?<=\b0 )\S+|\S+(?= 0)/g
q, 38 bytes
{max x where 0 in'x,'(next x),'prev x}
PHP, 77 68 71 bytes
-3 bytes from anonymous, -4 and -2 from MartinEnder
preg_match_all("#(?<=\b0 )\S+|\S+(?= 0)#",$argv[1],$m);echo max($m[0]);
run with php -r '<code>' '<space separated values>'
JavaScript (ES6), 59 57 56 bytes
let f =
l=>l.map((n,i)=>m=l[i-1]==0|l[i+1]==0&&n>m?n:m,m=-1/0)|m
console.log(f([1, 4, 3, 6, 0, 3, 7, 0])); // 7
console.log(f([9, 4, 9, 0, 9, 0, 9, 15, -2])); // 9
console.log(f([-4, -6, -2, 0, -9])); // -2
console.log(f([-11, 0, 0, 0, 0, 0, -12, 10])); // 0
console.log(f([3, 0, 5])); // 5
console.log(f([28, 0, 14, 0])); // 28
Edit: saved 2 bytes thanks to Huntro
Edit: saved 1 byte thanks to ETHproductions
Ruby, 51 bytes
->a{a.each_cons(2).map{|a,b|a*b!=0?-1.0/0:a+b}.max}
usage
f=->a{a.each_cons(2).map{|a,b|a*b!=0?-1.0/0:a+b}.max}
p f[gets.split.map(&:to_i)]
C 132 bytes
Outputs using main's return code:
int main(int a,char**_){int i,m=0;_[0]=_[a]="1";for(i=1;i<a;++i){m=(*_[i-1]-48||*_[i+1]-48?m>atoi(_[i])?m:atoi(_[i]):m);}return m;}
I feel like I should be able to save a few bytes by saving one of the atoi calls, but I couldn't find an efficient way. (,t plus t= plus , plus t twice is too long). Also this technically uses undefined behaviour (setting _[a] to "1") but every compiler I know of allows it by default.
Strategy: pad the start and end of the array with 1, then loop over the internal section checking each neighbor.
Racket 183 bytes
(λ(k)(let*((lr(λ(l i)(list-ref l i)))(l(append(list 1)k(list 1)))(m(for/list((i(range 1(sub1(length l))))
#:when(or(= 0(lr l(sub1 i)))(= 0(lr l(add1 i)))))(lr l i))))(apply max m)))
Detailed version:
(define f
(λ(k)
(let* ((lr (λ(l i)(list-ref l i)))
(l (append (list 1) k (list 1)))
(m (for/list ((i (range 1 (sub1(length l))))
#:when (or (= 0 (lr l (sub1 i)))
(= 0 (lr l (add1 i))) ))
(lr l i) )))
(apply max m) )))
Testing:
(f (list 1 4 3 6 0 3 7 0))
(f (list 9 4 9 0 9 0 9 15 -2))
(f (list -4 -6 -2 0 -9))
(f (list -11 0 0 0 0 0 -12 10))
(f (list 0 20 ))
Output:
7
9
-2
0
20
R, 48 47 bytes
EDIT:
Fixed an error thanks to @Vlo and changed it to read input from stdins, saved one byte by assigning w and skipping parantheses.
function(v)sort(v[c(w<-which(v==0)-1,w+1)],T)[1]
v=scan();w=which(v==0);sort(v[c(w-1,w+1)],T)[1]
Unnested explanation
- Find indices for which the vector
vtakes on the values 0:w <- which(v == 0) - Create new vector which contains the indices
+-1:w-1andw+1 - Extract elements that match the indices
w-1andw+1 - Sort in descending order and extract fist element
Note that if the last or first element of v is a zero, w+-1 will effectively fetch an index outside of the length of the vector which implies that v[length(v)+1] returns NA. This is generally no problem but the max() functions inconveniently returns NA if there are any occurrences in the vector unless one specifies the option na.rm=T. Thus it is 2 bytes shorter to sort and extract first element than to use max(), e.g.:
max(x,na.rm=T)
sort(x,T)[1]
Python, 49 bytes
lambda a:max(sum(x)for x in zip(a,a[1:])if 0in x)
Tests are at ideone
Zips through the pairs, sums the ones containing any zero, returns the maximum.
PowerShell v3+, 62 bytes
param($n)($n[(0..$n.count|?{0-in$n[$_-1],$n[$_+1]})]|sort)[-1]
A bit longer than the other answers, but a nifty approach.
Takes input $n. Then loops through the indices 0..$n.count, uses the Where-Object (|?{...}) to pull out those indices where the previous or next item in the array is 0, and feeds those back into array slice $n[...]. We then |sort those elements, and take the biggest [-1].
Examples
PS C:\Tools\Scripts\golfing> @(1,4,3,6,0,3,7,0),@(9,4,9,0,9,0,9,15,-2),@(-4,-6,-2,0,-9),@(-11,0,0,0,0,0,-12,10)|%{""+$_+" --> "+(.\largest-number-beside-a-zero.ps1 $_)}
1 4 3 6 0 3 7 0 --> 7
9 4 9 0 9 0 9 15 -2 --> 9
-4 -6 -2 0 -9 --> -2
-11 0 0 0 0 0 -12 10 --> 0
PS C:\Tools\Scripts\golfing> @(0,20),@(20,0),@(0,7,20),@(7,0,20),@(7,0,6,20),@(20,0,6)|%{""+$_+" --> "+(.\largest-number-beside-a-zero.ps1 $_)}
0 20 --> 20
20 0 --> 20
0 7 20 --> 7
7 0 20 --> 20
7 0 6 20 --> 7
20 0 6 --> 20
Dyalog APL, 14 bytes
⌈/∊2(+↑⍨0∊,)/⎕
⌈/ largest of
∊ the flattened ("enlisted"
2(...)/ pairwise
+ sum (zero plus something is something)
↑⍨ taken if
0 zero
∊ is a member of
, the pair (lit. the concatenation of the left-hand number and the right-hand number)
05AB1E, 9 bytes
ü‚D€P_ÏOZ
Explanation
ü‚ # pair up elements
D # duplicate
€P # product of each pair (0 if the pair contains a 0)
_ # logical negate, turns 0 into 1 and everything else to 0
Ï # keep only the pairs containing at least 1 zero
O # sum the pairs
Z # take max
Doesn't work in the online interpreter, but works offline.
T-SQL, 182 bytes
Golfed:
DECLARE @x varchar(max)='1 5 4 3 6 1 3 17 1 -8 0 -7'
DECLARE @a INT, @b INT, @ INT WHILE @x>''SELECT @a=@b,@b=LEFT(@x,z),@x=STUFF(@x,1,z,''),@=IIF(@a=0,IIF(@b<@,@,@b),IIF(@b<>0 or @>@a,@,@a))FROM(SELECT charindex(' ',@x+' ')z)z PRINT @
Ungolfed:
DECLARE @x varchar(max)='1 5 4 3 6 1 3 17 1 -8 0 -7'
DECLARE @a INT, @b INT, @ INT
WHILE @x>''
SELECT
@a=@b,
@b=LEFT(@x,z),
@x=STUFF(@x,1,z,''),
@=IIF(@a=0,IIF(@b<@,@,@b),IIF(@b<>0 or @>@a,@,@a))
FROM(SELECT charindex(' ',@x+' ')z)z
PRINT @
Jelly, 8 bytes
ṡ2ẠÐḟS€Ṁ
ṡ2 Overlapping pairs
ẠÐḟ Remove pairs without zeroes
S€ Sum of each pair
Ṁ Maximum
JavaScript (ES6), 53 bytes
a=>(m=-1/0,a.reduce((l,r)=>(m=l*r||l+r<m?m:l+r,r)),m)
Because I like using reduce. Alternative solution, also 53 bytes:
a=>Math.max(...a.map((e,i)=>e*a[++i]==0?e+a[i]:-1/0))
MATLAB with Image Processing Toolbox, 32 bytes
@(x)max(x(imdilate(~x,[1 0 1])))
This is an anonymous function. Example use for the test cases:
>> f = @(x)max(x(imdilate(~x,[1 0 1])))
f =
function_handle with value:
@(x)max(x(imdilate(~x,[1,0,1])))
>> f([1 4 3 6 0 3 7 0])
ans =
7
>> f([9 4 9 0 9 0 9 15 -2])
ans =
9
>> f([-4 -6 -2 0 -9])
ans =
-2
>> f([-11 0 0 0 0 0 -12 10])
ans =
0
>> f([0 20])
ans =
20
MATL, 10 bytes
t~5BZ+g)X>
Try it online! Or verify all test cases.
Explanation
Let's take input [-4 -6 -2 0 -9] as an example.
t % Input array. Duplicate
% STACK: [-4 -6 -2 0 -9], [-4 -6 -2 0 -9]
~ % Logical negate. Replaces zeros by logical 1, and nonzeros by logical 0
% STACK: [-4 -6 -2 0 -9], [0 0 0 1 0]
5B % Push logical array [1 0 1] (5 in binary)
% STACK: [-4 -6 -2 0 -9], [0 0 0 1 0], [1 0 1]
Z+ % Convolution, maintaining size. Gives nonzero (1 or 2) for neighbours of
% zeros in the original array, and zero for the rest
% STACK: [-4 -6 -2 0 -9], [0 0 1 0 1]
g % Convert to logical
% STACK: [-4 -6 -2 0 -9], [0 0 1 0 1]
) % Use as index into original array
% STACK: [-2 -9]
X> % Maximum of array.
% STACK: -2
% Implicitly display
Python 2, 74 Bytes
def f(x):x=[9]+x;print max(x[i]for i in range(len(x)) if 0in x[i-1:i+2:2])
Cycle through every element, if there's a 0 in the position of either the left or the right of the current element, include it in the generator, and then run it through max. We need to pad the list with some non-0 number. It'll never be included because the slice [-1:2:2] won't include anything.
Haskell, 63 43 bytes
f x=maximum[a+b|(a,b)<-tail>>=zip$x,a*b==0]
Thanks to @MartinEnder for 4 bytes!
CJam, 16 bytes
q~2ew{0&},::+:e>
Try it online! (As a test suite.)
Explanation
q~ e# Read and eval input.
2ew e# Get all (overlapping) pairs of adjacent values.
{0&}, e# Keep only those that contain a 0.
::+ e# Sum each pair to get the other (usually non-zero) value.
:e> e# Find the maximum.