38
\$\begingroup\$

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!

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

31 Answers 31

3
\$\begingroup\$

Jelly, 8 bytes

ṡ2ẠÐḟS€Ṁ

Try it online!

ṡ2            Overlapping pairs
  ẠÐḟ         Remove pairs without zeroes
     S€       Sum of each pair
       Ṁ      Maximum
\$\endgroup\$
19
\$\begingroup\$

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
\$\endgroup\$
4
  • \$\begingroup\$ x(~~(dec2bin(5)-48)). Who's idea was it to implement that one? Very clever, and useful for logical arrays! :) Nice answer! \$\endgroup\$ Sep 21 '16 at 11:02
  • 1
    \$\begingroup\$ @WeeingIfFirst Thanks! I had used dec2bin()-'0' hundreds of times in MATLAB, so I knew that one had to be in MATL :-) \$\endgroup\$
    – Luis Mendo
    Sep 21 '16 at 11:04
  • 5
    \$\begingroup\$ 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 =) \$\endgroup\$ Sep 21 '16 at 11:56
  • 2
    \$\begingroup\$ Convolution Rocks. +1 \$\endgroup\$
    – Suever
    Sep 21 '16 at 17:41
10
\$\begingroup\$

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.

\$\endgroup\$
7
  • \$\begingroup\$ This is amazing haha! Just in time :p. \$\endgroup\$
    – Adnan
    Sep 21 '16 at 10:24
  • 1
    \$\begingroup\$ Just implemented one of these operators or? :) \$\endgroup\$ Sep 21 '16 at 10:27
  • 1
    \$\begingroup\$ @WeeingIfFirst: ü was added just yesterday :) \$\endgroup\$
    – Emigna
    Sep 21 '16 at 10:28
  • 2
    \$\begingroup\$ Won’t this return 0 if the actual answer would be negative? You have to throw out the zeroes, I think. \$\endgroup\$
    – Lynn
    Sep 21 '16 at 12:44
  • 1
    \$\begingroup\$ @Lynn Nice catch! This can easily be fixed by replacing ˜ with O (sum). \$\endgroup\$
    – Adnan
    Sep 21 '16 at 12:55
9
\$\begingroup\$

Haskell, 63 43 bytes

f x=maximum[a+b|(a,b)<-tail>>=zip$x,a*b==0]

Thanks to @MartinEnder for 4 bytes!

\$\endgroup\$
3
  • \$\begingroup\$ I think you can use a*b==0 instead of the ||. \$\endgroup\$ Sep 21 '16 at 10:15
  • \$\begingroup\$ You have to go back to previous version with zip. Here a and be are no longer adjacent \$\endgroup\$
    – Damien
    Sep 21 '16 at 10:46
  • \$\begingroup\$ You don't need lambdabot here. This is "regular" Haskell \$\endgroup\$
    – Damien
    Sep 21 '16 at 11:00
8
\$\begingroup\$

Pyth, 12 11 10 bytes

eSsM/#0,Vt

Forms pairs, filters by zero member, sorts by sum, returns largest.

\$\endgroup\$
2
  • \$\begingroup\$ ,Vt (implicit QQ) returns the same pairs as .:Q2, but with the pairs flipped. Should work, though. \$\endgroup\$ Sep 21 '16 at 14:38
  • \$\begingroup\$ f}0T is /#0 \$\endgroup\$
    – isaacg
    Sep 21 '16 at 23:10
7
\$\begingroup\$

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

\$\endgroup\$
4
  • 1
    \$\begingroup\$ You can save two bytes by using == instead of === \$\endgroup\$
    – Huntro
    Sep 21 '16 at 11:47
  • 1
    \$\begingroup\$ 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 \$\endgroup\$ Sep 21 '16 at 15:02
  • \$\begingroup\$ Error: { "message": "Syntax error", "filename": "stacksnippets.net/js", "lineno": 15, "colno": 3 } \$\endgroup\$
    – user58988
    Sep 26 '16 at 15:17
  • \$\begingroup\$ @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.) \$\endgroup\$
    – Arnauld
    Sep 26 '16 at 15:48
6
\$\begingroup\$

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))
\$\endgroup\$
0
5
\$\begingroup\$

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.

\$\endgroup\$
4
\$\begingroup\$

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)]
\$\endgroup\$
6
  • \$\begingroup\$ I don't think you need the parentheses around a+b. \$\endgroup\$ Sep 21 '16 at 11:24
  • \$\begingroup\$ @Martin Ender syntax error occurs... ideone.com/F6Ed4B \$\endgroup\$
    – cia_rana
    Sep 21 '16 at 11:28
  • \$\begingroup\$ It works in Ruby 2.3. (available here for instance: repl.it/languages/ruby) \$\endgroup\$ Sep 21 '16 at 11:32
  • \$\begingroup\$ @Martin Ender When I use "!=" instead of "==", it works. Thanks for your advice! ideone.com/F6Ed4B \$\endgroup\$
    – cia_rana
    Sep 21 '16 at 11:38
  • \$\begingroup\$ 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. \$\endgroup\$
    – m-chrzan
    Sep 21 '16 at 16:11
4
\$\begingroup\$

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

