Find the largest number that's adjacent to a zero

38

3

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!

Stewie Griffin

Posted 2016-09-21T09:57:59.870

Reputation: 43 471

You should add a test case like the 4th one, but where the result is negative (there are positive numbers in the list). – mbomb007 – 2016-09-21T15:11:13.370

I was going to try this in Retina, but then I noticed there are negatives. Retina hates negatives. – mbomb007 – 2016-09-21T15:12:19.533

2Don't let retina dictate what you can and cannot do. Take charge, you're the boss! – Stewie Griffin – 2016-09-22T10:26:31.083

Answers

3

Jelly, 8 bytes

ṡ2ẠÐḟS€Ṁ

Try it online!

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

Lynn

Posted 2016-09-21T09:57:59.870

Reputation: 55 648

19

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

Luis Mendo

Posted 2016-09-21T09:57:59.870

Reputation: 87 464

x(~~(dec2bin(5)-48)). Who's idea was it to implement that one? Very clever, and useful for logical arrays! :) Nice answer! – Stewie Griffin – 2016-09-21T11:02:14.580

1@WeeingIfFirst Thanks! I had used dec2bin()-'0' hundreds of times in MATLAB, so I knew that one had to be in MATL :-) – Luis Mendo – 2016-09-21T11:04:11.947

5By 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 =) – Stewie Griffin – 2016-09-21T11:56:21.103

2Convolution Rocks. +1 – Suever – 2016-09-21T17:41:51.700

10

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.

Emigna

Posted 2016-09-21T09:57:59.870

Reputation: 50 798

This is amazing haha! Just in time :p. – Adnan – 2016-09-21T10:24:20.067

@Adnan: Indeed. Awesome timing :) – Emigna – 2016-09-21T10:25:20.907

1Just implemented one of these operators or? :) – Stewie Griffin – 2016-09-21T10:27:37.560

1@WeeingIfFirst: ü was added just yesterday :) – Emigna – 2016-09-21T10:28:13.417

2Won’t this return 0 if the actual answer would be negative? You have to throw out the zeroes, I think. – Lynn – 2016-09-21T12:44:06.017

1@Lynn Nice catch! This can easily be fixed by replacing ˜ with O (sum). – Adnan – 2016-09-21T12:55:17.043

@Lynn: Right you are. Thanks for catching that bug :) – Emigna – 2016-09-21T13:32:59.300

9

Haskell, 63 43 bytes

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

Thanks to @MartinEnder for 4 bytes!

BlackCap

Posted 2016-09-21T09:57:59.870

Reputation: 3 576

I think you can use a*b==0 instead of the ||. – Martin Ender – 2016-09-21T10:15:54.003

You have to go back to previous version with zip. Here a and be are no longer adjacent – Damien – 2016-09-21T10:46:51.447

You don't need lambdabot here. This is "regular" Haskell – Damien – 2016-09-21T11:00:12.143

8

Pyth, 12 11 10 bytes

eSsM/#0,Vt

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

orlp

Posted 2016-09-21T09:57:59.870

Reputation: 37 067

,Vt (implicit QQ) returns the same pairs as .:Q2, but with the pairs flipped. Should work, though. – PurkkaKoodari – 2016-09-21T14:38:19.243

f}0T is /#0 – isaacg – 2016-09-21T23:10:58.210

7

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

Arnauld

Posted 2016-09-21T09:57:59.870

Reputation: 111 334

1You can save two bytes by using == instead of === – Huntro – 2016-09-21T11:47:40.543

1I 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 – ETHproductions – 2016-09-21T15:02:20.007

Error: { "message": "Syntax error", "filename": "http://stacksnippets.net/js", "lineno": 15, "colno": 3 }

– RosLuP – 2016-09-26T15:17:33.010

@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.) – Arnauld – 2016-09-26T15:48:20.227

6

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

Neil

Posted 2016-09-21T09:57:59.870

Reputation: 95 035

5

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.

Jonathan Allan

Posted 2016-09-21T09:57:59.870

Reputation: 67 804

4

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

Titus

Posted 2016-09-21T09:57:59.870

Reputation: 13 814

2using \K to discard the match so far is shorter than using a look-behind. – user59178 – 2016-09-21T11:46:50.747

2You 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 ,. – Martin Ender – 2016-09-21T11:51:46.583

1Does this work for input like 4 0 0 5 ? – Ton Hospel – 2016-09-21T16:01:18.017

@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. – Titus – 2016-09-21T16:25:04.900

Make a look at the other PHP solution with register_globals – Jörg Hülsermann – 2016-09-21T20:35:01.617

@JörgHülsermann Take a look at my comment to that. – Titus – 2016-09-21T21:18:38.167

4

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

cia_rana

Posted 2016-09-21T09:57:59.870

Reputation: 441

I don't think you need the parentheses around a+b. – Martin Ender – 2016-09-21T11:24:33.437

@Martin Ender syntax error occurs... https://ideone.com/F6Ed4B

– cia_rana – 2016-09-21T11:28:39.683

