# Find the largest number that's adjacent to a zero

Challenge:

Take a vector / list of integers as input, and output the largest number that's adjacent to a zero.

Specifications:

• As always, optional input and output format
• You may assume that there will be at least one zero, and at least one non-zero element.

Test cases:

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

0 20
20

Good luck and happy golfing!

• You should add a test case like the 4th one, but where the result is negative (there are positive numbers in the list). Commented Sep 21, 2016 at 15:11
• I was going to try this in Retina, but then I noticed there are negatives. Retina hates negatives. Commented Sep 21, 2016 at 15:12
• Don't let retina dictate what you can and cannot do. Take charge, you're the boss! Commented Sep 22, 2016 at 10:26

# MATL, 10 bytes

t~5BZ+g)X>

### 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
• x(~~(dec2bin(5)-48)). Who's idea was it to implement that one? Very clever, and useful for logical arrays! :) Nice answer! Commented Sep 21, 2016 at 11:02
• @WeeingIfFirst Thanks! I had used dec2bin()-'0' hundreds of times in MATLAB, so I knew that one had to be in MATL :-) Commented Sep 21, 2016 at 11:04
• By the way, the fact that you included the content of the stack after every operation is worth an upvote alone. It makes it so much easier to understand (and possibly learn) MATL =) Commented Sep 21, 2016 at 11:56
• Convolution Rocks. +1 Commented Sep 21, 2016 at 17:41

f x=maximum[a+b|(a,b)<-tail>>=zip$x,a*b==0] Thanks to @MartinEnder for 4 bytes! • I think you can use a*b==0 instead of the ||. Commented Sep 21, 2016 at 10:15 • You have to go back to previous version with zip. Here a and be are no longer adjacent Commented Sep 21, 2016 at 10:46 • You don't need lambdabot here. This is "regular" Haskell Commented Sep 21, 2016 at 11:00 # 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. • This is amazing haha! Just in time :p. Commented Sep 21, 2016 at 10:24 • Just implemented one of these operators or? :) Commented Sep 21, 2016 at 10:27 • @WeeingIfFirst: ü was added just yesterday :) Commented Sep 21, 2016 at 10:28 • Won’t this return 0 if the actual answer would be negative? You have to throw out the zeroes, I think. – lynn Commented Sep 21, 2016 at 12:44 • @Lynn Nice catch! This can easily be fixed by replacing ˜ with O (sum). Commented Sep 21, 2016 at 12:55 # Pyth, 1211 10 bytes eSsM/#0,Vt Forms pairs, filters by zero member, sorts by sum, returns largest. • ,Vt (implicit QQ) returns the same pairs as .:Q2, but with the pairs flipped. Should work, though. Commented Sep 21, 2016 at 14:38 • f}0T is /#0 Commented Sep 21, 2016 at 23:10 # 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. ## JavaScript (ES6), 5957 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 • You can save two bytes by using == instead of === Commented Sep 21, 2016 at 11:47 • I you can save a few bytes in several places: l=>l.map((n,i)=>m=l[i-1]*l[i+1]==0&n>m?n:m,m=-1/0)|m Commented Sep 21, 2016 at 15:02 • Error: { "message": "Syntax error", "filename": "stacksnippets.net/js", "lineno": 15, "colno": 3 } – user58988 Commented Sep 26, 2016 at 15:17 • @RosLuP - This requires ES6 with arrow function support and won't work on all browsers (including, but not limited to: all IE versions before Edge, all Safari versions below v10, etc.) Commented Sep 26, 2016 at 15:48 ## 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)) ## 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)] • I don't think you need the parentheses around a+b. Commented Sep 21, 2016 at 11:24 • @Martin Ender syntax error occurs... ideone.com/F6Ed4B Commented Sep 21, 2016 at 11:28 • It works in Ruby 2.3. (available here for instance: repl.it/languages/ruby) Commented Sep 21, 2016 at 11:32 • @Martin Ender When I use "!=" instead of "==", it works. Thanks for your advice! ideone.com/F6Ed4B Commented Sep 21, 2016 at 11:38 • There's a bug in there :(. -3 -2 0 returns 0. I think replacing ...?0:... with ...?-1.0/0:... should fix it, adding 5 bytes. Commented Sep 21, 2016 at 16:11 # PHP, 7768 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>'