\$\endgroup\$
6
  • 2
    \$\begingroup\$ using \K to discard the match so far is shorter than using a look-behind. \$\endgroup\$
    – user59178
    Sep 21 '16 at 11:46
  • 2
    \$\begingroup\$ 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 ,. \$\endgroup\$ Sep 21 '16 at 11:51
  • 1
    \$\begingroup\$ Does this work for input like 4 0 0 5 ? \$\endgroup\$
    – Ton Hospel
    Sep 21 '16 at 16:01
  • \$\begingroup\$ @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. \$\endgroup\$
    – Titus
    Sep 21 '16 at 16:25
  • \$\begingroup\$ Make a look at the other PHP solution with register_globals \$\endgroup\$ Sep 21 '16 at 20:35
4
\$\begingroup\$

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:

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
\$\endgroup\$
2
  • 1
    \$\begingroup\$ 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;} \$\endgroup\$
    – cliffroot
    Sep 21 '16 at 15:18
  • 3
    \$\begingroup\$ 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). \$\endgroup\$
    – mrco
    Sep 23 '16 at 13:35
3
\$\begingroup\$

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.
\$\endgroup\$
3
\$\begingroup\$

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
\$\endgroup\$
0
3
\$\begingroup\$

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!

\$\endgroup\$
3
\$\begingroup\$

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]
\$\endgroup\$
2
  • 1
    \$\begingroup\$ 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] \$\endgroup\$
    – Vlo
    Sep 21 '16 at 14:15
  • \$\begingroup\$ @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. \$\endgroup\$
    – Billywob
    Sep 21 '16 at 15:11
3
\$\begingroup\$

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.

\$\endgroup\$
0
2
\$\begingroup\$

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
\$\endgroup\$
2
\$\begingroup\$

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

\$\endgroup\$
0
1
\$\begingroup\$

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.

\$\endgroup\$
1
\$\begingroup\$

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

\$\endgroup\$
1
\$\begingroup\$

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
\$\endgroup\$
1
\$\begingroup\$

q, 38 bytes

{max x where 0 in'x,'(next x),'prev x}
\$\endgroup\$
1
  • \$\begingroup\$ This doesn't seem to work when the maximum comes after a 0. Also, I'm no q expert, but I think you would have to surround your code with {} to make it a function. \$\endgroup\$
    – Dennis
    Sep 21 '16 at 18:07
1
\$\begingroup\$

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
\$\endgroup\$
1
\$\begingroup\$

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
}
\$\endgroup\$
1
\$\begingroup\$

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
\$\endgroup\$
1
\$\begingroup\$

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.

\$\endgroup\$
4
  • 1
    \$\begingroup\$ I'm assuming your indentation is a bit off. Otherwise it's 126 bytes =) \$\endgroup\$ Sep 22 '16 at 10:58
  • \$\begingroup\$ Ok, thanks. Fixed that now. \$\endgroup\$
    – kgbviz
    Sep 22 '16 at 11:15
  • \$\begingroup\$ What is SPSS syntax? Just curious. Also, welcome to PPCG! \$\endgroup\$
    – clismique
    Sep 22 '16 at 12:09
  • \$\begingroup\$ @qwerp-derp Thank you for the welcome! :-) SPSS Syntax is a high-level data management programming language within the fourth generation of programming languages . It is used within IBM SPSS Statistics software package for statistical analysis. \$\endgroup\$
    – kgbviz
    Sep 22 '16 at 14:01
1
\$\begingroup\$

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 }));
}
\$\endgroup\$
7
  • \$\begingroup\$ Hi. you can remove the space at int[]i) {. Also, I count 75 bytes in your current code (74 if you remove the space). \$\endgroup\$ Sep 21 '16 at 12:25
  • \$\begingroup\$ I think you can save 4 bytes by inverting the ternaries: a?b?i.Min()).Max():a:b \$\endgroup\$
    – Titus
    Sep 21 '16 at 12:46
  • \$\begingroup\$ Plus using System.Linq;, no? \$\endgroup\$ Sep 22 '16 at 0:28
  • \$\begingroup\$ True but this question just asked for a method, not a full program and using System.Linq; is part of the default new class template. \$\endgroup\$
    – Grax32
    Sep 22 '16 at 11:00
  • \$\begingroup\$ @Grax Either way you need to include the using statement in your byte count \$\endgroup\$ Sep 23 '16 at 14:58
1
\$\begingroup\$

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!

\$\endgroup\$
4
  • \$\begingroup\$ Am I doing it wrong? pastebin.com/0AA11xcw \$\endgroup\$
    – manatwork
    Sep 22 '16 at 11:10
  • \$\begingroup\$ This fails for cases such as 20 0, because s[w(s==0)+1] returns NA, and max's default treatment of NA is to return it. You can fix by adding the argument na.rm=T, or re-work the code to use sort (see the other R answer posted above). \$\endgroup\$
    – rturnbull
    Sep 22 '16 at 12:50
  • \$\begingroup\$ Can you condense everything into one line? I don't know how to code in R, but I'm assuming you can. \$\endgroup\$
    – clismique
    Sep 25 '16 at 7:36
  • \$\begingroup\$ @Qwerp-Derp: Not as far as I know. scan() waits for console input to read in the vector, the input stream is closed by entering an empty line. If you were to run the two lines as one, the second part would be at least partially recognized to be input for to the vector s. \$\endgroup\$
    – Headcrash
    Sep 25 '16 at 7:42
0
\$\begingroup\$

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
\$\endgroup\$
0
\$\begingroup\$

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.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.