Electrical outlet

This is a problem from NCPC 2005. Roy has an apartment with only one single electrical outlet, but he has a bunch of power strips. Compute the maximum number of outlets he can have using the power strips he has. The number of outlets per power strip is given as input.

It turns out that if the number of outlets of the strips respectively are

p1, p2, ..., pn,

then the number of outlets is

1 - n + Σ pi ,

or

1 + p1-1 + p2-1 + ... + pn-1 .

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
``````
-
And I thought you weren't supposed to chain power strips ... – Joey Feb 4 at 20:00
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 Feb 5 at 13:47
@PålGD The tied Jelly answer was posted earlier anyway. – Martin Ender Feb 5 at 14:21
Because electricity is so expensive, your code should be as short as possible as to avoid using more energy – cat Feb 6 at 0:53
@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 Feb 6 at 9:04

Jelly, 3 bytes

``````’S‘
``````

Decrement (all), sum, increment. Try it here.

-

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 `1`s we find after spaces, thereby decrementing all but the first input.

-
+1 for aesthetics – Insane Feb 5 at 3:39
I'm wondering if input in unary should be allowed. – Jan Dvorak Feb 5 at 11:39
@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 Feb 5 at 12:15
@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 Feb 5 at 12:52
@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 Feb 5 at 12:56

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.

-

Mathematica, 9 bytes

``````Tr[#-1]+1&
``````
-

``````foldl1\$(+).pred
``````

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

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

-

Python, 24 bytes

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

Try it online

-
This assumes that the function is first assigned, then applied to the input from other variable. – juandesant Feb 5 at 10:42

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

Pyth, 5 bytes

``````hstMQ
``````

increment(sum(map(decrement, input)))

-

J, 6 bytes

``````+/+1-#
``````

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

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

ES6, 25 bytes

``````a=>a.map(n=>r+=n-1,r=1)|r
``````
-
I was going to post: "One of the rare cases when reduce wins the game" ... and it's 25 too `l=>l.reduce((a,b)=>a+b-1)`. – edc65 Feb 4 at 14:21
@edc65 Yeah, the `(,b)` is costly, but I like that version too. – Neil Feb 4 at 15:46

MATL, 3 bytes

``````qsQ
``````

Try it online.

Explanation

``````qsQ
q      thread decrement over the input array
s    sum
Q   increment
``````
-

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]`).

-
Very elegant for a golfing lang – Pharap Feb 6 at 8:45
@Pharap Thank you :) – Adnan Feb 6 at 8:47

Starry, 26 24 bytes

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

Expects newline-separated integers. Try it online!

Thanks to @MartinBüttner for -2 bytes.

``````,           Read line as integer
`           Set label 0
+     Push 1
*          Sub
`          Set label 1
.           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. – VTCAKAVSMoACE Feb 4 at 21:11
@VoteToClose Did you count the leading spaces? (I'm assuming you're talking about the 26 byte) – Sp3000 Feb 4 at 21:33

APL (NARS 2000), 13 10 bytes

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

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

`{1++/1-⍨⍵}`

-

gs2, 5 bytes

(CP437-encoded.)

``````W&Φd'
``````

That’s `read-nums dec m1 sum inc`.

-

CJam, 7 bytes

``````q~:(:+)
``````

Test it here.

Same approach as Lynn's (decrement all, sum, increment). This also works for 8 bytes (and is maybe a bit more interesting):

``````q~{(+}*
``````

This folds "decrement, add" over the list. By doing that, the decrement is only applied to all elements except the first, such that we don't need to take care of the increment separately.

-

C, 6059 55 bytes

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

Perl 6, 14 bytes

``````{1+[+] --«@_}
``````

usage

``````my &f = {1+[+] --«@_}

say f([2,3,4]) # 7
say f([2,4,6]) # 10
say f([1,1,1,1,1,1,1,1]) # 1
say f([100,1000,10000]) # 11098
``````
-
Wow, how awesome – OverCoder Feb 4 at 22:32
I fully intended to edit my answer to the very same thing ( see the html comment) – Brad Gilbert b2gills Feb 5 at 4:36

Bash + GNU utilities, 16

If there are `N` power strips, then there should be `N-1` separators in the comma-separated input list. All we need to do is replace the separators with `- 1 +` and arithmetically evaluate:

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

Or using the same trick:

Pure Bash (no external utilities), 19

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

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

Perl 6, 20 bytes

``````put 1+sum --«@*ARGS
``````

( You can use `<<` instead of `«` )

Usage:

``````\$ perl6 -e 'put 1+sum --«@*ARGS' 100 1000 10000
11098
``````
-
« is a Perl operator? – immibis Feb 4 at 19:56
@immibis Actually it's part of several Perl 6 operators `@arraya »+« @arrayb` `++«@array` `@array».method` `@array»++` `« a 'space separated' list of words »` Several of those are what is known as Meta operators, in that they combine with other operators. ( Perl 5 doesn't have those operators currently. ) – Brad Gilbert b2gills Feb 4 at 21:37

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

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

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`.

-

𝔼𝕊𝕄𝕚𝕟, 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((\$,_)=>\$+--_)
``````
-
Interesting encoding. – lirtosiast Feb 4 at 22:56
It works quite nicely, too. – Mama Fun Roll Feb 5 at 2:19

Python 3, 79 bytes

``````import sys
``````
-
Looks like you're counting a newline as two bytes. Maybe replace it with a semi-colon to save a byte. A few spaces can be removed too. – Daffy Feb 6 at 3:06

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.

-

Perl, 21 + 2 = 23 bytes

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

Requires `-a` and `-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 Feb 4 at 16:02
Using `-p` instead of `say` is the same because I need to use `\$_=` anyway. – andlrc Feb 4 at 17:10
@ChatterOne `-a` is a good idea! – andlrc Feb 4 at 17:17

Brainfuck, 15 bytes

Assumption: The , operator returns 0 once all input has been exhausted, and there are no extension cords with 0 plugs. Also, the IO needs to be in byte values instead of ASCII character codes.

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

Explanation: This uses 2 registers. A "Value" accumulator register, representing the number of devices that can be plugged in, and a "current cord" register that keeps track of the value of the current cord. It starts off by incrementing the value by 1, for the existing outlet. Then, for each extension cord, it subtracts one from the value since a plug is being taken up, then increments the value by the number of plugs.

Most online interpreters don't operate in raw byte input mode. To test it online, use this code:

``````+>,[->-[>+<-----]>---[-<+>]<[-<->]<[-<+>],]<.
``````
-
Can I test the program somewhere? – Pål GD Feb 4 at 18:12
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. – Ethan Feb 4 at 18:21
If you want to test out the code, run it here: copy.sh/brainfuck Don't put spaces in between the numerical values. Unfortunately, since it's operating in ASCII mode, the demo code will only work on single digit values. However, the 15 byte version will work properly on an value <= 255. After you run it, view the memory dump to view the final value. – Ethan Feb 4 at 18:29
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'. – Pharap Feb 6 at 8:48

PARI/GP, 17 bytes

Completely straightforward.

``````v->vecsum(v)-#v+1
``````
-

Pylons, 6

Takes a list of space separated numbers on the command line then sums them all and subtracts the length.

``````1(i)-s
``````

How it works:

``````1   # Push 1 to the stack.
(   # Start a list.
i  # Get command line input.
) # End a list.
-   # Subtract the top two elements of the stack. In the case where one of the elements is
# a list, it does matrix subtraction.
s   # Sum the stack.
# Print the stack implicitly.
``````
-