# Sum of neighbours

This should be a fairly simple challenge.

For an array of numbers, generate an array where for every element all neighbouring elements are added to itself, and return the sum of that array.

Here is the transformation which occurs on the input array [1,2,3,4,5]

[1,2,3,4,5] => [1+2, 2+1+3, 3+2+4, 4+3+5, 5+4] => [3,6,9,12,9] => 39
0          => neighbours of item 0, including item 0
[1,2]       => 1 + 2      => 3
1
[1,2,3]     => 1 + 2 + 3  => 6
2
[2,3,4]   => 2 + 3 + 4  => 9
3
[3,4,5] => 3 + 4 + 5  => 12
4
[4,5] => 4 + 5      => 9

3+6+9+12+9 => 39


### Test cases

[]            => 0 (or falsy)
[1]           => 1
[1,4]         => 10 (1+4 + 4+1)
[1,4,7]       => 28
[1,4,7,10]    => 55
[-1,-2,-3]    => -14
[0.1,0.2,0.3] => 1.4
[1,-20,300,-4000,50000,-600000,7000000] => 12338842


var QUESTION_ID=96188,OVERRIDE_USER=41257;function answersUrl(e){return"http://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"http://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>

• Oct 14, 2016 at 12:42
• Do we need to support floating point numbers or only integers? Oct 14, 2016 at 12:55
• @corvus_192 The test cases include non-integers. Oct 14, 2016 at 13:10
• @Geobits I didn't notice that, I'll edit my answer. Oct 14, 2016 at 13:12
• You should do this with 2 dimensional arrays next. Oct 14, 2016 at 18:23

# Python, 25 bytes

lambda a:sum((a*3)[1:-1])


To see why this works, rotate the expansion in the OP by 45 degrees:

             1 + 2
+ 1 + 2 + 3                            2 + 3 + 4 + 5
+ 2 + 3 + 4          =       + 1 + 2 + 3 + 4 + 5
+ 3 + 4 + 5              + 1 + 2 + 3 + 4.
+ 4 + 5


# Python 2, 28 bytes

lambda a:sum(a)*3-a[0]-a[-1]


Just 3 times the sum and minus one of each end element

• I also found a neat 25-byte solution.
– lynn
Oct 14, 2016 at 16:32
• Actually, what if a is the empty list (first test case)? a[0] will throw an IndexError, no?
– lynn
Oct 14, 2016 at 17:37

# MATL, 5 bytes

7BZ+s


Try it online!

### Explanation

7B  % Push array [1, 1, 1], obtained as 7 in binary
Z+  % Take input implicitly. Convolve with [1, 1, 1], keeping size
s   % Sum of resulting array. Display implicitly

• Very clever use of 7B there to get [1 1 1] Oct 14, 2016 at 12:51
• I don't know MATL, but I wonder: for a list [a,b,c,...], how do you get a+b but avoid getting a? Oct 14, 2016 at 13:24
• @Christian The addition is done by means of a convolution operation. It would produce the partial results you refer to, but there's a version of convolution that avoids them, because it produces an output array with only as many entries as the input. This is also used in Suever's answer Oct 14, 2016 at 13:40

# 05AB1E, 11 5 bytes

Saved 6 bytes thanks to Adnan.

€Ð¦¨O


Try it online!

Explanation

€Ð     # triplicate each item in the list
¦¨   # remove first and last element
O  # sum

• Does €Ð¦¨O work :)? Oct 14, 2016 at 18:31
• @Adnan: Brilliant! I tried to think of a way to do it with 3*, but I never even considered €Ð even though I've used €D before :P Oct 14, 2016 at 22:24

## JavaScript (ES6), 40 33 bytes

l=>eval(l.join+)*3-l[0]-l.pop()


Returns NaN when given an empty list.

• You can chop off 2 more characters if you move the multiplication into the join like so v=>eval(v.join*3++"*2")-v[0] Oct 15, 2016 at 1:20
• @Grax - Nice! However, it would not be falsy anymore for the empty array. Oct 15, 2016 at 1:30
• There's always something isn't there? Oct 15, 2016 at 1:44
• @Grax - No. The first test case is an empty array. Oct 15, 2016 at 11:32

## R, 75 70 52 34 33 31 bytes

Sum times three and subtract first and last element

sum(x<-scan())*3-x[1]-tail(x,1)


Edit: Saved 3 extra bytes thanks to @rturnbull

# Scala, 47 bytes

def&(a:Float*)=(0+:a:+0)sliding 3 map(_.sum)sum


Prepends and appends a 0, then uses a sliding window of size 3 to sum the neighbors, and calculates the total sum

# Java 7, 72 Bytes

float c(float[]a){float s=0,l=0;for(float i:a)s+=l=i;return 3*s-l-a[0];}