It works in Ruby 2.3. (available here for instance: https://repl.it/languages/ruby)

– Martin Ender – 2016-09-21T11:32:26.683

@Martin Ender When I use "!=" instead of "==", it works. Thanks for your advice! https://ideone.com/F6Ed4B

– cia_rana – 2016-09-21T11:38:29.270

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. – m-chrzan – 2016-09-21T16:11:47.303

@m-chrzan I didn't notice that. Thanks for information. – cia_rana – 2016-09-21T17:37:47.603

4

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

Kevin Cruijssen

Posted 2016-09-21T09:57:59.870

Reputation: 67 575

1slightly 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;} – cliffroot – 2016-09-21T15:18:13.210

3The 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 – 2016-09-23T13:35:27.257

3

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.

Martin Ender

Posted 2016-09-21T09:57:59.870

Reputation: 184 808

3

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

Luis Mendo

Posted 2016-09-21T09:57:59.870

Reputation: 87 464

3

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.

LegionMammal978

Posted 2016-09-21T09:57:59.870

Reputation: 15 731

3

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]

Billywob

Posted 2016-09-21T09:57:59.870

Reputation: 3 363

1Need 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 – 2016-09-21T14:15:50.180

@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. – Billywob – 2016-09-21T15:11:44.503

3

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!

Adám

Posted 2016-09-21T09:57:59.870

Reputation: 37 779

2

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

nyro_0

Posted 2016-09-21T09:57:59.870

Reputation: 281

2

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

Ton Hospel

Posted 2016-09-21T09:57:59.870

Reputation: 14 114

1

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.

SCB

Posted 2016-09-21T09:57:59.870

Reputation: 261

1

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 }));
}

Grax32

Posted 2016-09-21T09:57:59.870

Reputation: 1 282

Hi. you can remove the space at int[]i) {. Also, I count 75 bytes in your current code (74 if you remove the space). – Kevin Cruijssen – 2016-09-21T12:25:31.250

I think you can save 4 bytes by inverting the ternaries: a?b?i.Min()).Max():a:b – Titus – 2016-09-21T12:46:32.987

Plus using System.Linq;, no? – pinkfloydx33 – 2016-09-22T00:28:39.220

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. – Grax32 – 2016-09-22T11:00:09.173

@Grax Either way you need to include the using statement in your byte count – TheLethalCoder – 2016-09-23T14:58:51.977

However compiling to a Func<int[], int> gets you 50 bytes + using System.Linq; for 68 bytes: using System.Linq;i=>i.Zip(i.Skip(1),(a,b)=>a*b==0?1<<31:a+b).Max(); – TheLethalCoder – 2016-09-23T15:02:15.230

Where do I find the instructions for this format? – Grax32 – 2016-09-23T17:54:26.977

1

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

t-clausen.dk

Posted 2016-09-21T09:57:59.870

Reputation: 2 874

1

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

AdmBorkBork

Posted 2016-09-21T09:57:59.870

Reputation: 41 581

1

q, 38 bytes

{max x where 0 in'x,'(next x),'prev x}

Liam Baron

Posted 2016-09-21T09:57:59.870

Reputation: 131

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. – Dennis – 2016-09-21T18:07:52.673

1

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

miles

Posted 2016-09-21T09:57:59.870

Reputation: 15 654

1

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
}

Brad Gilbert b2gills

Posted 2016-09-21T09:57:59.870

Reputation: 12 713

1

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

aross

Posted 2016-09-21T09:57:59.870

Reputation: 1 583

1

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!

Headcrash

Posted 2016-09-21T09:57:59.870

Reputation: 11

Am I doing it wrong? http://pastebin.com/0AA11xcw

– manatwork – 2016-09-22T11:10:56.957

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). – rturnbull – 2016-09-22T12:50:23.667

Can you condense everything into one line? I don't know how to code in R, but I'm assuming you can. – clismique – 2016-09-25T07:36:43.093

@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. – Headcrash – 2016-09-25T07:42:58.067

0

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

rnso

Posted 2016-09-21T09:57:59.870

Reputation: 1 635

0

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.

LambdaBeta

Posted 2016-09-21T09:57:59.870

Reputation: 2 499

0

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;

Roman Gräf

Posted 2016-09-21T09:57:59.870

Reputation: 2 915

Why do not use directly the input as array. I could not seen the reason for json_encode. – Jörg Hülsermann – 2016-09-21T20:37:18.873

For non-default settings you have to add the full length of the setting change to your byte count. (see http://meta.codegolf.stackexchange.com/q/4778#4778) In this case +21 bytes for -d register_globals=1 (or specify a version where register_globals is enabled by default)

– Titus – 2016-09-21T21:14:36.910

But json_decode is a nice idea. – Titus – 2016-09-21T21:15:50.293

@Titus What I mean is ?id[]=1&id[]=2&id[]=3 and then $_GET["id"] gives back an array. For this reason json_decode makes no sense for me – Jörg Hülsermann – 2016-09-21T21:42:51.097

@JörgHülsermann It costs bytes, but it´s still a nice idea. – Titus – 2016-09-21T22:12:45.417

This answer is incorrect – aross – 2016-09-22T09:23:39.067

0

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.

kgbviz

Posted 2016-09-21T09:57:59.870

Reputation: 11

1I'm assuming your indentation is a bit off. Otherwise it's 126 bytes =) – Stewie Griffin – 2016-09-22T10:58:02.980

Ok, thanks. Fixed that now. – kgbviz – 2016-09-22T11:15:12.300

What is SPSS syntax? Just curious. Also, welcome to PPCG! – clismique – 2016-09-22T12:09:21.337

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

– kgbviz – 2016-09-22T14:01:29.787