23
\$\begingroup\$

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

Leaderboard

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>

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

37 Answers 37

8
\$\begingroup\$

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
| improve this answer | |
\$\endgroup\$
  • 3
    \$\begingroup\$ Very clever use of 7B there to get [1 1 1] \$\endgroup\$ – Suever Oct 14 '16 at 12:51
  • \$\begingroup\$ I don't know MATL, but I wonder: for a list [a,b,c,...], how do you get a+b but avoid getting a? \$\endgroup\$ – Christian Sievers Oct 14 '16 at 13:24
  • 1
    \$\begingroup\$ @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 \$\endgroup\$ – Luis Mendo Oct 14 '16 at 13:40
19
\$\begingroup\$

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
| improve this answer | |
\$\endgroup\$
14
\$\begingroup\$

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

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ I also found a neat 25-byte solution. \$\endgroup\$ – Lynn Oct 14 '16 at 16:32
  • 1
    \$\begingroup\$ Actually, what if a is the empty list (first test case)? a[0] will throw an IndexError, no? \$\endgroup\$ – Lynn Oct 14 '16 at 17:37
6
\$\begingroup\$

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
| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ Does €Ð¦¨O work :)? \$\endgroup\$ – Adnan Oct 14 '16 at 18:31
  • \$\begingroup\$ @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 \$\endgroup\$ – Emigna Oct 14 '16 at 22:24
4
\$\begingroup\$

JavaScript (ES6), 40 33 bytes

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

Returns NaN when given an empty list.

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ 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] \$\endgroup\$ – Grax32 Oct 15 '16 at 1:20
  • \$\begingroup\$ @Grax - Nice! However, it would not be falsy anymore for the empty array. \$\endgroup\$ – Arnauld Oct 15 '16 at 1:30
  • \$\begingroup\$ There's always something isn't there? \$\endgroup\$ – Grax32 Oct 15 '16 at 1:44
  • \$\begingroup\$ @Grax - No. The first test case is an empty array. \$\endgroup\$ – Arnauld Oct 15 '16 at 11:32
4
\$\begingroup\$

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

| improve this answer | |
\$\endgroup\$
3
\$\begingroup\$

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

| improve this answer | |
\$\endgroup\$
3
\$\begingroup\$

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];}
| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ I don't think adding extra inputs denoting the first and last elements of the array is in the spirit of the challenge. \$\endgroup\$ – Geobits Oct 14 '16 at 12:50
  • \$\begingroup\$ @Geobits I change it..... \$\endgroup\$ – Numberknot Oct 14 '16 at 13:00
  • \$\begingroup\$ Cool. You can golf it some more by using float instead of double :) \$\endgroup\$ – Geobits Oct 14 '16 at 13:04
  • \$\begingroup\$ Can i use it instead.... Double has 2x the precision of float. \$\endgroup\$ – Numberknot Oct 14 '16 at 13:09
  • 1
    \$\begingroup\$ why not ints? \$\endgroup\$ – sidgate Oct 14 '16 at 19:32
3
\$\begingroup\$

Mathematica, 34 32 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.

| improve this answer | |
\$\endgroup\$
  • 2
    \$\begingroup\$ +1 for teaching me Check \$\endgroup\$ – Greg Martin Oct 14 '16 at 16:07
2
\$\begingroup\$

MATLAB, 31 28 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.

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ You can probably shorten to 's' \$\endgroup\$ – Luis Mendo Oct 14 '16 at 13:00
  • 1
    \$\begingroup\$ @LuisMendo Oh good call! MATLAB allows it but Octave doesn't (of course) \$\endgroup\$ – Suever Oct 14 '16 at 13:02
2
\$\begingroup\$

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
| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ So many 5 byters, where's the 4? ḊṖ+ḤS, Ṗ++ḊS, +Ḋ+ṖS, +Ṗ+ḊS, ... \$\endgroup\$ – Jonathan Allan Oct 14 '16 at 17:10
2
\$\begingroup\$

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
| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ Nice. And happy 6k+! \$\endgroup\$ – Conor O'Brien Oct 15 '16 at 4:20
2
\$\begingroup\$

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
({}{}<>)
| improve this answer | |
\$\endgroup\$
2
\$\begingroup\$

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
| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ ParameterArgumentValidationErrorEmptyStringNotAllowed ಠ_ಠ What an exception! \$\endgroup\$ – Kade Oct 14 '16 at 20:02
2
\$\begingroup\$

Ruby, 35 33 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.

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ You don't need parentheses around :+. \$\endgroup\$ – m-chrzan Oct 14 '16 at 18:59
  • \$\begingroup\$ [*(a*3)[1..-2]] does .to_a in two fewer bytes. \$\endgroup\$ – histocrat Oct 14 '16 at 19:19
  • \$\begingroup\$ You might want to give Ruby 2.4.0 a go. It comes with Array#sum. \$\endgroup\$ – Martin Ender Oct 14 '16 at 20:05
2
\$\begingroup\$

Perl 6, 25 bytes

{.sum*3-.[0]-(.[*-1]//0)}    # generates warning
{+$_&&.sum*3-.[0]-.[*-1]}

Expanded:

# bare block lambda with implicit parameter 「$_」
{
  +$_        # 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;
}
| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

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.

| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

><>, 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<
| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

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

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

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.
| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

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 !

| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

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

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.

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ 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. \$\endgroup\$ – Martin Ender Oct 14 '16 at 15:32
1
\$\begingroup\$

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

| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

Pyke, 9 5 bytes

3*tOs

Try it here!

| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

Java 8, 60

d->d.length>0?Arrays.stream(d).sum()*3-d[0]-d[d.length-1]:0;
| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

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;
}
| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

Haskell, 25 bytes

From fastest

sum.sequence[(0-).head,(3*).sum,(0-).last]$[1..5]

via prettiest

sum.sequence[sum.init,sum,sum.tail]$[1..5]

down to ugliest but shortest

let y x=sum$init x++x++tail x in y[1..5]     
--  1234567890123456789012345
| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

Batch, 67 bytes

@set/as=l=0
@for %%n in (%*)do @set/as+=l=%%n
@cmd/cset/as*3-%1-l

If there are no parameters, the last command turns into 0 * 3 - -0.

| improve this answer | |
\$\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.