• I don't think adding extra inputs denoting the first and last elements of the array is in the spirit of the challenge. Oct 14, 2016 at 12:50
• @Geobits I change it..... Oct 14, 2016 at 13:00
• Cool. You can golf it some more by using float instead of double :) Oct 14, 2016 at 13:04
• Can i use it instead.... Double has 2x the precision of float. Oct 14, 2016 at 13:09
• why not ints? Oct 14, 2016 at 19:32

## Mathematica, 3432 29 bytes

Taking some inspiration Lynn's neat Python answer...

Check[3Tr@#-Last@#-#[[1]],0]&


or

Check[3(+##)-#&@@#-Last@#,0]&


or

Check[##-#/3&@@#*3-Last@#,0]&


Unfortunately, this approach isn't quite as convenient in Mathematica as it is in Python, because there's no short and safe way to discard the first and last element of a list that might be empty.

• +1 for teaching me Check Oct 14, 2016 at 16:07

# MATLAB, 3128 26 bytes

3 bytes saved thanks to @Luis

@(x)sum(conv(x,1:3>0,'s'))


This creates an anonymous function named ans that can be called like: ans([1, 2, 3, 4, 5])

In order to provide an online demo (which uses Octave), I had to use 'same' instead of 's' as the last input to conv

Online Demo

Explanation

We perform convolution (conv) with a 1 x 3 kernel of all 1's (created by making an array 1:3 and then comparing to zero >0) and keep the size of the original by specifying the third input as 'same' or in MATLAB we can simply shorten this to 's'. We then apply the sum to the result.

• You can probably shorten to 's' Oct 14, 2016 at 13:00
• @LuisMendo Oh good call! MATLAB allows it but Octave doesn't (of course) Oct 14, 2016 at 13:02

# Jelly, 5 bytes

ẋ3ṖḊS


Try it online!

Translation of my Python answer.

ẋ3      Concatenate three copies of the input list
Ṗ     Remove the last element
Ḋ    Remove the first element
S   Sum

• So many 5 byters, where's the 4? ḊṖ+ḤS, Ṗ++ḊS, +Ḋ+ṖS, +Ṗ+ḊS, ... Oct 14, 2016 at 17:10

# J, 9 bytes

+/@,}.,}:


For [1, 2, 3, 4, 5], the neighbors are

1 2 3 4 5
1+2
1+2+3
2+3+4
3+4+5
4+5


Then look along the diagonals of the sums

(2+3+4+5)+(1+2+3+4+5)+(1+2+3+4)


So we need only the find the sum of the input with its head removed and with its tail removed.

## Usage

   f =: +/@,}.,}:
f 1 2 3 4 5
39
f '' NB. Empty array
0
f 1
1
f 1 4
10
f 1 4 7
28
f 1 4 7 10
55
f _1 _2 _3
_14
f 0.1 0.2 0.3
1.4
f 1 _20 300 _4000 50000 _600000 7000000
12338842


## Explanation

+/@,}.,}:  Input: array A
}:  Return a list with the last value in A removed
}.     Return a list with the first value in A removed
,    Join them
,       Join that with A
+/@        Reduce that using addition to find the sum and return

• Nice. And happy 6k+! Oct 15, 2016 at 4:20

# Brain-Flak, 68 bytes

(<><>)([]){{}({}({})<>{})<>({}<(({})<>{})><>)([][()()])}{}({}{}<>{})


Try it online!

Explanation:

#Push a 0
(<><>)

#Push the stack height
([])

#While true:
{

#Pop the stack height
{}

#Add the sum of the top 3 elements to the other stack, and pop the top of the stack
({}({})<>{})<>({}<(({})<>{})><>)

#Push the new stack height minus two
([][()()])

#End
}

#Pop the exhausted counter
{}

#Add the top two numbers to the other stack
({}{}<>)


## PowerShell v2+, 40 bytes

param($a)($a-join'+'|iex)*3-$a[0]-$a[-1]


Similar to the other answers, sums the list, multiplies by 3, subtracts the end elements. Barfs out a spectacular error for empty input, and then spits out 0, but since STDERR is ignored by default, this is OK.

PS C:\Tools\Scripts\golfing> .\sum-of-neighbors.ps1 @()
Invoke-Expression : Cannot bind argument to parameter 'Command' because it is an empty string.
At C:\Tools\Scripts\golfing\sum-of-neighbors.ps1:1 char:22
+ param($a)($a-join'+'|iex)*3-$a[0]-$a[-1]
+                      ~~~
+ CategoryInfo          : InvalidData: (:String) [Invoke-Expression], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationErrorEmptyStringNotAllowed,Microsoft.PowerShell.Commands.InvokeExpressionCommand

0

