电源插座


23

这是NCPC 2005的问题。罗伊有一间只有一个电源插座的公寓,但他有一堆配电盘。使用他拥有的配电盘计算他可以拥有的最大插座数量。每个配电盘的插座数作为输入给出。

事实证明,如果条的出口数量分别是

p1,p2,,pn

then the number of outlets is

1n+ipi
,

or

1+p11+p21++pn1
.

The input to the program or function is a non-empty series of positive integers.

Examples

2 3 4
> 7
2 4 6
> 10
1 1 1 1 1 1 1 1
> 1
100 1000 10000
> 11098

17
And I thought you weren't supposed to chain power strips ...
Joey

As far as I can tell my Retina answer is the only answer using unary input. You might want to have a look at the comment discussion there: codegolf.stackexchange.com/questions/71047/electrical-outlet/… ... If you think that the unary solution is too much of a hack that's not in the spirit of the challenge, I'm happy for you to specify that the input should be in decimal (and will then fix my answer accordingly).
Martin Ender

7
Because electricity is so expensive, your code should be as short as possible as to avoid using more energy
cat

1
@cat Time to dig out the old hamster driven turing machine and mechanical computers.
Pharap

1
@immibis sure, but the output would be treated as the information contained in the byte stream not as what happens to by rendered by your terminal.
Martin Ender

Answers:



29

Retina, 3 bytes

 1

The trailing linefeed is significant.

Input is a space-separated list of unary numbers.

Try it online!

Explanation

The code simply removes all spaces as well as the 1 after them from the string. Here is why that works:

Addition in unary is simple: just concatenate the numbers which is the same as removing the delimiters. Decrementing by 1 is also simple: just remove a 1 from each number. We want 1 more than the sum of the decremented inputs though, so we simply only remove the 1s we find after spaces, thereby decrementing all but the first input.


1
I'm wondering if input in unary should be allowed.
John Dvorak

@JanDvorak it is by default, unless the challenge explicitly specifies decimal input. (See the link in the answer.) Doesn't matter though, Jelly is winning anyway.
Martin Ender

@MartinBüttner There's sample data both in this question and the original assignment. Don't you think (unless otherwise stated) that it should be a necessary (though not sufficient) criterion for passing, that the code works with the verbatim sample data?
nitro2k01

1
@nitro2k01 No (in that case most answers would probably be invalid). Unless the challenge explicitly specifies one particular input format we normally assume that lists can be taken in any native list format. Same goes for number formats (at least unary and taking integers as byte values are allowed by consensus unless the challenge forbids them). It's pretty much impossible to include sample data in every thinkable native input format in the challenge.
Martin Ender

@MartinBüttner Imo, that's not the problem that the recommendation is addressing. What still speaks against this is that (unless I'm mistaken) this doesn't work because unary is a supported or native number format in Retina but it happens to work when you process the string as string data. It's a hack. It's even a clever hack, but I'm still not convinced that's it's according to the rules. If space-separated unary numbers was a native format in Retina in the same way that a list of bytes is a native format in bf, I would agree the recommendation applies and I would have a different opinion.
nitro2k01

9

Hexagony, 18 14 bytes

