Summe der Nachbarn


22

Dies sollte eine relativ einfache Herausforderung sein.

Generieren Sie für ein Array von Zahlen ein Array, in dem für jedes Element alle benachbarten Elemente zu sich selbst hinzugefügt werden, und geben Sie die Summe dieses Arrays zurück.

Hier ist die Transformation, die auf dem Eingabearray stattfindet [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

Testfälle

[]            => 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

Bestenliste



Müssen wir Gleitkommazahlen oder nur ganze Zahlen unterstützen?
corvus_192

@ corvus_192 Die Testfälle enthalten Nicht-Ganzzahlen.
Geobits

@Geobits Ich habe das nicht bemerkt, ich werde meine Antwort bearbeiten.
corvus_192

2
Sie sollten dies als nächstes mit zweidimensionalen Arrays tun.
Bradley Uffner

Antworten:


8

MATL , 5 Bytes

7BZ+s

Probieren Sie es online!

Erläuterung

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

3
Sehr kluger Gebrauch von 7Bdort zu bekommen[1 1 1]
Suever

Ich kenne MATL nicht, aber ich frage mich: [a,b,c,...]Wie bekommst du eine Liste , a+baber vermeidest sie a?
Christian Sievers

1
@Christian Die Addition erfolgt mittels einer Faltungsoperation. Es würde die Teilergebnisse erzeugen, auf die Sie sich beziehen, aber es gibt eine Version der Faltung, die diese vermeidet, da sie ein Ausgabearray mit nur so vielen Einträgen wie der Eingabe erzeugt. Dies wird auch in Suevers Antwort verwendet
Luis Mendo

19

Python, 25 Bytes

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

Um zu sehen, warum dies funktioniert, drehen Sie die Erweiterung im OP um 45 Grad:

             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

14

Python 2, 28 Bytes

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

Nur 3 mal die Summe und minus eines von jedem Endelement


Ich fand auch eine ordentliche 25-Byte-Lösung .
Lynn

1
Was aist eigentlich, wenn die Liste leer ist (erster Testfall)? a[0]wird ein werfen IndexError, nein?
Lynn

6

05AB1E , 11 5 Bytes

6 Bytes gespart dank Adnan .

€Ð¦¨O

Probieren Sie es online!

Erläuterung

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

Funktioniert das €Ð¦¨O:)?
Adnan

@Adnan: Genial! Ich habe versucht, mir einen Weg zu überlegen, wie ich es mit 3 * machen könnte, aber ich habe noch nie darüber nachgedacht €Ð, obwohl ich es €Dzuvor verwendet habe : P
Emigna

4

JavaScript (ES6), 40 33 Bytes

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

Gibt zurück, NaNwenn eine leere Liste angegeben wird.


Sie können 2 weitere Zeichen abhacken, wenn Sie die Multiplikation wie v=>eval(v.join`*3+`+"*2")-v[0]
folgt

@Grax - Schön! Für das leere Array wäre es jedoch nicht mehr falsch.
Arnauld

Es gibt immer etwas, was nicht da ist?
Grax32

@Grax - Nein. Der erste Testfall ist ein leeres Array.
Arnauld

4

R 75 70 52 34 33 31 Bytes

Summiere mal drei und subtrahiere das erste und das letzte Element

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

Bearbeiten: 3 zusätzliche Bytes dank @rturnbull gespeichert


3

Scala, 47 Bytes

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

Stellt eine 0 voran und hängt sie an, verwendet dann ein Schiebefenster der Größe 3, um die Nachbarn zu summieren, und berechnet die Gesamtsumme


3

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

Ich denke nicht, dass das Hinzufügen zusätzlicher Eingänge, die das erste und das letzte Element des Arrays kennzeichnen, der Herausforderung entspricht.
Geobits

@ Geobits Ich ändere es .....
Numberknot

Cool. Sie können es mehr Golf mit floatanstelle von double:)
Geobits

Kann ich es stattdessen benutzen? Double hat die doppelte Präzision des Schwimmers.
Numberknot

1
warum nicht ints?
Sidgate

3

Mathematica, 34 32 29 Bytes

Lass dich inspirieren Lynns saubere Python-Antwort ...

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

oder

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

oder

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

Leider ist dieser Ansatz in Mathematica nicht so praktisch wie in Python, da es keine kurze und sichere Möglichkeit gibt, das erste und letzte Element einer Liste zu verwerfen, die möglicherweise leer ist.


2
+1 für mich zu lehrenCheck
Greg Martin

2

MATLAB, 31 28 26 Bytes

3 Bytes gespart dank @Luis

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

Dadurch wird eine anonyme Funktion mit dem Namen anserstellt, die wie folgt aufgerufen werden kann:ans([1, 2, 3, 4, 5])

