邻居总数


22

这应该是一个相当简单的挑战。

对于数字数组,生成一个数组,其中对于每个元素,所有相邻元素都添加到自身,然后返回该数组的总和。

这是在输入数组上发生的转换 [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

测试用例

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

排行榜



我们需要支持浮点数还是仅支持整数?
corvus_192

@ corvus_192测试用例包括非整数。
Geobits,2013年

@Geobits我没有注意到,我将编辑答案。
corvus_192

2
接下来,您应该使用二维数组来执行此操作。
布拉德利·乌夫纳

Answers:


8

MATL,5个字节

7BZ+s

在线尝试!

说明

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
非常聪明地使用7B那里[1 1 1]
-Suever

我不知道MATL,但我想知道:对于清单[a,b,c,...],您如何获得a+b却避免获得a
Christian Sievers

1
@Christian加法是通过卷积运算完成的。它会产生您引用的部分结果,但是有一个避免使用它们的卷积版本,因为它会产生一个输出数组,该数组只包含与输入相同的条目。这也适用于Suever的答案
路易斯Mendo

19

Python,25个字节

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

要了解为什么这样做,将OP中的扩展旋转45度:

             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个字节

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

每个端点元素的总和减3倍


我还找到了一个整洁的25字节解决方案
林恩

1
实际上,如果a空列表是什么(第一个测试用例)呢?a[0]会抛出一个IndexError,不是吗?
林恩

6

05AB1E11 5字节

感谢Adnan,节省了6个字节

€Ð¦¨O

在线尝试!

说明

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

难道€Ð¦¨O工作:)?
阿德南

@Adnan:太棒了!我试图想出一种使用3 *的方法,但是€Ð即使我以前从未使用€D过它,也从未考虑过:P
Emigna

4

JavaScript(ES6),40 33字节

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

NaN给定一个空列表时返回。


如果像这样将乘法移动到v=>eval(v.join`*3+`+"*2")-v[0]
联接中,

@Grax-太好了!但是,对于空数组不再是虚假的。
Arnauld

总有东西不存在吗?
Grax32

@Grax-否。第一个测试用例是一个空数组。
Arnauld

4

R,75 70 52 34 33 31字节

乘以三,然后减去第一个和最后一个元素

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

编辑:感谢@rturnbull,节省了3个额外的字节


3

Scala,47个字节

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

前置并附加一个0,然后使用大小为3的滑动窗口对邻居求和,并计算总和


3

Java 7,72字节

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

我认为挑战精神不在于添加额外的输入来表示数组的第一个元素和最后一个元素。
Geobits

@Geobits我改变了.....
Numberknot

凉。你可以打高尔夫球是一些利用float,而不是double:)
Geobits

我可以改用它吗?... Double的浮点数精度是其两倍。
Numberknot

1
为什么不int呢?
sidgate

3

Mathematica,34 32 29字节

汲取Lynn简洁的Python答案 ...

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

要么

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

要么

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

不幸的是,这种方法在Mathematica中不如在Python中那样方便,因为没有一种简短安全的方法可以丢弃可能为空的列表的第一个和最后一个元素。


2
+1教我Check
Greg Martin

2

MATLAB,31 28 26字节

@Luis节省了3个字节

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

这将创建一个名为 ans,可以这样调用:ans([1, 2, 3, 4, 5])

为了提供在线演示(使用Octave),我不得不使用'same'代替's'作为最后的输入conv

在线演示

说明

我们conv使用1 x 3全为1的内核(通过创建一个数组1:3,然后与零进行比较)执行卷积(),>0并通过将第三个输入指定为来保持原始大小,'same'在MATLAB中,我们可以简单地将其缩短为's'。然后,我们将总和应用于结果。


您可能会缩短为's'
Luis Mendo

1
@LuisMendo哦,好电话!MATLAB允许,但Octave不允许(当然)
Suever


2

J,9个字节

+/@,}.,}:

对于[1, 2, 3, 4, 5],邻居是

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

然后沿着总和的对角线看

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

因此,我们只需要查找除去头部和除去尾部的输入总和。

用法

   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

说明

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

真好 祝6k +开心!
科纳·奥布莱恩

2

Brain-Flak,68位元组

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

在线尝试!

说明:

#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个字节

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

与其他答案类似,对列表求和,乘以3,然后减去结尾元素。对于空输入,Barfs出现一个严重的错误,然后吐出0,但是由于默认情况下STDERR被忽略,所以可以。

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ಠ_ಠ真是个例外!
卡德

2

Ruby,35 33 31字节

受到Lynn解决方案的启发:

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

to_a段在那里处理空数组。

编辑:感谢m-chrzan和histocrat。


您不需要括号:+
m-chrzan

[*(a*3)[1..-2]]确实.to_a在少两个字节。
历史学家

您可能想尝试一下Ruby 2.4.0。它带有Array#sum
Martin Ender

2

Perl 6,25个字节

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

展开:

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

测试:

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字节

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

像这样运行:

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

说明

可以将挑战减少为每个数字加3次,第一个和最后一个数字除外(两次加法)。因此,我返回总和的3倍减去第一个和最后一个数字。


1

> <>,25(对于+3 -v)= 28字节

从堆栈中获取输入, -v并假设stdin为空,并依靠它提供一个-1值。

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

1

具有LINQ的C#,42个字节

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

需要System.Linq名称空间。


C#,84个字节

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

完整的测试用例程序:

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

拍子48个字节

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

取消高尔夫:

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

测试:

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

输出:

0
1
10
28
55
-14
1.4000000000000001
12338842

1

Gloo,12个字节

事实证明,Gloo的功能无法正常工作,因此我不得不以痛苦的方式进行操作。

__]:]:]:,,[+

说明:

__                   // 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字节

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

使用捕获运算符的匿名函数。

完整的测试用例程序:

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

ElixirPlayground上在线尝试!


1

TI基本(17字节)

仅是列表总和的三倍,减去第一个和最后一个元素。

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

我认为对meta的共识Ans是无效的输入形式。
科纳·奥布莱恩

您可以将其与列表一起使用,不用担心。像{1,3,5,7,2,6}:prgmNEIGHBOR
蒂姆泰克

仍然Ans作为输入。
科纳·奥布莱恩

看起来像我在乎吗?这是在TI-Basic中传递输入的标准方法。
Timtech '16

尽管我同意你的看法,但这并不能使答案更加有效。
科纳·奥布赖恩

1

Ruby,41个字节

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

完整的测试用例程序:

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

我第一次尝试使用Ruby。


从Ruby 2.4.0开始,存在Array#sum。我尚未安装预览版本,以测试是否可以将其简单地放入此解决方案中。
Martin Ender



1

Java 8、60

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

1

C ++,67个字节

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

用法:

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

1

Haskell,25个字节

从最快

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

通过最漂亮的

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

到最丑但最短

let y x=sum$init x++x++tail x in y[1..5]     
--  1234567890123456789012345

1

批处理,67字节

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

如果没有参数,则最后一条命令变为0 * 3 - -0

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.