.?<_(@'")>{+.!

Unfolded:

  . ? <
 _ ( @ '
" ) > { +
 . ! . .
  . . .

Try it online!

I don't think side-length 2 is possible, but there must might be a more efficient side-length 3 solution that this.

This is the usual "decrement all, sum, increment" approach, but I'll have to add diagrams later to show how exactly it works in Hexagony.


7

Python, 24 bytes

lambda*n:1-len(n)+sum(n)

Try it online


1
This assumes that the function is first assigned, then applied to the input from other variable.
juandesant

1
@juandesant ...which is perfectly fine. It's a function literal, which is a valid form of submission.
FlipTack


7

Haskell, 17 15 bytes

foldl1$(+).pred

Usage example: ( foldl1$(+).pred ) [2,4,6] -> 10.

Old version, different approach, 17 bytes: succ.sum.map pred.


6

J, 6 bytes

+/+1-#

Sum plus one minus length. Parenthesize and apply it, like so:

   (+/+1-#) 2 3 4
7

6

Labyrinth, 9 bytes

"?;)!@
+(

Try it online!

The usual primer:

  • Labyrinth is 2D and stack-based. Stacks have an infinite number of zeroes on the bottom.
  • When the instruction pointer reaches a junction, it checks the top of the stack to determine where to turn next. Negative is left, zero is forward and positive is right.

Here we start at the top left ", a no-op, heading rightward. Next is ?, which reads an int from STDIN (throwing away chars it can't parse as an integer, e.g. spaces). Now we have two cases:

If the input is positive, we turn right, performing:

(            decrement top of stack
+            add top two stack elements
             [continue loop]

If the input is zero (which occurs at EOF), we go straight ahead, performing:

;            pop zero from EOF
)            increment top of stack
!            output top of stack as number
@            halt program

5

Pyth,5个字节

hstMQ

增量(sum(map(减量,输入)))


5

ES6, 25 bytes

a=>a.map(n=>r+=n-1,r=1)|r

4
我要发表的文章是:“ reduce赢得比赛的罕见情况之一”……也是25岁l=>l.reduce((a,b)=>a+b-1)
edc65 '16

@ edc65是的,(,b)价格昂贵,但我也喜欢该版本。
尼尔


4

05AB1E, 4 bytes

Code:

E<O>

Explanation:

E     # Evaluates input
 <    # Decrement on list
  O   # Compute the total sum
   >  # Increment on the sum
      # Implicit: output top of the stack

Takes input like an array (e.g. [3, 4, 5]).


非常适合打高尔夫球
法拉普

4

Starry, 26 24 bytes

, + '`      + ** `, +'*.

Expects newline-separated integers. Try it online!

Thanks to @MartinBüttner for -2 bytes.

,           Read line as integer
 + '        Dupe and jump to label 1 if nonzero
`           Set label 0
      +     Push 1
 *          Sub
*           Add
 `          Set label 1
,           Read line as integer
 + '        Dupe and jump to label 0 if nonzero
*           Add
.           Output as integer

The loop is unrolled so that the first number is not decremented, negating the need to increment. Pushing numbers is expensive in Starry...


I count only 20 bytes.
Addison Crump

1
@VoteToClose Did you count the leading spaces? (I'm assuming you're talking about the 26 byte)
Sp3000

4

Bash + GNU实用程序,16

如果有N配电盘,则N-1在逗号分隔的输入列表中应有分隔符。我们需要做的就是用替换分隔符- 1 +并对其进行算术评估:

sed s/,/-1+/g|bc

或使用相同的技巧:

Pure Bash(无外部实用程序),19

echo $[${1//,/-1+}]

3

APL (NARS 2000), 13 10 bytes

{1+(+/⍵)-⍴∊⍵}

Edit: Down to 10 with Lynn's (better) approach.

{1++/1-⍨⍵}


3

gs2, 5 bytes

(CP437-encoded.)

W&Φd'

That’s read-nums dec m1 sum inc.


3

CJam,7个字节

q~:(:+)

在这里测试。

与Lynn的方法相同(全部递减,求和,递增)。这也适用于8个字节(可能更有趣):

q~{(+}*

这会在列表上折叠“递减,添加”。这样,减量仅适用于除第一个元素以外的所有元素,因此我们无需单独处理增量。


3

C,60 59 55字节

x;main(s){while(~scanf("%i",&x))s+=x-1;printf("%i",s);}


3

Seriously, 7 bytes

,;l@Σ-u

Try it online!

Explanation:

,;l@Σ-u
,        push input
 ;       dupe
  l@     push length (n), swap
    Σ-u  push sum, subtract n, add one

2

Perl 6,20个字节

put 1+sum --«@*ARGS

(您可以使用<<代替«

用法:

$ perl6 -e 'put 1+sum --«@*ARGS' 100 1000 10000
11098

«是Perl运算符?
user253751 '02

@immibis实际上,它是几个Perl 6运算符的一部分,其中@arraya »+« @arrayb ++«@array @array».method @array»++ « a 'space separated' list of words »一些称为元运算符,因为它们与其他运算符结合在一起。(Perl 5当前没有这些运算符。)
布拉德·吉尔伯特b2gills '16

2

Perl 5 23+2=25 or 19+2=21

Requires -ap flags:

map{$.+=($_-1)}@F;$_=$.

Saved in a file and run as

perl -ap file.pl

EDIT: Another answer, smaller (19+2) but basically copied from dev-null answer:

$.+=$_-1for@F;$_=$.

2

F#, 25 bytes

Seq.fold(fun s n->s+n-1)1

This is a function that takes in an array/list/sequence of integers and returns the required result.

How it works:

Seq.fold allows you to apply a function to every element of a sequence while carrying some state around while it does so. The result of the function as applied to the first element will give the state that will be put into the function for the second element, and so forth. For example, to sum up the list [1; 3; 4; 10], you'd write it like this:

Seq.fold (fun sum element -> sum + element) 0 [1; 3; 4; 10]
         (       function to apply        ) ^ (sequence to process)
                                     ( initial state )

Which would be applied like so:

// First, initial state  + first element
0 + 1  = 1
// Then, previous state + next element until the end of the sequence
1 + 3  = 4
4 + 4  = 8
8 + 10 = 18

With the last state being the return value of Seq.fold.


2

𝔼𝕊𝕄𝕚𝕟, 5 chars / 7 bytes

ï⒭+‡_

Try it here (Firefox only).

Uses a custom encoding with 10-bit chars (thx @Dennis!). Run encode('ï⒭+‡_') in the JS console to get encoded form, and decode(/*ENCODED TEXT HERE*/) to decode encoded form.

Explanation

Translates to Javascript ES6 as:

i=>i.reduce(($,_)=>$+--_)

有趣的编码。
lirtosiast 2016年

It works quite nicely, too.
Mama Fun Roll

2

莫宁顿湾Mornington Crescent)1909年1873年 1839字节

Take Northern Line to Stockwell
Take Victoria Line to Seven Sisters
Take Victoria Line to Victoria
Take Circle Line to Victoria
Take Circle Line to Bank
Take Circle Line to Hammersmith
Take Circle Line to Cannon Street
Take Circle Line to Hammersmith
Take Circle Line to Cannon Street
Take Circle Line to Bank
Take Circle Line to Hammersmith
Take District Line to Upminster
Take District Line to Hammersmith
Take District Line to Upminster
Take District Line to Becontree
Take District Line to Upminster
Take District Line to Becontree
Take District Line to Upminster
Take District Line to Becontree
Take District Line to Turnham Green
Take District Line to Hammersmith
Take District Line to Turnham Green
Take District Line to Notting Hill Gate
Take Circle Line to Notting Hill Gate
Take Circle Line to Bank
Take Circle Line to Embankment
Take Northern Line to Stockwell
Take Northern Line to Embankment
Take Circle Line to Temple
Take Circle Line to Hammersmith
Take District Line to Upminster
Take District Line to Becontree
Take District Line to Upminster
Take District Line to Becontree
Take District Line to Upminster
Take District Line to Becontree
Take District Line to Blackfriars
Take Circle Line to Embankment
Take District Line to Parsons Green
Take District Line to Bank
Take Circle Line to Hammersmith
Take District Line to Upminster
Take District Line to Becontree
Take District Line to Upminster
Take District Line to Becontree
Take District Line to Upminster
Take District Line to Becontree
Take District Line to Parsons Green
Take District Line to Embankment
Take Circle Line to Blackfriars
Take Circle Line to Bank
Take Northern Line to Angel
Take Northern Line to Bank
Take Circle Line to Bank
Take District Line to Upminster
Take District Line to Bank
Take Circle Line to Bank
Take Northern Line to Mornington Crescent

在线尝试!


“所有指示中有90%涉及乘坐区线。” 这是因为District是所有算术工作站所在的位置。但是,在TIO上,它似乎不适用于任何示例
NieDzejkob,

1873 bytes by using shorter line names where possible
NieDzejkob

TIO's interpreter has a bug and doesn't implement Turnham Green
pppery

Nice catch. I've sent a PR that fixes it upstream.
NieDzejkob

1

Python 3, 79 bytes

import sys
print(sum(map(lambda x: int(x)-1, sys.stdin.readline().split()))+1)

看起来您正在将换行符计为两个字节。也许用分号代替它来保存一个字节。也可以删除一些空格。
达菲

1

Ruby, 30 bytes

$*.inject(1){|s,v|s+=v.to_i-1}

Simple enough - starting from 1, add up the supplied numbers, each -1 (command line args are in $*). Shame inject is such a long word.


1

PowerShell, 19 bytes

$args-join'-1+'|iex

Note that 1 + p1-1 + p2-1 + ... + pn-1 is equivalent to p1-1 + p2-1 + ... + pn.

Takes input as separate command-line arguments with $args. We -join those together with a -1+ delimiter to create a string, such as 2-1+3-1+4. The string is then piped to Invoke-Expression (similar to eval), and outputs the result.


1

Perl,21 + 2 = 23字节

$a+=$_-1for@F;say++$a

需要-a-E

$ perl -aE'$a+=$_-1for@F;say++$a'<<<'2 3 4'
7

You can use the -a flag to get @F variable with already split elements, and replace -n with -p so you dont'need say, reducing it to 21+2: $a+=$_-1for@F;$_=++$a
ChatterOne

使用-p代替代替say是相同的,因为$_=无论如何我都需要使用。
andlrc

@ChatterOne -a is a good idea!
andlrc

1

Brainfuck,15个字节

假设:一旦所有输入都用尽,操作员将返回0,并且没有带0插头的延长线。同样,IO必须使用字节值而不是ASCII字符代码。

+>,[-[-<+>],]<.

说明:这使用2个寄存器。“值”累加器寄存器代表可以插入的设备数量,“电流线”寄存器用于跟踪当前线的值。首先,将现有插座的值增加1。然后,对于每根延长线,由于已拔出插头,因此将从值中减去一个,然后将值增加插头数。

大多数在线解释器都不以原始字节输入模式运行。要在线测试,请使用以下代码:

+>,[->-[>+<-----]>---[-<+>]<[-<->]<[-<+>],]<.

我可以在某个地方测试程序吗?
帕尔GD

Thanks, corrected those mistakes. I'm not aware of any online interpreters that operate in byte mode. I can throw together an implementation that subtracts '0' from the inputs that will run on any online interpreter.
伊桑

如果要测试代码,请在此处运行:copy.sh/brainfuck请勿在数字值之间放置空格。不幸的是,由于它以ASCII模式运行,因此该演示代码仅适用于单个数字值。但是,15字节版本将在<= 255的值上正常工作。运行它后,查看内存转储以查看最终值。
伊桑

One day BF will have proper standards for expected IO and we'll just be able to say 'using standard 3' instead of e.g. 'input and output are all asciii terminated by null char'.
法拉普
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.