PS C:\Tools\Scripts\golfing> .\sum-of-neighbors.ps1 @(1)
1

PS C:\Tools\Scripts\golfing> .\sum-of-neighbors.ps1 @(1,4)
10

PS C:\Tools\Scripts\golfing> .\sum-of-neighbors.ps1 @(1,4,7)
28

PS C:\Tools\Scripts\golfing> .\sum-of-neighbors.ps1 @(1,4,7,10)
55

PS C:\Tools\Scripts\golfing> .\sum-of-neighbors.ps1 @(-1,-2,-3)
-14

PS C:\Tools\Scripts\golfing> .\sum-of-neighbors.ps1 @(0.1,0.2,0.3)
1.4

PS C:\Tools\Scripts\golfing> .\sum-of-neighbors.ps1 @(1,-20,300,-4000,50000,-600000,7000000)
12338842

• ParameterArgumentValidationErrorEmptyStringNotAllowed ಠ_ಠ What an exception!
Oct 14, 2016 at 20:02

# Ruby, 3533 31 bytes

Inspired by Lynn's solution:

->a{[*(a*3)[1..-2]].reduce:+}


The to_a segment is there to handle the empty array.

EDIT: Thanks to m-chrzan and histocrat.

• You don't need parentheses around :+. Oct 14, 2016 at 18:59
• [*(a*3)[1..-2]] does .to_a in two fewer bytes. Oct 14, 2016 at 19:19
• You might want to give Ruby 2.4.0 a go. It comes with Array#sum. Oct 14, 2016 at 20:05

# Perl 6, 25 bytes