• using \K to discard the match so far is shorter than using a look-behind. Commented Sep 21, 2016 at 11:46
• You can also use space separation for input and then use \S+ to match a signed integer. You'll probably have to use \b0, so you don't have to prepend the ,. Commented Sep 21, 2016 at 11:51
• Does this work for input like 4 0 0 5 ? Commented Sep 21, 2016 at 16:01
• @TonHospel No. Does \K not work with alternatives? For unknown reason, the second alternative returns 0 0, so that there is no more 0 to match before the 5. Fixed, thanks. Commented Sep 21, 2016 at 16:25
• Make a look at the other PHP solution with register_globals Commented Sep 21, 2016 at 20:35

# Java 7, 118105 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:

Try it here.

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
• slightly different approach using arithmetics, seems to be working int d(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;} Commented Sep 21, 2016 at 15:18
• The output is wrong, when the first number is not adjacent to 0, but larger than any number adjacent to 0. Reproducible by the test case {2, 1, 0}. You can fix this by initializing i with 0 directly and m with 1<<31 (+1 overall).
– mrco
Commented Sep 23, 2016 at 13:35

# Jelly, 6 5 bytes

SfµƝṀ

Try it online!

-1 remembering it's not a dyadic chain

S        Sum the pair,
f       and filter it to only element[s] in the pair.
Ṁ    Take the maximum.

# Nekomata, 7 bytes

qᵗZđ+aṀ

Attempt This Online!

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
a      All possible values
Ṁ     Maximum

# Jelly, 8 bytes

ṡ2ẠÐḟS€Ṁ

Try it online!

ṡ2            Overlapping pairs
ẠÐḟ         Remove pairs without zeroes
S€       Sum of each pair
Ṁ      Maximum

## 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.

# 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

# 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)

TryAPL online!

## 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

1. Find indices for which the vector v takes on the values 0: w <- which(v == 0)
2. Create new vector which contains the indices +-1: w-1 and w+1
3. Extract elements that match the indices w-1 and w+1
4. 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]
• Need an extra parenthesis otherwise fails all test cases where max is to right of 0 such as c(1, 4, 3, 6, 0, 10, 7, 0) c((w<-which(v==0))-1,w+1) Also a tad bit shorter with scan sort((v<-scan())[c(w<-which(v==0)-1,w+1)],T)[1]
– Vlo
Commented Sep 21, 2016 at 14:15
• @Vlo Thanks for pointing that obvious error out, +1. In your suggested solution you forgot the ()too though ;). Updated the code and assigned v prior manipulation now. Commented Sep 21, 2016 at 15:11

# 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.

# K (ngn/k), 14 bytes

|/+/'(*/')_2':

Try it online!

|/+/'(*/')_2':
2':   pairs
(*/')_      discard those whose product are nonzero
+/'            sum of each pair
|/               maximum

# 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 # 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 ## 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 # VyxalG, 36 bitsv2, 4.5 bytes 2lƛ∑w↔ Try it Online! 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. • Did you forget the update the code, TIO, and byte-count? zṠ↔ is 3.375 bytes, isn't it? Or is it incorrect somehow, and you forgot to roll-back the explanation? Commented Feb 22 at 15:00 # Nibbles, 8.5 bytes /.|!$>>@:?$0+$]

Attempt This Online!

Disgustingly long…

/.|!$>>@:?$0+$] ! : Zip$            the input
>>          with the tail of
@         the input
|             Filter by
?$0 containing a zero . Map +$   sum
`/             ] Maximum

# BQN, 14 bytes

⌈´((«∨»)0⊸=)⊸/

Try

Seemed like a good excuse to use the shifts in «∨».

• 13: ⌈´(«∨»)∘=⟜0⊸/ Commented Sep 18, 2023 at 7:11
• @Bubbler I was just coming here to post that exact solution! Commented Feb 23 at 3:59

# J, 16 bytes

}.>./@(+#~0=*)}:

Attempt This Online!

}.>./@(+#~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

# Vyxal 3G, 4 bytes

oᶻΠf

Try it Online!

oᶻΠf­⁡​‎‎⁪⁡⁪⁠⁪⁡⁪‏‏​⁡⁠⁡‌⁢​‎‎⁪⁡⁪⁠⁪⁢⁪‏⁠‎⁪⁡⁪⁠⁪⁣⁪‏‏​⁡⁠⁡‌⁣​‎‎⁪⁡⁪⁠⁪⁤⁪‏‏
o     # ‎⁡overlapping pairs
ᶻΠ   # ‎⁢where the product is zero
f  # flatten
💎

Created with the help of Luminespire.

• 3 byters fail on [4,5,9,1,0,0] Commented Feb 22 at 16:28
• Fails on [9, 4, 9, 0, 19, 1, 9, 15, -2] Commented Feb 26 at 5:41
• @emanresuA luckily there were other 4 byters Commented Feb 26 at 12:48

# 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.

# 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 @

Fiddle

## 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