Um eine Online-Demo (die Octave verwendet) zur Verfügung zu stellen, musste ich 'same'statt 's'als letzte Eingabe verwendenconv

Online Demo

Erläuterung

Wir führen Convolution ( conv) mit einem 1 x 3Kernel aller Einsen durch (erstellt durch Erstellen eines Arrays 1:3und anschließender Vergleich mit Null >0) und behalten die Größe des Originals bei, indem 'same'wir die dritte Eingabe als oder in MATLAB angeben, auf die wir diese einfach kürzen können 's'. Wir wenden dann die Summe auf das Ergebnis an.


Sie können wahrscheinlich verkürzen's'
Luis Mendo

1
@ LuisMendo Oh guten Anruf! MATLAB erlaubt es, aber Octave nicht (natürlich)
Suever


2

J 9 Bytes

+/@,}.,}:

Denn [1, 2, 3, 4, 5]die Nachbarn sind

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

Dann schauen Sie sich die Diagonalen der Summen an

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

Wir brauchen also nur die Summe der Eingaben zu finden, wobei der Kopf und der Schwanz entfernt sind.

Verwendung

   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

Erläuterung

+/@,}.,}:  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

Nett. Und fröhliche 6k +!
Conor O'Brien

2

Brain-Flak , 68 Bytes

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

Probieren Sie es online!

Erläuterung:

#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
({}{}<>)

2

PowerShell v2 +, 40 Byte

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

Summiert ähnlich wie bei den anderen Antworten die Liste, multipliziert mit 3, subtrahiert die Endelemente. Bei Leereingaben wird ein spektakulärer Fehler ausgegeben und dann ausgespuckt. 0Da STDERR jedoch standardmäßig ignoriert wird, ist dies in Ordnung.

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ಠ_ಠ Was für eine Ausnahme!
Kade

2

Ruby, 35 33 31 Bytes

Inspiriert von Lynns Lösung:

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

Das to_aSegment ist dazu da, das leere Array zu handhaben.

EDIT: Danke an m-chrzan und histocrat.


Sie brauchen keine runden Klammern :+.
m-chrzan

[*(a*3)[1..-2]]macht .to_ain zwei weniger Bytes.
Histokrat

Vielleicht möchten Sie Ruby 2.4.0 ausprobieren. Es kommt mit Array#sum.
Martin Ender

2

Perl 6 , 25 Bytes

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

Erweitert:

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

Prüfung:

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

1

PHP, 39 Bytes

<?=3*array_sum($a=$argv)-$a[1]-end($a);

Laufen Sie wie folgt:

echo '<?=3*array_sum($a=$argv)-$a[1]-end($a);' | php -- 1 -20 300 -4000 50000 -600000 7000000 2>/dev/null;echo

Erläuterung

Die Herausforderung kann auf das 3-fache Hinzufügen jeder Zahl mit Ausnahme der ersten und der letzten Zahl (zweimal hinzugefügt) reduziert werden. Deshalb gebe ich 3 mal die Summe abzüglich der ersten und letzten Zahl zurück.


1

> <> , 25 (+3 für -v ) = 28 Bytes

Nimmt eine Eingabe von dem Stapel mit  -vund übernimmt stdin leer ist, die sich auf einen schaffen -1Wert.

:{:}+i*v
:$v?=1l<+++:
;n<

1

C # mit LINQ, 42 Bytes

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

Benötigt den System.LinqNamespace.


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

Volles Programm mit Testfällen:

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

1

Schläger 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))))

Testen:

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

Ausgabe:

0
1
10
28
55
-14
1.4000000000000001
12338842

1

Gloo , 12 Bytes

Es stellte sich heraus, dass eine Funktion von Gloo nicht wie beabsichtigt funktioniert, also musste ich dies auf schmerzhafte Weise tun.

__]:]:]:,,[+

Erläuterung:

__                   // 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.

1

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 !


1

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.
Conor O'Brien

You can use it with a list, don't worry. Pass it like {1,3,5,7,2,6}:prgmNEIGHBOR
Timtech

That's still Ans as input.
Conor O'Brien

Does it look like I care? That's the standard way of passing input in TI-Basic.
Timtech

as much as I agree with you, that doesn't make the answer any more valid.
Conor O'Brien

1

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.
Martin Ender

1

Javascript, 46 bytes

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

Thanks @rlemon for the extra 2 bytes



1

Java 8, 60

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

1

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

1

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

1

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.

Durch die Nutzung unserer Website bestätigen Sie, dass Sie unsere Cookie-Richtlinie und Datenschutzrichtlinie gelesen und verstanden haben.
Licensed under cc by-sa 3.0 with attribution required.