{.sum*3-.[0]-(.[*-1]//0)}    # generates warning
{
+$_ # the number of elements && # if that is 0 return 0, otherwise return the following .sum * 3 # sum them up and multiply by 3 - .[ 0 ] # subtract the first value - .[*-1] # subtract the last value }  ## Test: use v6.c; use Test; my &code = {+$_&&.sum*3-.[0]-.[*-1]}

my @tests = (
[]            => 0,
[1]           => 1,
[1,4]         => 10,
[1,4,7]       => 28,
[1,4,7,10]    => 55,
[-1,-2,-3]    => -14,
[0.1,0.2,0.3] => 1.4,
[1,-20,300,-4000,50000,-600000,7000000] => 12338842,
);

plan +@tests;

for @tests -> $_ ( :key(@input), :value($expected) ) {
is code(@input), $expected, .gist; }  # MathGolf, 5 4 bytes ñ+╞Σ  Try it online. Explanation: ñ # Palindromize the (implicit) input-list + # Merge it to the (implicit) input-list ╞ # Discard the first item Σ # Sum the remaining items in the list # (after which the entire stack is output implicitly as result)  • Fun to see that MathGolf is still being used! – maxb Apr 9 at 11:56 # 05AB1E, 4 bytes û«¦O  Port of my MathGolf answer. Explanation: û # Palindromize the (implicit) input-list « # Merge it to the (implicit) input-list ¦ # Remove the first item O # Sum the remaining items in the list # (after which this sum is output implicitly as result)  # PHP, 39 bytes <?=3*array_sum($a=$argv)-$a[1]-end($a);  Run like this: echo '<?=3*array_sum($a=$argv)-$a[1]-end($a);' | php -- 1 -20 300 -4000 50000 -600000 7000000 2>/dev/null;echo  # Explanation Challenge can be reduced to adding every number 3 times, except the first and last number (added twice). Therefore I return 3 times the sum, minus the first and last number. # ><>, 25 (+3 for  -v) = 28 bytes Takes input from the stack with  -v and assumes stdin is empty, relying on it to provide a -1 value. :{:}+i*v :$v?=1l<+++:
;n<


# C# with LINQ, 42 bytes

a=>3*a.Sum()-(a.Length>0?a[0]+a.Last():0);


Requires the System.Linq namespace.

# C#, 84 bytes

a=>{int i=0,l=a.Length;var r=0d;for(;i<l;)r+=3*a[i++];return(l>0?r-a[0]-a[l-1]:0);};


Full program with test cases:

using System;

namespace SumOfNeighbours
{
class Program
{
static void Main(string[] args)
{
Func<double[],double>f= a=>{int i=0,l=a.Length;var r=0d;for(;i<l;)r+=3*a[i++];return(l>0?r-a[0]-a[l-1]:0);};

// test cases:
double[] x = new double[]{1,2,3,4,5};
Console.WriteLine(f(x));    // 39

x = new double[] {};
Console.WriteLine(f(x));    // 0

x = new double[] {1};
Console.WriteLine(f(x));    // 1

x = new double[] {1,4};
Console.WriteLine(f(x));    // 10 (1+4 + 4+1)

x = new double[] {1,4,7};
Console.WriteLine(f(x));    // 28

x = new double[] {1,4,7,10};
Console.WriteLine(f(x));    // 55

x = new double[] {-1,-2,-3};
Console.WriteLine(f(x));    // -14

x = new double[] {0.1,0.2,0.3};
Console.WriteLine(f(x));    // 1.4

x = new double[] {1,-20,300,-4000,50000,-600000,7000000};
Console.WriteLine(f(x));    // 12338842
}
}
}


## Racket 48 bytes

(if(null? l)0(-(* 3(apply + l))(car l)(last l)))


Ungolfed:

(define (f lst)
(if (null? lst)
0
(- (* 3 (apply + lst))
(first lst)
(last lst))))


Testing:

(f '())
(f '(1))
(f '(1 4))
(f '(1 4 7))
(f '(1 4 7 10))
(f '(-1 -2 -3))
(f '(0.1 0.2 0.3))
(f '(1 -20 300 -4000 50000 -600000 7000000))


Output:

0
1
10
28
55
-14
1.4000000000000001
12338842


# Gloo, 12 Bytes

Turns out a feature of Gloo isn't working as intended so I had to do this a painful way.

__]:]:]:,,[+


Explanation:

__                   // duplicate the input list twice
]:]:]:             // flatten each list, and rotate stack left
,,           // pop the last 2 numbers
// (which are the first and last element of the list)
[+         // wrap all items in a list and sum.


# Elixir, 93 bytes

&if (length(&1)>0),do: Enum.reduce(&1,fn(n,r)->n+r end)*3-Enum.at(&1,0)-List.last(&1),else: 0


Anonymous function using the capture operator.

Full program with test cases:

s=&if (length(&1)>0),do: Enum.reduce(&1,fn(n,r)->n+r end)*3-Enum.at(&1,0)-List.last(&1),else: 0
# test cases:
IO.puts s.([])            # 0
IO.puts s.([1])           # 1
IO.puts s.([1,4])         # 10 (1+4 + 4+1)
IO.puts s.([1,4,7])       # 28
IO.puts s.([1,4,7,10])    # 55
IO.puts s.([-1,-2,-3])    # -14
IO.puts s.([0.1,0.2,0.3]) # 1.4
IO.puts s.([1,-20,300,-4000,50000,-600000,7000000]) # 12338842


Try it online on ElixirPlayground !

# TI-Basic, 17 bytes

Simply three times the sum of the list, minus the first and last element.

3sum(Ans)-Ans(1)-Ans(dim(Ans)-1

• I believe consensus on meta says that Ans is an invalid form of input. Oct 15, 2016 at 4:19
• You can use it with a list, don't worry. Pass it like {1,3,5,7,2,6}:prgmNEIGHBOR Oct 15, 2016 at 13:03
• That's still Ans as input. Oct 15, 2016 at 19:54
• Does it look like I care? That's the standard way of passing input in TI-Basic. Oct 16, 2016 at 0:41
• as much as I agree with you, that doesn't make the answer any more valid. Oct 16, 2016 at 3:51

# Ruby, 41 bytes

->a{a.reduce(0,:+)*3-(a[0]?a[0]+a[-1]:0)}


Full program with test cases:

f=->a{a.reduce(0,:+)*3-(a[0]?a[0]+a[-1]:0)}

#test cases
a=[]
puts f.call(a)  # 0

a=[1]
puts f.call(a)  # 1

a=[1,4]
puts f.call(a)  # 10

a=[1,4,7]
puts f.call(a)  # 28

a=[1,4,7,10]
puts f.call(a)  # 55

a=[-1,-2,-3]
puts f.call(a)  # -14

a=[0.1,0.2,0.3]
puts f.call(a)  # 1.4

a=[1,-20,300,-4000,50000,-600000,7000000]
puts f.call(a)  # 12338842


My first attempt in Ruby.

• As of Ruby 2.4.0 there's Array#sum. I haven't yet installed the preview release though to test whether this can simply be dropped into this solution. Oct 14, 2016 at 15:32

# Javascript, 46 bytes

a.reduce((t,c,i)=>t+(a[i-1]|0)+c+(a[i+1]|0),0)


const a = [1,2,3,4,5];
console.log(a.reduce((t,c,i)=>t+(a[i-1]|0)+c+(a[i+1]|0),0));

Thanks @rlemon for the extra 2 bytes

## Pyke, 9 5 bytes

3*tOs


Try it here!

# Java 8, 60

d->d.length>0?Arrays.stream(d).sum()*3-d[0]-d[d.length-1]:0;


# C++, 67 bytes

#import<valarray>
int f(std::valarray<int>v){return 3*v.sum()-v[0]-v[v.size()-1];}


Usage:

#include <iostream>
int main() {
std::cout << f({1,2,1});
return 0;
}