答:
Racket 147 bytes

```<code>(let p((l(map char->integer(string->list s))))(if(= 1(length l))(car l)(p
(for/list((i(range 1(length l))))(-(list-ref l(- i 1))(list-ref l i))))))
</code>```

Ungolfed:

```<code>(define (f s)
  (let loop ((lst (map char->integer (string->list s))))
    (if (= 1 (length lst))
        (first lst)
        (loop (for/list ((i (range 1 (length lst))))
                (- (list-ref lst (sub1 i))
                   (list-ref lst i))
                )))))
</code>```

Testing:

```<code>(f "AFG")
(f "BACEDF")
(f "cows")
(f "helloworld")
(f "abcdef")
(f "aaaaaa")
(f "ghfie")
(f "CODEGOLF")
</code>```

Output:

```<code>-4
-9
8
-905
0
0
-20
-185
</code>```

Body:
Racket 147 bytes

(let p((l(map char->integer(string->list s))))(if(= 1(length l))(car l)(p
(for/list((i(range 1(length l))))(-(list-ref l(- i 1))(list-ref l i))))))

Ungolfed:

(define (f s)
  (let loop ((lst (map char->integer (string->list s))))
    (if (= 1 (length lst))
        (first lst)
        (loop (for/list ((i (range 1 (length lst))))
                (- (list-ref lst (sub1 i))
                   (list-ref lst i))
                )))))

Testing:

(f "AFG")
(f "BACEDF")
(f "cows")
(f "helloworld")
(f "abcdef")
(f "aaaaaa")
(f "ghfie")
(f "CODEGOLF")

Output:

-4
-9
8
-905
0
0
-20
-185


问:
Given a string, Return its Cumulative Delta
Related

Explanation

Given a string such as DCBA, convert it to ASCII ordinals, such as 68 67 66 65. Then, take the differences between each value, eg 67 - 68 = -1, 66 - 67 = -1... giving -1 -1 -1 Now as long as there is more than 1 left over value, repeat getting the differences.

For a 3 letter string, your pathway should be similar to

```<code>A   F   G
65  70  71
-5  -1
-4
</code>```

And for a 5 letter string...

```<code>B   A   C   E   D   F
66  65  67  69  68  70
1   -2  -2  1   -2
3   0   -3  3
3   3   -6
0   9
-9
</code>```

The Challenge

Take a string input through any Standard IO Method, and output the value of the cumulative delta as described above.

Test Cases

```<code>input: cows
output: 8

input: helloworld
output: 905

input: aaaaaa
output: 0

input: abcdef
output: 0

input: ghfie
output: 20

input: CODEGOLF
output: 185
</code>```

Rules

Standard Loopholes Apply

The input will only consist of ASCII letters that are either all uppercase or all lowercase

Your code MUST work for both lower and upper case.

The input will contain at least 2 characters.

The output may be positive or negative, as long as its absolute value matches the absolute value of the cumulative delta.

This is marked as code-golf, as such, shortest answer in bytes wins!

答:
RProgN, 17 Bytes

```<code>►Sb]L1-1\1:[d}P
</code>```

Explination

```<code>►                   # Spaceless segment
 Sb                 # Convert the input to a stack, convert the stack of strings to a stack of ordinals.
   ]L               # Push a duplicate of that stack, pop it and push the length in its place
     1-             # Subtract 1 from the length.
       1\1          # Push a one, slide it under the top value, push another one, such that 1 LENGTH 1
          :  }      # For (i=1; i<=LENGTH; i+=1)
           [d       # Pop the iterator, pop the current stack, push the delta stack representing it.
              P     # Pop the top value of the stack, push it to the reg stack, and implicitly print.
</code>```

I used (A version of) this script to test the question itself. I thought I might as well share it.

Try It Online!

ContentLicense: CC BY-SA 3.0

Body:
RProgN, 17 Bytes

►Sb]L1-1\1:[d}P

Explination

►                   # Spaceless segment
 Sb                 # Convert the input to a stack, convert the stack of strings to a stack of ordinals.
   ]L               # Push a duplicate of that stack, pop it and push the length in its place
     1-             # Subtract 1 from the length.
       1\1          # Push a one, slide it under the top value, push another one, such that 1 LENGTH 1
          :  }      # For (i=1; i<=LENGTH; i+=1)
           [d       # Pop the iterator, pop the current stack, push the delta stack representing it.
              P     # Pop the top value of the stack, push it to the reg stack, and implicitly print.

I used (A version of) this script to test the question itself. I thought I might as well share it.

Try It Online!


答:
J, 15 bytes

```<code><:@#2&(-/\)3&u:
</code>```

Usage

```<code>   f =: <:@#2&(-/\)3&u:
   f 'cows'
8
   f 'helloworld'
_905
   f 'aaaaaa'
0
   f 'abcdef'
0
   f 'ghfie'
_20
   f 'CODEGOLF'
_185
</code>```

Explanation

```<code><:@#2&(-/\)3&u:  Input: string S
           3&u:  Ordinal of each char
   #             Get the length of S
<:@                Decrement it
    2&(   )      Repeat len(s)-1 times on x = ordinal(S)
    2    \         For each pair of values
       -/            Reduce using subtraction
                   Return that as the next value of x
                 Return the final x as the result
</code>```

Title: Given a string, Return its Cumulative Delta

Body:
Related

Explanation

Given a string such as DCBA, convert it to ASCII ordinals, such as 68 67 66 65. Then, take the differences between each value, eg 67 - 68 = -1, 66 - 67 = -1... giving -1 -1 -1 Now as long as there is more than 1 left over value, repeat getting the differences.

For a 3 letter string, your pathway should be similar to

```<code>A   F   G
65  70  71
-5  -1
-4
</code>```

And for a 5 letter string...

```<code>B   A   C   E   D   F
66  65  67  69  68  70
1   -2  -2  1   -2
3   0   -3  3
3   3   -6
0   9
-9
</code>```

The Challenge

Take a string input through any Standard IO Method, and output the value of the cumulative delta as described above.

Test Cases

```<code>input: cows
output: 8

input: helloworld
output: 905

input: aaaaaa
output: 0

input: abcdef
output: 0

input: ghfie
output: 20

input: CODEGOLF
output: 185
</code>```

Rules

Standard Loopholes Apply

The input will only consist of ASCII letters that are either all uppercase or all lowercase

Your code MUST work for both lower and upper case.

The input will contain at least 2 characters.

The output may be positive or negative, as long as its absolute value matches the absolute value of the cumulative delta.

This is marked as code-golf, as such, shortest answer in bytes wins!

Body:
J, 15 bytes

<:@#2&(-/\)3&u:

Usage

   f =: <:@#2&(-/\)3&u:
   f 'cows'
8
   f 'helloworld'
_905
   f 'aaaaaa'
0
   f 'abcdef'
0
   f 'ghfie'
_20
   f 'CODEGOLF'
_185

Explanation

<:@#2&(-/\)3&u:  Input: string S
           3&u:  Ordinal of each char
   #             Get the length of S
<:@                Decrement it
    2&(   )      Repeat len(s)-1 times on x = ordinal(S)
    2    \         For each pair of values
       -/            Reduce using subtraction
                   Return that as the next value of x
                 Return the final x as the result


问:
World Time Conversion

World Time Conversion

Challenge:

Given an initial clock time in UTC and a list of countries: for each country in the list, output the local time it is in that country based on the initial time.  In cases where a country is big enough to have multiple local time zones (like the United States), you may output any valid local time for that country, provided you state which time zone you are using (i.e. for United States, EST for Eastern Standard Time).  You do not have to worry about daylight savings time.

Input:

The current time, in UTC, followed by a list of countries.  The format of the input time can be given in any way (12 or 24 hour, with or without seconds, etc), and the countries can all be on the same line or on new lines after the time, your choice.  You may also use any characters to delimit the countries (space, comma, etc.).  You may choose to take a list of country -> timezone in as input, in which case I would prefer a common list be used across all answers, found here.  This part can be excluded from your byte count.

Output:

The local time in each country from the input list.  Once again, you may use any characters or newline to delimit the times for each country so long as it is easy to tell one time from another.  However, unlike the input, the times must be output in a 12 hour format (so there must be an AM/PM indication).  Other than that, you may express the digits in the time in any format (i.e. leading 0's for hours that are single digits, with or without seconds/milliseconds) as long as the character that is used to separate hours and minutes is different than the character that is used to separate the different times.  I would prefer if a date was not included in the answer since this is a challenge dealing specifically with different times.

Examples:

Input 1:

```<code>12:00 AM [United States]
</code>```

Output 1:

```<code>7:00 PM EST (or any other time zone with the appropriate time)
</code>```

Input 2:

```<code>12:00 PM [United States, Italy, Russia]
</code>```

Output 2:

```<code>4:00 AM PST, 2:00 PM, 3:00 PM MSK
</code>```

Rules:

This is code-golf, so shortest code in bytes wins.  Standard loopholes are forbidden.

Common list of country -> timezone:

```<code>// Format:  <country>,<UTC offset>,<time-zone abbreviation>
// You may use any alternate format or any other UTC/abbreviation for a country for those that have more than one zone
France,1,CET
United States,-5,EST
Russia,3,MSK
United Kingdom,0,UTC
Australia,10,AEST
Canada,-5,EST
Kingdom of Denmark,1,CET
New Zealand,12,NZST
Brazil,-3,BRT
Mexico,-6,MDT
Indonesia,7,WIST
Kiribati,12,LINT
Chile,-3,CLT
Democratic Republic of the Congo,1,WAT
Ecuador,-5,ECT
Federated States of Micronesia,11,KOST
Kazakhstan,6,ALMT
Kingdom of the Netherlands,1,CET
Mongolia,8,ULAT
Papua New Guinea,10,AEST
Portugal,0,WET
South Africa,2,SAST
Spain,1,CET
Afghanistan,4.5,AFT
Albania,1,CET
Algeria,1,CET
Andorra,1,CET
Angola,1,WAT
Antigua and Barbuda,-4,AST
Argentina,-3,ART
Armenia,4
Austria,1,CET
Azerbaijan,4
Bahamas,-5,EST
Bahrain,3
Bangladesh,6,BDT
Barbados,-4
Belarus,3,FET
Belgium,1,CET
Belize,-6
Benin,1,WAT
Bhutan,6,BTT
Bolivia,-4
Bosnia and Herzegovina,1,CET
Botswana,2,CAT
Brunei,8
Bulgaria,2,EET
Burkina Faso,0,UTC
Burundi,2,CAT
Cambodia,7
Cameroon,1,WAT
Cape Verde,-1,CVT
Central African Republic,1,WAT
Chad,1,WAT
China,8,CST
Colombia,-5
Comoros,3,EAT
Republic of the Congo,1,WAT
Costa Rica,-6
Croatia,1,CET
Cuba,-5
Cyprus,2,EET
Czech Republic,1,CRT
Djibouti,3,EAT
Dominica,-4
Dominican Republic,-4
East Timor,9
Egypt,2,EET
El Salvador,-6
Equatorial Guinea,1,WAT
Eritrea,3,EAT
Estonia,2,EET
Ethiopia,3,EAT
Fiji,12
Finland,2,EET
Gabon,1,WAT
Gambia,0,GMT
Georgia,4
Germany,1,CET
Ghana,0,GMT
Greece,2,EET
Grenada,-4
Guatemala,-6
Guinea,0,GMT
Guinea-Bissau,0,GMT
Guyana,-4
Haiti,-5
Honduras,-6
Hong Kong,8,HKT
Hungary,1,CET
Iceland,0,GMT
India,5.5,IST
Iran,3.5,IRST
Iraq,3
Ireland,0,WET
Israel,2,IST
Italy,1,CET
Ivory Coast,0,GMT
Jamaica,-5
Japan,9,JST
Jordan,2
Kenya,3,EAT
North Korea,8.5,PYT
South Korea,9,KST
Kuwait,3,AST
Kosovo,1
Kyrgyzstan,6
Laos,7
Latvia,2,EET
Lebanon,2,EET
Lesotho,2
Liberia,0,GMT
Libya,2,EET
Liechtenstein,1,CET
Lithuania,2,EET
Luxembourg,1,CET
Macau China,8,CST
Macedonia,1,CET
Madagascar,3,EAT
Malawi,2,CAT
Malaysia,8,MYT
Maldives,5
Mali,0,GMT
Malta,1,CET
Marshall Islands,12
Mauritania,0,GMT
Mauritius,4,MUT
Moldova,2,EET
Monaco,1,CET
Montenegro,1,CET
Morocco,0,WET
Mozambique,2,CAT
Myanmar,6.5,MST
Namibia,1,WAT
Nauru,12
Nepal,5.75,NPT
Nicaragua,-6
Niger,1,WAT
Nigeria,1,WAT
Norway,1,CET
Oman,4
Pakistan,5,PKT
Palau,9
Panama,-5
Paraguay,-4
Peru,-5,PET
Philippines,8,PHT
Poland,1,CET
Qatar,3,AST
Romania,2,EET
Rwanda,2,CAT
Saint Kitts and Nevis,-4
Saint Lucia,-4
Saint Vincent and the Grenadines,-4
Samoa,13
San Marino,1,CET
São Tomé and Príncipe,0,GMT
Saudi Arabia,3,AST
Senegal,0,GMT
Serbia,1,CET
Seychelles,4,SCT
Sierra Leone,0,GMT
Singapore,8,SST
Slovakia,1,CET
Slovenia,1,CET
Solomon Islands,11
Somalia,3,EAT
South Sudan,3,EAT
Sri Lanka,5.5,SLST
Sudan,3,EAT
Suriname,-3
Swaziland,2
Sweden,1,CET
Switzerland,1,CET
Syria,2,EET
Taiwan,8
Tajikistan,5,
Tanzania,3,EAT
Thailand,7,THA
Togo,0,GMT
Tonga,13
Trinidad and Tobago,-4
Tunisia,1,CET
Turkey,2,EET
Turkmenistan,5
Tuvalu,12
Uganda,3,EAT
Ukraine,2,EET
United Arab Emirates,4
Uruguay,-3
Uzbekistan,5,UZT
Vanuatu,11,
Vatican City,1,CET
Venezuela,-4
Vietnam,7,ICT
Yemen,3
Zambia,2,CAT
Zimbabwe,2,CAT
</code>```

答:
bash (126 bytes)

```<code>w(){ cd /u*/sh*/z*
join -o2.2 <(egrep "$2" i*) <(cut -sf1,3 zone.*)|while read z
do TZ=$z date -d"UTC$1" +"%z %r";done|uniq;}
w 12:00PM "United States|Italy|Russia"
</code>```

uses GNU date and file:/usr/share/zoneinfo/{iso3166,zone}.tab

Title: World Time Conversion

Body:
bash (126 bytes)

w(){ cd /u*/sh*/z*
join -o2.2 <(egrep "$2" i*) <(cut -sf1,3 zone.*)|while read z
do TZ=$z date -d"UTC$1" +"%z %r";done|uniq;}
w 12:00PM "United States|Italy|Russia"

uses GNU date and file:/usr/share/zoneinfo/{iso3166,zone}.tab


问:
List of first n prime numbers most efficiently and in shortest code
Rules are simple:

First n primes (not primes below n), should be printed to standard output separated by newlines (primes should be generated within the code)

primes cannot be generated by an inbuilt function or through a library, i.e. use of a inbuilt or library function such as, prime = get_nth_prime(n), is_a_prime(number), or factorlist = list_all_factors(number) won't be very creative.

Scoring - Say, we define Score = f([number of chars in the code]), O(f(n)) being the complexity of your algorithm where n is the number of primes it finds. So for example, if you have a 300 char code with O(n^2) complexity, score is 300^2 = 90000, for 300 chars with O(n*ln(n)), score becomes 300*5.7 = 1711.13 (let's assume all logs to be natural logs for simplicity)

Use any existing programming language, lowest score wins

Edit: Problem has been changed from finding 'first 1000000 primes' to 'first n primes' because of a confusion about what 'n' in O(f(n)) is, n is the number of primes you find (finding primes is the problem here and so complexity of the problem depends on the number of primes found)

Note: to clarify some confusions on complexity, if 'n' is the number of primes you find and 'N' is the nth prime found, complexity in terms of n is and N are not equivalent i.e. O(f(n)) != O(f(N)) as , f(N) != constant * f(n) and N != constant * n, because we know that nth prime function is not linear, I though since we were finding 'n' primes complexity should be easily expressible in terms of 'n'.

As pointed out by Kibbee, you can visit this site to verify your solutions (here, is the old google docs list)

Please Include these in your solution -

what complexity your program has (include basic analysis if not trivial)

character length of code

the final calculated score

This is my first CodeGolf Question so, if there is a mistake or loophole in above rules please do point them out.

答:
Haskell (52²=2704)

```<code>52`take`Data.List.nubBy(((1<).).gcd)[2..]`forM_`print
</code>```

Body:
Haskell (52²=2704)

52`take`Data.List.nubBy(((1<).).gcd)[2..]`forM_`print


问:
EvenSt-ring C ode - g ol!f
An 'Even string' is any string where the parity of the ASCII values of the characters is always alternating. For example, the string EvenSt-ring$! is an even-string because the ASCII values of the characters are:

```<code>69 118 101 110 83 116 45 114 105 110 103 36 33
</code>```

And the parities of these numbers are:

```<code>Odd Even Odd Even Odd Even Odd Even Odd Even Odd Even Odd
</code>```

Which is alternating the whole way. However, a string like Hello world! is not an even string because the ASCII values are:

```<code>72 101 108 108 111 32 87 111 114 108 100 33
</code>```

And the parities are:

```<code>Even Odd Even Even Odd Even Odd Odd Even Even Even Odd
</code>```

Which is clearly not always alternating.

The challenge

You must write either a full program or a function that accepts a string for input and outputs a truthy value if the string is even, and a falsy value otherwise. You can take your input and output in any reasonable format, and you can assume that the input will only have printable ASCII (the 32-127 range). You do not have to handle empty input.

Examples

Here are some examples of even strings:

```<code>#define
EvenSt-ring$!
long
abcdABCD
3.141
~
0123456789
C ode - g ol!f
HatchingLobstersVexinglyPopulateJuvenileFoxglove
</code>```

And all of these examples are not even strings:

```<code>Hello World
PPCG
3.1415
babbage
Code-golf
Standard loopholes apply
Shortest answer in bytes wins
Happy golfing!
</code>```

You may also use this ungolfed solution to test any strings if you're curious about a certain test-case.

答:
Starry, 85 bytes

```<code> ,       +    *   ` , +               + * ' +  ' `       +    * +   + *   '     +  `.
</code>```

Try it online!

Note that since a Starry program has no way of telling when an input of arbitrary length ends, this program uses a trailing newline in the input to mark the end of the string. If you get a cryptic error message about and undefined method ord for nil:NilClass then the input is missing a trailing newline.

Explanation

The basic strategy that the program employs is it reads the characters one by one from input and if they are not a newline (character 10) it mods they ASCII value of the character by 2 and finds the difference between it and the previously read character. If the difference is zero the program terminates and prints 0 (falsey). Otherwise the program loops back and does the process over again. If the program reads a newline it terminates and prints 10 (truthy).

Annotated Program

```<code> ,               Push the first character
       +         Push 2
    *            Replace the first character and 2 with the first character mod 2
   `             Label 3 <--------------------------------------------------------\
 ,               Push the next the character                                      |
 +               Push a duplicate of it                                           |
               + Push 10                                                          |
 *               Replace the 10 and the duplicate with their difference           |
 '               Pop and if not zero (the read char is not 10) goto label 1 >-\   |
 +               Push a duplicate of the character which must be newline (10) |   |
  '              Pop and goto label 2 >---------------------------------------+-\ |
 `               Label 1 <----------------------------------------------------/ | |
       +         Push 2                                                         | |
    *            Replace the character and 2 with the character mod 2           | |
 +               Duplicate it ^                                                 | |
   +             Roll the top three items on the stack. The top goes to         | |
                   the bottom. The top three items are now                      | |
                   (from top to bottom) the current character, the previous     | |
                   character, the current character (all modded by 2).          | |
 *               Replace the current character and previous character           | |
                   with their difference                                        | |
   '             Pop if nonzero goto label 3 >----------------------------------+-/
     +           Push zero                                                      |
  `              Label 2 <------------------------------------------------------/
.                Print out the number on top of the stack
                    0 if we came by not following the goto label 3
                   10 if we came by going to label 2
</code>```

Title: EvenSt-ring C ode - g ol!f

Body:
Starry, 85 bytes

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

Try it online!

Note that since a Starry program has no way of telling when an input of arbitrary length ends, this program uses a trailing newline in the input to mark the end of the string. If you get a cryptic error message about and undefined method ord for nil:NilClass then the input is missing a trailing newline.

Explanation

The basic strategy that the program employs is it reads the characters one by one from input and if they are not a newline (character 10) it mods they ASCII value of the character by 2 and finds the difference between it and the previously read character. If the difference is zero the program terminates and prints 0 (falsey). Otherwise the program loops back and does the process over again. If the program reads a newline it terminates and prints 10 (truthy).

Annotated Program

 ,               Push the first character
       +         Push 2
    *            Replace the first character and 2 with the first character mod 2
   `             Label 3 <--------------------------------------------------------\
 ,               Push the next the character                                      |
 +               Push a duplicate of it                                           |
               + Push 10                                                          |
 *               Replace the 10 and the duplicate with their difference           |
 '               Pop and if not zero (the read char is not 10) goto label 1 >-\   |
 +               Push a duplicate of the character which must be newline (10) |   |
  '              Pop and goto label 2 >---------------------------------------+-\ |
 `               Label 1 <----------------------------------------------------/ | |
       +         Push 2                                                         | |
    *            Replace the character and 2 with the character mod 2           | |
 +               Duplicate it ^                                                 | |
   +             Roll the top three items on the stack. The top goes to         | |
                   the bottom. The top three items are now                      | |
                   (from top to bottom) the current character, the previous     | |
                   character, the current character (all modded by 2).          | |
 *               Replace the current character and previous character           | |
                   with their difference                                        | |
   '             Pop if nonzero goto label 3 >----------------------------------+-/
     +           Push zero                                                      |
  `              Label 2 <------------------------------------------------------/
.                Print out the number on top of the stack
                    0 if we came by not following the goto label 3
                   10 if we came by going to label 2


问:
2048-like array shift
Assume we want to shift an array like it is done in the 2048 game: if we have two equal consecutive elements in array, merge them into twice the value element.
Shift must return a new array, where every pair of consecutive equal elements is replaced with their sum, and pairs should not intersect.
Shifting is performed only once, so we don't need to merge resulting values again.
Notice that if we have 3 consecutive equal elements, we have to sum rightmost ones, so for example, [2, 2, 2] should become [2, 4], not [4, 2].

The task is to write shortest function which takes an array and returns a shifted array.

You may assume that all integers will be strictly positive.

Examples:

```<code>[] -> []
[2, 2, 4, 4] -> [4, 8]
[2, 2, 2, 4, 4, 8] -> [2, 4, 8, 8]
[2, 2, 2, 2] -> [4, 4]
[4, 4, 2, 8, 8, 2] -> [8, 2, 16, 2]
[1024, 1024, 512, 512, 256, 256] -> [2048, 1024, 512]
[3, 3, 3, 1, 1, 7, 5, 5, 5, 5] -> [3, 6, 2, 7, 10, 10]
</code>```

I am also very interested in solution using reduce :)

Title: 2048-like array shift

Body:
Perl6, 92 bytes

{my @b;loop ($_=@^a-1;$_>=0;--$_) {@b.unshift($_&&@a[$_]==@a[$_-1]??2*@a[$_--]!!@a[$_])};@b}


答:
Perl 6, 152 bytes, O(n log n log (n log n) log (log (n log n))) (?), 9594.79 points

According to this page, the bit complexity of finding all primes up to n is O(n log n log log n); the complexity above uses the fact that the nth prime is proportional to n log n.

```<code>my \N=+slurp;my \P=N*(N.log+N.log.log);my @a=1 xx P;for 2..P.sqrt ->$i {if @a[$i] {@a[$_*$i]=0 for $i..P/$i}};say $_[1] for (@a Z ^P).grep(*[0])[2..N+1]
</code>```

Title: List of first n prime numbers most efficiently and in shortest code

Body:
Rules are simple:

First n primes (not primes below n), should be printed to standard output separated by newlines (primes should be generated within the code)

primes cannot be generated by an inbuilt function or through a library, i.e. use of a inbuilt or library function such as, prime = get_nth_prime(n), is_a_prime(number), or factorlist = list_all_factors(number) won't be very creative.

Scoring - Say, we define Score = f([number of chars in the code]), O(f(n)) being the complexity of your algorithm where n is the number of primes it finds. So for example, if you have a 300 char code with O(n^2) complexity, score is 300^2 = 90000, for 300 chars with O(n*ln(n)), score becomes 300*5.7 = 1711.13 (let's assume all logs to be natural logs for simplicity)

Use any existing programming language, lowest score wins

Edit: Problem has been changed from finding 'first 1000000 primes' to 'first n primes' because of a confusion about what 'n' in O(f(n)) is, n is the number of primes you find (finding primes is the problem here and so complexity of the problem depends on the number of primes found)

Note: to clarify some confusions on complexity, if 'n' is the number of primes you find and 'N' is the nth prime found, complexity in terms of n is and N are not equivalent i.e. O(f(n)) != O(f(N)) as , f(N) != constant * f(n) and N != constant * n, because we know that nth prime function is not linear, I though since we were finding 'n' primes complexity should be easily expressible in terms of 'n'.

As pointed out by Kibbee, you can visit this site to verify your solutions (here, is the old google docs list)

Please Include these in your solution -

what complexity your program has (include basic analysis if not trivial)

character length of code

the final calculated score

This is my first CodeGolf Question so, if there is a mistake or loophole in above rules please do point them out.

Body:
Perl 6, 152 bytes, O(n log n log (n log n) log (log (n log n))) (?), 9594.79 points

According to this page, the bit complexity of finding all primes up to n is O(n log n log log n); the complexity above uses the fact that the nth prime is proportional to n log n.

my \N=+slurp;my \P=N*(N.log+N.log.log);my @a=1 xx P;for 2..P.sqrt ->$i {if @a[$i] {@a[$_*$i]=0 for $i..P/$i}};say $_[1] for (@a Z ^P).grep(*[0])[2..N+1]


答:
JavaScript (ES6), 116 bytes

Good that the input is more than 1 char so I can use s.length for both Arrays and Strings!

Snippet referenced from Neil's answer on another question :P

d=k=>/\d/.test(k)?k:k.charCodeAt(0);r=x=>(a=[...x],a.pop(),a.map((c,i)=>d(c)-d(x[i+1])));f=s=>s.length-1?f(r(s)):s[0]```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input oninput=o.textContent=this.value&&f(this.value)><pre id=o></code>```

Body:
JavaScript (ES6), 116 bytes

Good that the input is more than 1 char so I can use s.length for both Arrays and Strings!

Snippet referenced from Neil's answer on another question :P

d=k=>/\d/.test(k)?k:k.charCodeAt(0);r=x=>(a=[...x],a.pop(),a.map((c,i)=>d(c)-d(x[i+1])));f=s=>s.length-1?f(r(s)):s[0]

<input oninput=o.textContent=this.value&&f(this.value)><pre id=o>


答:
Haskell, <s>51</s> 47 bytes

```<code>g[x]=x
g x=g$zipWith(-)=<<tail$x
g.map fromEnum
</code>```

Usage example: g.map fromEnum $ "CODEGOLF"-> 185.

map fromEnum turns the string into a list of ascii values. If it has only a single element, return it, else build neighbor differences and check again.

Body:
Haskell, <s>51</s> 47 bytes

g[x]=x
g x=g$zipWith(-)=<<tail$x
g.map fromEnum

Usage example: g.map fromEnum $ "CODEGOLF"-> 185.

map fromEnum turns the string into a list of ascii values. If it has only a single element, return it, else build neighbor differences and check again.


答:
05AB1E, 7 bytes

```<code>ÇDgG¥}`
</code>```

Try it online!

Explanation

```<code>Ç        # convert to list of ascii codes
 DgG }   # length-1 times do:
    ¥    # take deltas
      `  # pop the single value left in the list and output
</code>```

Body:
05AB1E, 7 bytes

ÇDgG¥}`

Try it online!

Explanation

Ç        # convert to list of ascii codes
 DgG }   # length-1 times do:
    ¥    # take deltas
      `  # pop the single value left in the list and output


答:
Brain-Flak, 97 bytes

```<code>([][()]<>){<>([][()]){({}[()]<({}[({})]<>)><>)}{}{}<>([]){({}[()]<({}<>)<>>)}{}<>({}<>[()])}<>
</code>```

Try it online!

This is 97 bytes of code, plus 3 bytes for the -a flag, which enables ASCII input.

This would be a lot simpler if we didn't have to worry about the difference between characters sometimes being zero. Instead, we have to muck around with reversing the stack and pushing stack height several times.

Explanation:

```<code>Push the stack height onto the alternate stack
([][()]<>)

While this stack is non-empty:
{

    Move back
    <>

    Push the height of the stack minus one
    ([][()])

    While true
    {

        Decrement the stack height counter
        ({}[()]

        Move the difference over to the other stack
        <({}[({})]<>)><>)

    }

    Pop the last value and the left-over counter
    {}{}

    Move on to the other stack
    <>

    Move everything back
    ([]){({}[()]<({}<>)<>>)}

    Pop the counter
    {}<>

    Move the step number minus one back
    ({}<>[()])

End
}

Move back one last time
<>
</code>```

Body:
Brain-Flak, 97 bytes

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

Try it online!

This is 97 bytes of code, plus 3 bytes for the -a flag, which enables ASCII input.

This would be a lot simpler if we didn't have to worry about the difference between characters sometimes being zero. Instead, we have to muck around with reversing the stack and pushing stack height several times.

Explanation:

Push the stack height onto the alternate stack
([][()]<>)

While this stack is non-empty:
{

    Move back
    <>

    Push the height of the stack minus one
    ([][()])

    While true
    {

        Decrement the stack height counter
        ({}[()]

        Move the difference over to the other stack
        <({}[({})]<>)><>)

    }

    Pop the last value and the left-over counter
    {}{}

    Move on to the other stack
    <>

    Move everything back
    ([]){({}[()]<({}<>)<>>)}

    Pop the counter
    {}<>

    Move the step number minus one back
    ({}<>[()])

End
}

Move back one last time
<>


答:
R, 58 bytes

```<code>x=rev(utf8ToInt(readline()));while(length(x)>1)x=diff(x);x
</code>```

diff() in R works differently than the difference defined in this challenge. Therfore we have reverse the vector (using rev) prior to taking the difference the first time.

Body:
R, 58 bytes

x=rev(utf8ToInt(readline()));while(length(x)>1)x=diff(x);x

diff() in R works differently than the difference defined in this challenge. Therfore we have reverse the vector (using rev) prior to taking the difference the first time.


问:
Randomized Pumpkin Patch
I was walking through a pumpkin patch the other day for a birthday party, and noticed the pumpkin vines making a nifty pattern, with whirls, loops, and offshoots. We're going to simulate that here with some ASCII art.

```<code>          (())
            \
   p--q      p-----q
  /    \    /       \
(())    b--d       (())
</code>```

Vine Construction Rules

There is only one main vine, composed solely of \ / - p q b d characters.

The vine only travels from left to right across the screen. In other words, suppose you were an ant starting at the left-most vine character. As you progress to the next adjacent character on the main vine, you must move one column to the right - never to the left.

When the vine changes direction, one of the p q b d characters are required to simulate a loop. The p joins vines traveling northeast to east, the q for east to southeast, the b from southeast to east, and the d from east to northeast. Note that the "loop" of the letter connects to the horizontal vine, and the "stem" of the letter connects to the diagonal.

The beginning of the vine must be one of p or b (your choice, doesn't have to be random), and starts horizontally. The end of the vine must be one of q or d (your choice, doesn't have to be random), and must end horizontally.

Note that loops can be placed immediately adjacent to other loops (e.g., pd is a valid substring of the vine), but that may make it more difficult to place the pumpkins later. You may want to always have one of - / \ immediately after a loop (as I did in my examples), but it's not required.

Pumpkin Rules

The pumpkins are composed solely of (()) (this exact string).

From the main vine, the pumpkins are attached by offshoots. These offshoots can only be attached to the p q b d loops, are precisely one \ or / in length, and attach to the pumpkin so the "end" of the offshoot is in the middle.

They can connect above or below the main vine.

The offshoots can connect going to the "left."

Only one pumpkin can attach per offshoot, and only one offshoot per loop.

Randomness

When traveling horizontally, the vine has a 50% chance of continuing horizontally, a 25% chance of turning northeast, and a 25% chance of turning southeast.

When traveling diagonally, the vine has a 90% chance of turning horizontal and a 10% chance of continuing diagonally.

There must be sufficient turns to support the input number of pumpkins, though more turns are allowed.

Once the vine is constructed, pumpkins can be randomly placed at any corner not already occupied by a pumpkin.

Pumpkins cannot overlap the vine or other pumpkins.

The Challenge

Given an input number, output a randomized pumpkin patch following the above rules. Executing the code multiple times with the same input should yield different results. All possible pumpkin patches for a given input number should have some (not necessarily equal) non-zero chance of occurring.

Input

A single integer n representing the number of pumpkins in the patch, in any convenient format. For brevity of code, you can assume the input is 0 < n < 256.

Output

The resulting pumpkin patch, either printed/displayed to the screen or returned as a string/string-array/etc.

Rules

This is code-golf so all the usual rules for golfing apply, and the shortest code (in bytes) wins.

Use our standard definition of "Random."

Either a full program or function are acceptable.

Standard loopholes are forbidden.

Leading and trailing whitespace / newlines are all completely optional.

Examples

For input n = 3, here are some VALID examples of a pumpkin patch following the above rules (separated by blank newlines).

```<code>          (())
            \
   p--q      p-----q
  /    \    /       \
(())    b--d       (())

(()) (())
  \   /
   b-q (())
      \ /
       b-q

p-----------------------q (())
                       / \ /
                     (()) b-q
                           /
                         (())
</code>```

Here are some INVALID examples for input n = 3, with explanations #.

```<code>    (()) (())
     /    /
p---q----q
 \
(())
# The vine continued horizontally after a loop was placed.

(()(())
  \ /
   p---q
        \
       (())
# The pumpkins are both overlapping and sprouting from the same loop.

p----------------q
 \      \         \
(())   (())      (())
# The pumpkin is attached to the middle of the vine, not at a loop.
</code>```

Title: Randomized Pumpkin Patch

Body:
Python 2, 819 bytes

Takes n as input

Always places pumkpins on the 'outside' of corners (randomly left/right)

While the vine is constructed, pumpkins are added, and when enough pumpkins are there, the vine stops.

r=lambda:__import__('random').random()
s=1
v=[s]*4
U=[-9]
D=[-9]
i=input()
while len(U)+len(D)<i+2:s=[[0,1][r()<.9],[[0,2][r()<.5],1][r()<.5],[2,1][r()<.9]][s];exec['',[['','U+=[len(v)]'][U[-1]<len(v)-7],'',['','D+=[len(v)]'][D[-1]<len(v)-7]][v[-1]-s+1]][r()<.8];v+=[s]*[1,2][v[-1]!=s]
v+=[1]*5
m=M=s=0
for i in v:s+=i-1;m=[m,s][m>s];M=[M,s][M<s]
R=[[' ']*(M-m+5)for x in v]
m=-m+2
R[2][m]='p'
for x in range(3,len(v)-3):X=v[x-1];R[x][m]='/d p-b q\\'[v[x]*3+X];m+=v[x]-1
R[-3][m]='q'
M=[len(a)-len(a.lstrip())for a in map(''.join,R)]
R=map(list,zip(*R))
B,L,a='-/U'
K="\\"*4
W="""exec("for p in "+a+"[1:]:x=M[p];b=r()<.5;exec('R[x"+B+"1][p'+['+1]=\\""+L+"\\"','-1]=\\""+K+"\\"'][b]);i=p-[0,3][b];l='(';exec('R[x"+B+"2][i]=l;i+=1;'*2+'l=\\")\\";')*2")"""
exec W+";B,a='+D';L,K=K,L;"+W
for x in R:print''.join(map(str,x))

Examples:

n=4

                (())
                 /
                p---q
 (())          /
   \       p--d
  p-q     /    \
     \   /    (())
      b-d
       \
      (())

n=20

                            (())
                              \
                            p--q
                           /    \
                          /      b--q
           (())     p----d      /    \
  (())       \     /          (())    b-q (())
    \         p---d                      \  \
  p--q       /     \                      b--q
      \     /     (())                   /    \                        (())                                           (())
       b---d                           (())    b-q                       \                                             /
        \                                         \          (())         p-q                                         p---q
       (())                                        \           \         /   \                                       /
                                                    b-----------q     p-d     b-q                            (())p--d
                                                                 \   /       /   \                            / /    \
                                                                  b-d      (())   b-q   (())  (())   p-q     p-d    (())
                                                                   /                 \   /      \   /   \   /
                                                                 (())                 b-q        p-d     b-d
                                                                                \ \      /         \
                                                                                (())b----d         (())
                                                                                /
                                                                                (())


问:
List of primes under a million
This is my first code golf question, and a very simple one at that, so I apologise in advance if I may have broken any community guidelines.

The task is to print out, in ascending order, all of the prime numbers less than a million. The output format should be one number per line of output.

The aim, as with most code golf submissions, is to minimise code size. Optimising for runtime is also a bonus, but is a secondary objective.

答:
MATL, 5 bytes

```<code>1e6Zq
</code>```

Explanation:

```<code>1e6   % push 10000 to stack
   Zq % primes up to top-of-stack number
</code>```

Title: List of primes under a million

Body:
MATL, 5 bytes

1e6Zq

Explanation:

1e6   % push 10000 to stack
   Zq % primes up to top-of-stack number


问:
Division of not so little numbers
Write a program or function that takes in positive integers a, b and c, and prints or returns a/b to c decimal places, using the operations +-*/% [add, subtract, multiply, divide, modulate] on the positive integers: you can use all that your language allows, but not on floating point numbers. The range of a,b,c would be the range allowed for unsigned integers in your language.
The number result will be truncated to the last digit to print (so no round).

This means that if your language does not have an integer type (only float), you can participate by using these float numbers as positive integers only.
The clue of this exercise it would be to write the function that find the
digits in a float point division, using only the operation +-*/%  on
[unsigned] integers.

Examples

print(1,2,1) would print 0.5

print(1,2,2) would print 0.50

print(13,7,27) would print 1.857142857142857142857142857

print(2,3,1) would print 0.6

print(4,5,7) would print 0.8000000

print(4,5,1) would print 0.8

print(9999,23,1) would print 434.7

print(12345613,2321,89) would print if your Language has 32 bit unsigned 5319.09220163722533390779836277466609220163722533390779836277466609220163722533390779836277466

The shortest code in bytes wins. I'm sorry if this appear not clear... I don't know languages too, not remember words well...
It is better to have one link to Ideone.com or some other place for easily try the answer especially for to test some input different from proposed.

答:
C, 67 bytes

h(a,b,i){int j=!i;for(;printf(j++?"%u":"%u.",a/b),i--;a=10*(a%b));}
```

Try it online!

Some previous version I think had a bug in read memory out of assigned to the program...Thanks to ceilingcat and for all...

Title: Division of not so little numbers

Body:
C, 67 bytes

h(a,b,i){int j=!i;for(;printf(j++?"%u":"%u.",a/b),i--;a=10*(a%b));}

<a href="https://tio.run/##lZLdcsIgEIXv8xRrZtKBuraEaG1Kaa/7DG0vSEwUrdEhSW80z24Rm9jfGWWAOTB8y@6BdDBN091uRhQmqOlGFxXMZU@LfGWIWBu7zsm833/0g9q/s9OVj@o6oagHA6FkyC6JChJKRbNbKl0Q6rkQsEBQkmFihxYefAbyn4oyMxVwWK9KXen3DOx@Ns0MFPUyyUz5AD4Vef5WlzPCqFjIMlWFBYMJBBMf4ULZkdA2M/@lsOc90DlJpGTb7aInOd0cr1vXFWTGqGrlTpqsqk0BTDQe7CvUkgl9HzLR72sKHtjWwTkJanSdymdbtTNItE51Gby6wM2xxj84zlhLOvmd/RcNkWMIsEedpALgDJQfUX4OGuEY@dihrTwR5RgdspyRTp6IDnGE4wPayTNQfkTPqTW2DXmE7nm@LE61ikfD0Y11iUc8xNvYefZr72ew7hN6zS6MAUIe8zgOPwA" rel="nofollow noreferrer" title="C (gcc) – Try It Online">Try it online!

Some previous version I think had a bug in read memory out of assigned to the program...Thanks to ceilingcat and for all...

ContentLicense: CC BY-SA 4.0


答:
Java 8, <s>100</s> <s>97</s> 92 bytes

o->{for(int i=1,n,j;i++<1e6;){for(n=i,j=2;j<n;n=n%j++<1?0:n);if(n>1)System.out.print(n);}}
```
<p>-3 bytes by thanks to <em>@Nevay</em>.<br />
-5 bytes by converting Java 7 to Java 8.</p>
<p>I know there are already a few other Java answers. I didn't knew which to choose to put the comment on with my golfed method, so I decided to post this separate answer. Not to mention it's slightly or a lot shorter than any of the other current Java answers so far.</p>
<p><strong>Explanation:</strong></p>
<p>Try it here.</p>
<pre class="lang-java prettyprint-override"><code>o->{                          // Method with empty unused parameter and no return-type
  for(int i=1,n,j;            //  Initialize some integers
      i++<1e6;){              //  Loop (1) from 2 through 1,000,000 (exclusive)
    for(n=i,j=2;              //   Set some integers
        j<n;                  //   Inner loop (2) from 2 through `n` (exclusive)
      n=                      //    Change `n` to:
        n%j++<1?              //     If `n` is divisible by `j`:
         0                    //      Change `n` to 0 (which means it isn't a prime)
        :                     //     Else:
         n                    //      Leave `n` unchanged
    );                        //   End of inner loop (2)
    if(n>1)                   //   If `n` is larger than 1, which means it's a prime:
      System.out.println(n);  //    Print `n` + new-line
  }                           //  End of loop (1)
}                             // End of method
</code>```

Title: List of primes under a million

Body:
This is my first code golf question, and a very simple one at that, so I apologise in advance if I may have broken any community guidelines.

The task is to print out, in ascending order, all of the prime numbers less than a million. The output format should be one number per line of output.

The aim, as with most code golf submissions, is to minimise code size. Optimising for runtime is also a bonus, but is a secondary objective.

Body:
Java 8, <s>100</s> <s>97</s> 92 bytes

o->{for(int i=1,n,j;i++<1e6;){for(n=i,j=2;j<n;n=n%j++<1?0:n);if(n>1)System.out.print(n);}}

-3 bytes by thanks to @Nevay.

-5 bytes by converting Java 7 to Java 8.

I know there are already a few other Java answers. I didn't knew which to choose to put the comment on with my golfed method, so I decided to post this separate answer. Not to mention it's slightly or a lot shorter than any of the other current Java answers so far.

Explanation:

Try it here.

o->{                          // Method with empty unused parameter and no return-type
  for(int i=1,n,j;            //  Initialize some integers
      i++<1e6;){              //  Loop (1) from 2 through 1,000,000 (exclusive)
    for(n=i,j=2;              //   Set some integers
        j<n;                  //   Inner loop (2) from 2 through `n` (exclusive)
      n=                      //    Change `n` to:
        n%j++<1?              //     If `n` is divisible by `j`:
         0                    //      Change `n` to 0 (which means it isn't a prime)
        :                     //     Else:
         n                    //      Leave `n` unchanged
    );                        //   End of inner loop (2)
    if(n>1)                   //   If `n` is larger than 1, which means it's a prime:
      System.out.println(n);  //    Print `n` + new-line
  }                           //  End of loop (1)
}                             // End of method


问:
Draw an asterisk triangle
Inspired by a task for Programming 101, here's a challenge that hopefully isn't too easy (or a duplicate).

Input:

A positive integer n >= 1.

Output:

n lines of asterisks, where every new line has one asterisk more than the line before, and starting with one asterisk in the first line.

Test case (n=5):

```<code>    *
    **
    ***
    ****
    *****
</code>```

This is code-golf, so shortest answer in bytes wins.

答:
Scala, <s>44</s> 30 bytes (<s>51</s> 45 without asterisk, 41 for hourglass)

With asterisk in code (30 bytes):

```<code>(i:Int)=>(i to(1,-1))map("*"*) //create a range from i to 1 and map each number to that number of asterisks
</code>```

Without asterisk (45 bytes):

```<code>(i:Int)=>(i to(1,-1))map(((41+1).toChar+"")*) //same as above, but without a literal asterisk
</code>```

Without asterisk and easy ways of calculating 42 (57 bytes):

```<code>(i:Int)=>(i to(1,-1))map(((math sqrt("7G"##)).toChar+"")*)
</code>```

## is the hashcode method, which returns 1764 for the string "7G", the square root of 1764 is 42, the ascii code for *

Hourglass:

```<code>(& :Int)=>((&to(1,-1))++(2 to&))map("*"*)

(& :Int)=>        //define an anonymus function with an int parameter called &
  (
    (& to (1,-1))   //a range from & to 1, counting by -1, aka downwards
    ++              //concat
    (2 to&)         //a range from 2 to &
  )
  map(              //map each number to
    "*" *             //the string "*" repeated x times
  )
</code>```

Title: Draw an asterisk triangle

Body:
Scala, <s>44</s> 30 bytes (<s>51</s> 45 without asterisk, 41 for hourglass)

With asterisk in code (30 bytes):

(i:Int)=>(i to(1,-1))map("*"*) //create a range from i to 1 and map each number to that number of asterisks

Without asterisk (45 bytes):

(i:Int)=>(i to(1,-1))map(((41+1).toChar+"")*) //same as above, but without a literal asterisk

Without asterisk and easy ways of calculating 42 (57 bytes):

(i:Int)=>(i to(1,-1))map(((math sqrt("7G"##)).toChar+"")*)

## is the hashcode method, which returns 1764 for the string "7G", the square root of 1764 is 42, the ascii code for *

Hourglass:

(& :Int)=>((&to(1,-1))++(2 to&))map("*"*)

(& :Int)=>        //define an anonymus function with an int parameter called &
  (
    (& to (1,-1))   //a range from & to 1, counting by -1, aka downwards
    ++              //concat
    (2 to&)         //a range from 2 to &
  )
  map(              //map each number to
    "*" *             //the string "*" repeated x times
  )


问:
(KevinC's) Triangular DeciDigits Sequence
Input:

A positive integer n which is 1 <= n <= 25000.

Output:

In this sequence we start with the decimal number 1/n.

Then we take the sum of digits up until the n'th digit after the comma (1-indexed); followed by the sum of digits up until the (n-1)'th, then (n-2)'th, etc. Continue until n is 1.

The output is the sum of all these combined.

For example:

```<code>n = 7
1/7 = 0.1428571428...
7th digit-sum = 1+4+2+8+5+7+1 = 28
6th digit-sum = 1+4+2+8+5+7 = 27
5th digit-sum = 1+4+2+8+5 = 20
4th digit-sum = 1+4+2+8 = 15
3rd digit-sum = 1+4+2 = 7
2nd digit-sum = 1+4 = 5
1st digit     = 1
Output = 28+27+20+15+7+5+1 = 103
</code>```

Challenge rules:

If the decimal of 1/n doesn't have n digits after the comma, the missing ones will be counted as 0 (i.e. 1/2 = 0.50 => (5+0) + (5) = 10).

You take the digits without rounding (i.e. the digits of 1/6 are 166666 and not 166667)

General rules:

Standard rules apply for your answer, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters, full programs. Your call.

Default Loopholes are forbidden.

If possible, please add a link with a test for your code.

Also, please add an explanation if necessary.

First 1 - 50 in the sequence:

```<code>0, 10, 18, 23, 10, 96, 103, 52, 45, 10, 270, 253, 402, 403, 630, 183, 660, 765, 819, 95, 975, 1034, 1221, 1500, 96, 1479, 1197, 1658, 1953, 1305, 1674, 321, 816, 2490, 2704, 4235, 2022, 3242, 2295, 268, 2944, 3787, 3874, 4097, 1980, 4380, 4968, 3424, 4854, 98
</code>```

Last 24990 - 25000 in the sequence:

```<code>1405098782, 1417995426, 1364392256, 1404501980, 1408005544, 1377273489, 1395684561, 1405849947, 1406216741, 1142066735, 99984
</code>```

答:
Java 8, <s>181</s> <s>169</s> <s>166</s> <s>153</s> 142 bytes

import java.math.*;n->{int m=n+2,r=0,i;for(;m>2;)for(i=m--;i-->2;r+=(BigDecimal.ONE.divide(new BigDecimal(n),n,3)+"").charAt(i)-48);return r;}
```
<p><strong>Explanation:</strong></p>
<p>Try it here.</p>
<pre class="lang-java prettyprint-override"><code>import java.math.*;   // Required import for BigDecimal

n->{                  // Method with integer as both parameter and return-type
  int m=n+2,          //  Copy of the input-integer plus 2
      r=0,            //  Result-integer, starting at 0
      i;              //  Index-integer
  for(;m>2;)          //  Loop (1) as long as `m` is larger than 2
    for(i=m--;        //   Set index `i` to `m`, and decrease `m` by one afterwards
        i-->2;        //   Inner loop (2) from `m` down to 2 (inclusive)
      r+=             //    Add to the result-sum:
         (BigDecimal.ONE.divide(
                      //     1 divided by,
           new BigDecimal(n),
                      //     the input
           n,3)       //     With the minimal required precision
          +"")        //     Convert this to a String
          .charAt(i)  //     Take the character of this String at index `i`
          -48         //     And convert it to a number
     );               //   End of inner loop (2)
                      //  End of loop (1) (implicit / single-line body)
  return r;           //  Return result
}                     // End of method
</code>```

Body:
Java 8, <s>181</s> <s>169</s> <s>166</s> <s>153</s> 142 bytes

import java.math.*;n->{int m=n+2,r=0,i;for(;m>2;)for(i=m--;i-->2;r+=(BigDecimal.ONE.divide(new BigDecimal(n),n,3)+"").charAt(i)-48);return r;}

Explanation:

Try it here.

import java.math.*;   // Required import for BigDecimal

n->{                  // Method with integer as both parameter and return-type
  int m=n+2,          //  Copy of the input-integer plus 2
      r=0,            //  Result-integer, starting at 0
      i;              //  Index-integer
  for(;m>2;)          //  Loop (1) as long as `m` is larger than 2
    for(i=m--;        //   Set index `i` to `m`, and decrease `m` by one afterwards
        i-->2;        //   Inner loop (2) from `m` down to 2 (inclusive)
      r+=             //    Add to the result-sum:
         (BigDecimal.ONE.divide(
                      //     1 divided by,
           new BigDecimal(n),
                      //     the input
           n,3)       //     With the minimal required precision
          +"")        //     Convert this to a String
          .charAt(i)  //     Take the character of this String at index `i`
          -48         //     And convert it to a number
     );               //   End of inner loop (2)
                      //  End of loop (1) (implicit / single-line body)
  return r;           //  Return result
}                     // End of method


答:
05AB1E, <s>12</s> 11 bytes

```<code>Di<ë°¹÷.pSO
</code>```

Try it online!
or a Test suite for the first 50 numbers.

Explanation

```<code>              # implicit input n
Di<           # if n == 1 then 0
   ë          # else
    °¹÷       # 10^n // n
       .p     # get prefixes
         SO   # sum digits
</code>```

A more efficient version for trying big numbers on TIO

The difference to the shorter version is that here we sum the product of the digits and the reversal of their 1-based index instead of summing digits in prefixes.

```<code>Di<ë°¹÷SDgLR*O
</code>```

Try it online!

Title: (KevinC's) Triangular DeciDigits Sequence

Body:
Input:

A positive integer n which is 1 <= n <= 25000.

Output:

In this sequence we start with the decimal number 1/n.

Then we take the sum of digits up until the n'th digit after the comma (1-indexed); followed by the sum of digits up until the (n-1)'th, then (n-2)'th, etc. Continue until n is 1.

The output is the sum of all these combined.

For example:

```<code>n = 7
1/7 = 0.1428571428...
7th digit-sum = 1+4+2+8+5+7+1 = 28
6th digit-sum = 1+4+2+8+5+7 = 27
5th digit-sum = 1+4+2+8+5 = 20
4th digit-sum = 1+4+2+8 = 15
3rd digit-sum = 1+4+2 = 7
2nd digit-sum = 1+4 = 5
1st digit     = 1
Output = 28+27+20+15+7+5+1 = 103
</code>```

Challenge rules:

If the decimal of 1/n doesn't have n digits after the comma, the missing ones will be counted as 0 (i.e. 1/2 = 0.50 => (5+0) + (5) = 10).

You take the digits without rounding (i.e. the digits of 1/6 are 166666 and not 166667)

General rules:

Standard rules apply for your answer, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters, full programs. Your call.

Default Loopholes are forbidden.

If possible, please add a link with a test for your code.

Also, please add an explanation if necessary.

First 1 - 50 in the sequence:

```<code>0, 10, 18, 23, 10, 96, 103, 52, 45, 10, 270, 253, 402, 403, 630, 183, 660, 765, 819, 95, 975, 1034, 1221, 1500, 96, 1479, 1197, 1658, 1953, 1305, 1674, 321, 816, 2490, 2704, 4235, 2022, 3242, 2295, 268, 2944, 3787, 3874, 4097, 1980, 4380, 4968, 3424, 4854, 98
</code>```

Last 24990 - 25000 in the sequence:

```<code>1405098782, 1417995426, 1364392256, 1404501980, 1408005544, 1377273489, 1395684561, 1405849947, 1406216741, 1142066735, 99984
</code>```

Body:
05AB1E, <s>12</s> 11 bytes

Di<ë°¹÷.pSO

Try it online!
or a Test suite for the first 50 numbers.

Explanation

              # implicit input n
Di<           # if n == 1 then 0
   ë          # else
    °¹÷       # 10^n // n
       .p     # get prefixes
         SO   # sum digits

A more efficient version for trying big numbers on TIO

The difference to the shorter version is that here we sum the product of the digits and the reversal of their 1-based index instead of summing digits in prefixes.

Di<ë°¹÷SDgLR*O

Try it online!


问:
Determine if a coin system is Canonical
The Cashier's Algorithm is an algorithm for making change in the minimal number of coins that works quite well for most currency systems.  However like most greedy algorithms it is not without its flaws.  If a currency system is set up just right (or just wrong) there are certain values in which the Cashier's Algorithm will fail to find the optimal change.

Take the following example:

We have 4¢, 3¢, and 1¢ coins.  We want to make 6¢.

The Cashier's Algorithm will first select as many of the largest coin (one 4¢ to start) and subtract and repeat.  This will result in one 4¢ coin and two 1¢ coins, for a total of 3 coins.

Unfortunately for the Algorithm there is a way to make 6¢ with only two coins (two 3¢ coins).

A system of change will be considered canonical iff for all integer values the Cashier's Algorithm will find the optimal number of coins.

Task

You task will be to take a system as a either an unordered container or sorted ordered container of integers representing coin values and output a truthy value if the system input is canonical and falsy otherwise.

Your program should work for all systems that can create any value.  (i.e. all systems will have a 1¢ coin)

This is code golf least bytes wins.

Test cases

This list is by no means exhaustive, your program should work for all valid input

```<code>1, 3, 4       -> 0
1, 5, 10, 25  -> 1
1, 6, 10, 25  -> 0
1, 2, 3       -> 1
1, 8, 17, 30  -> 0
1, 3, 8, 12   -> 0
1, 2, 8, 13   -> 0
1, 2, 4, 6, 8 -> 1
</code>```

答:
JavaScript (ES6), <s>144</s> <s>132</s> <s>124</s> <s>122</s> 110 bytes

```<code>a=>![...Array(a[0]*2)].some((_,i)=>(g=(a,l=0,n=i)=>[a.filter(c=>c>n||(l+=n/c|0,n%=c,0)),-l*!n])(...g(a))[1]>0)
</code>```

Requires the array to be sorted in descending order. Uses the observation in the linked paper that if the system is not canonical then there is at least one value less than 2a[0] which takes fewer coins when decomposed using the unused coins from the initial greedy algorithm.

Edit: Saved 12 bytes by realising that I could check all the coins even though I had already reached the target value. Saved 8 bytes by switching my intermediate output from [l,b] to [b,-l]; this allowed me to pass the first result directly as the parameter of the second call, plus also a small saving detecting whether the second call was successful. Saved 2 bytes by moving the definition of g into the some callback, allowing me to avoid unnecessarily passing in the loop variable twice. Saved 12 bytes by switching from my recursive helper function to a call to filter (made possible by my intermediate output switch).

Title: Determine if a coin system is Canonical

Body:
JavaScript (ES6), <s>144</s> <s>132</s> <s>124</s> <s>122</s> 110 bytes

a=>![...Array(a[0]*2)].some((_,i)=>(g=(a,l=0,n=i)=>[a.filter(c=>c>n||(l+=n/c|0,n%=c,0)),-l*!n])(...g(a))[1]>0)

Requires the array to be sorted in descending order. Uses the observation in the linked paper that if the system is not canonical then there is at least one value less than 2a[0] which takes fewer coins when decomposed using the unused coins from the initial greedy algorithm.

Edit: Saved 12 bytes by realising that I could check all the coins even though I had already reached the target value. Saved 8 bytes by switching my intermediate output from [l,b] to [b,-l]; this allowed me to pass the first result directly as the parameter of the second call, plus also a small saving detecting whether the second call was successful. Saved 2 bytes by moving the definition of g into the some callback, allowing me to avoid unnecessarily passing in the loop variable twice. Saved 12 bytes by switching from my recursive helper function to a call to filter (made possible by my intermediate output switch).


问:
Draw an ASCII chess board!
Here is a simple challenge for you: You must produce this ASCII representation of a chess board. White is represented by uppercase characters, and black is represented by lowercase. Empty tiles are represented by a .. Here is the full board:

```<code>rnbqkbnr
pppppppp
........
........
........
........
PPPPPPPP
RNBQKBNR
</code>```

Since this is a kolmogorov-complexity question, you may not take any input and you must output this board by any default method, for example, saving a file, printing to STDOUT or returning from a function. You may optionally produce one trailing newline. Standard loopholes apply, and the shortest program in bytes!

However, remember this is equally as much a competition between submissions in the same language. While it's unlikely that a languages like Java could beat a language like perl, or a golfing language like pyth or cjam, having the shortest Java answer is still really impressive! To help you track the shortest answer in each language, you may use this leaderboard, which will show the shortest submission by language and overall.

Leaderboards

To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:

```<code># Language Name, N bytes
</code>```

where N is the size of your submission. If you improve your score, you can keep old scores in the headline, by striking them through. For instance:

```<code># Ruby, <s>104</s> <s>101</s> 96 bytes
</code>```

If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the last number in the header:

```<code># Perl, 43 + 2 (-p flag) = 45 bytes
</code>```

You can also make the language name a link which will then show up in the leaderboard snippet:

```<code># [><>](http://esolangs.org/wiki/Fish), 121 bytes
</code>```

var QUESTION_ID=95745,OVERRIDE_USER=31716;function answersUrl(e){return"https://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"https://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="
"+e.body.replace(OVERRIDE_REG,"")+"
")});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;/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;```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}</code>```

 <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

{{PLACE}}	{{NAME}}	{{LANGUAGE}}	{{SIZE}}	Link

{{LANGUAGE}}	{{NAME}}	{{SIZE}}	Link

```

答:
Scala, 65 bytes

```<code>Seq("rnbqkbnr","p",".",".",".",".","P","RNBQKBNR")map(_*8 take 8)
</code>```

Really straightforward; makes use of the repeat 8 times and take the first 8 chars

Title: Draw an ASCII chess board!

Body:
Scala, 65 bytes

Seq("rnbqkbnr","p",".",".",".",".","P","RNBQKBNR")map(_*8 take 8)

Really straightforward; makes use of the repeat 8 times and take the first 8 chars


答:
Scala, 84 bytes

```<code>val b=BigDecimal
def?(& :Int)=1 to&map(x=>(""+b(1)/b(&))slice(2,x+2)map(_-48)sum)sum
</code>```

Ungolfed:

```<code>def f(n: Int)={
  val digits = ""+BigDecimal(1)/BigDecimal(n)
  (1 to n).map( x=>
    digits.slice(2, x+2).map(d => d - 48).sum
  ).sum
</code>```

Explanation:

```<code>val b=BigDecimal   //define an alias for BigDecimal
def?(& :Int)=      //define a method called ? with an integer & as a parameter
  1 to &           //create a range from 1 to &
  map(x=>          //for each number x...
    (""+b(1)/b(&))   //calculate the fraction
    slice(2,x+2)     //and take the slice starting from the third element,
                     //(dropping the "1.") and containing x elements
    map(_-48)        //for each char, subtract 48 to get the integer value
    sum              //and sum them
  )sum             //and take the sum
</code>```

I could save some bytes by exploiting the way the compiler tokenizes: By calling the argument &, you can write 1 to&map instead of 1 to n map. The same rule applies to def?.

Body:
Scala, 84 bytes

val b=BigDecimal
def?(& :Int)=1 to&map(x=>(""+b(1)/b(&))slice(2,x+2)map(_-48)sum)sum

Ungolfed:

def f(n: Int)={
  val digits = ""+BigDecimal(1)/BigDecimal(n)
  (1 to n).map( x=>
    digits.slice(2, x+2).map(d => d - 48).sum
  ).sum

Explanation:

val b=BigDecimal   //define an alias for BigDecimal
def?(& :Int)=      //define a method called ? with an integer & as a parameter
  1 to &           //create a range from 1 to &
  map(x=>          //for each number x...
    (""+b(1)/b(&))   //calculate the fraction
    slice(2,x+2)     //and take the slice starting from the third element,
                     //(dropping the "1.") and containing x elements
    map(_-48)        //for each char, subtract 48 to get the integer value
    sum              //and sum them
  )sum             //and take the sum

I could save some bytes by exploiting the way the compiler tokenizes: By calling the argument &, you can write 1 to&map instead of 1 to n map. The same rule applies to def?.


答:
Mathematica, 42 bytes

```<code>#&@@RealDigits[1/#,10,#,-1].(#-Range@#+1)&
</code>```

or

```<code>#&@@RealDigits[1/#,10,#,-1].Range[#,1,-1]&
</code>```

or

```<code>Tr@Accumulate@#&@@RealDigits[1/#,10,#,-1]&
</code>```

Explanation

Take the example from the challenge spec. We want to compute:

```<code>  1+4+2+8+5+7+1
+ 1+4+2+8+5+7
+ 1+4+2+8+5
+ 1+4+2+8
+ 1+4+2
+ 1+4
+ 1
</code>```

Rearranging, this is:

```<code>  1*7 + 4*6 + 2*5 + 8*4 + 5*3 + 7*2 + 1*1
= (1, 4, 2, 8, 5, 7, 1) . (7, 6, 5, 4, 3, 2, 1)
</code>```

where . is the scalar product of two vectors.

That's pretty much all the solution does.

```<code>#&@@RealDigits[1/#,10,#,-1]
</code>```

This gets us the first N decimal digits of 1/N (the #&@@ extracts the first element of the RealDigits result because that also returns the offset of the first digit which we don't care about).

Then we get the list from N down to 1 either using (#-Range@#+1) or Range[#,1,-1], both of which are shorter than Reverse@Range@#, and take the scalar product.

The alternative solution instead uses Accumulate to compute a list of all prefix sums and then adds up those prefix sums with Tr.

Since this is really fast even for large inputs, here is a scatter plot of the sequence up to N = 100,000 (doing all of them and plotting them took a while though):

Click for larger version.

The blue line is the naive upper bound of 9 N (N+1) / 2 (if all the decimal digits were 9) and the orange line is exactly half of that. Unsurprisingly this is right inside the main branch of the plot since, statistically, we'd expect the average digit to be 4.5.

The thin line of plot points which you can see below the main branch are fractions which end in ...3333..., as they all lie very close to 3 N (N+1) / 2.

Body:
Mathematica, 42 bytes

#&@@RealDigits[1/#,10,#,-1].(#-Range@#+1)&

or

#&@@RealDigits[1/#,10,#,-1].Range[#,1,-1]&

or

Tr@Accumulate@#&@@RealDigits[1/#,10,#,-1]&

Explanation

Take the example from the challenge spec. We want to compute:

  1+4+2+8+5+7+1
+ 1+4+2+8+5+7
+ 1+4+2+8+5
+ 1+4+2+8
+ 1+4+2
+ 1+4
+ 1

Rearranging, this is:

  1*7 + 4*6 + 2*5 + 8*4 + 5*3 + 7*2 + 1*1
= (1, 4, 2, 8, 5, 7, 1) . (7, 6, 5, 4, 3, 2, 1)

where . is the scalar product of two vectors.

That's pretty much all the solution does.

#&@@RealDigits[1/#,10,#,-1]

This gets us the first N decimal digits of 1/N (the #&@@ extracts the first element of the RealDigits result because that also returns the offset of the first digit which we don't care about).

Then we get the list from N down to 1 either using (#-Range@#+1) or Range[#,1,-1], both of which are shorter than Reverse@Range@#, and take the scalar product.

The alternative solution instead uses Accumulate to compute a list of all prefix sums and then adds up those prefix sums with Tr.

Since this is really fast even for large inputs, here is a scatter plot of the sequence up to N = 100,000 (doing all of them and plotting them took a while though):

Click for larger version.

The blue line is the naive upper bound of 9 N (N+1) / 2 (if all the decimal digits were 9) and the orange line is exactly half of that. Unsurprisingly this is right inside the main branch of the plot since, statistically, we'd expect the average digit to be 4.5.

The thin line of plot points which you can see below the main branch are fractions which end in ...3333..., as they all lie very close to 3 N (N+1) / 2.


问:
Simulate keystrokes
Your job is to simulate a couple of keystrokes that a user types in.

Input

A string array or string with a delimiter of your choice (outside the range 32-126) containing at least one 'keystroke'.

This array will only contain two types of string: passive keystrokes (single chars) and commands (chars within brackets [ ]).

Passive keystrokes

ASCII character codes [32-126]

Commands:

[B] : backspace (remove last character added if there is one)

[C] : copy all of what has already been written

[D] : delete all of what has been written

[P] : paste what has been copied

Output

The string produced by the keystrokes.

Examples

```<code>['H', 'e', 'l', 'l', 'o'] -> 'Hello'
['H', 'e', 'l', 'l', 'o', ' ', '[C]', '[P]'] -> 'Hello Hello '
['[D]', 'D', '[B]'] -> ''
['H', '[C]', 'i', '[P]', '[C]', '[P]'] -> 'HiHHiH'
['e', '[C]', '[B]', 'I', ' ', 'l', 'i', 'k', '[P]', ' ', 'b', '[P]', '[P]', 's', '!'] -> I like bees!
['N', '[P]'] -> 'N'
['#', '5', '0', 'K', '0', '0', '1', '[D]', '#', 'n', 'o', 't'] -> '#not'
['H', 'o', 'w', ' ', '[D]', 'H', 'e', 'y'] -> 'Hey'
['s', 'u', 'd', '[B]', 'p', '[C]', '[D]', 'I', ' ' , 'h', 'a', 'v', 'e', ' ', '[P]', 'p', 'e', 'r', '!'] -> 'I have supper!'
</code>```

This is code-golf, so shortest code in bytes wins!

答:
Scala, 158 bytes

```<code>(i:Seq[String])=>(("","")/:i){case((a,c),k)=>if(k.size<2)(a+k,c)else
if(k=="[B]")(a dropRight 1,c)else
if(k=="[C]")(a,a)else
if(k=="[D]")("",c)else(a+c,c)}._1
</code>```

Ungolfed:

```<code>(i:Seq[String]) => i.foldLeft(("", "")){
  case ((res,clipboard),key) =>
    if (k.size == 1) (res+key,clipboard)
    else if (k=="[B]") (res dropRight 1, clipboard)
    else if (k=="[C]") (res, res)
    else if (k=="[D]") ("", clipboard)else(acc+clipboard,clipboard)
}._1
</code>```

Solves this problem as a fold with the result and the clipboard as accumulator. Sadly, scala doesn't have a ternary conditional operator, but instead uses if else as an expression.

Title: Simulate keystrokes

Body:
Scala, 158 bytes

(i:Seq[String])=>(("","")/:i){case((a,c),k)=>if(k.size<2)(a+k,c)else
if(k=="[B]")(a dropRight 1,c)else
if(k=="[C]")(a,a)else
if(k=="[D]")("",c)else(a+c,c)}._1

Ungolfed:

(i:Seq[String]) => i.foldLeft(("", "")){
  case ((res,clipboard),key) =>
    if (k.size == 1) (res+key,clipboard)
    else if (k=="[B]") (res dropRight 1, clipboard)
    else if (k=="[C]") (res, res)
    else if (k=="[D]") ("", clipboard)else(acc+clipboard,clipboard)
}._1

Solves this problem as a fold with the result and the clipboard as accumulator. Sadly, scala doesn't have a ternary conditional operator, but instead uses if else as an expression.


问:
Sum of neighbours
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]

```<code>[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
</code>```

Test cases

```<code>[]            => 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
</code>```

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="
"+e.body.replace(OVERRIDE_REG,"")+"
")});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;/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;```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}</code>```

 <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

{{PLACE}}	{{NAME}}	{{LANGUAGE}}	{{SIZE}}	Link

{{LANGUAGE}}	{{NAME}}	{{SIZE}}	Link

```

答:
Scala, 47 bytes

```<code>def&(a:Float*)=(0+:a:+0)sliding 3 map(_.sum)sum
</code>```

Prepends and appends a 0, then uses a sliding window of size 3 to sum the neighbors, and calculates the total sum

Title: Sum of neighbours

Body:
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


答:
MATLAB, 18 bytes

```<code>@(s)mod(diff(s),2)
</code>```

This returns

```<code>f=@(s)mod(diff(s),2)
f('PPCG')
ans =
     0     1     0
f('#define')
ans =
     1     1     1     1     1     1
</code>```

In MATLAB, if x is a vector, then if x is equivalent to if all(x). According to this Meta post, it's enough to return x.

Title: EvenSt-ring C ode - g ol!f

Body:
An 'Even string' is any string where the parity of the ASCII values of the characters is always alternating. For example, the string EvenSt-ring$! is an even-string because the ASCII values of the characters are:

```<code>69 118 101 110 83 116 45 114 105 110 103 36 33
</code>```

And the parities of these numbers are:

```<code>Odd Even Odd Even Odd Even Odd Even Odd Even Odd Even Odd
</code>```

Which is alternating the whole way. However, a string like Hello world! is not an even string because the ASCII values are:

```<code>72 101 108 108 111 32 87 111 114 108 100 33
</code>```

And the parities are:

```<code>Even Odd Even Even Odd Even Odd Odd Even Even Even Odd
</code>```

Which is clearly not always alternating.

The challenge

You must write either a full program or a function that accepts a string for input and outputs a truthy value if the string is even, and a falsy value otherwise. You can take your input and output in any reasonable format, and you can assume that the input will only have printable ASCII (the 32-127 range). You do not have to handle empty input.

Examples

Here are some examples of even strings:

```<code>#define
EvenSt-ring$!
long
abcdABCD
3.141
~
0123456789
C ode - g ol!f
HatchingLobstersVexinglyPopulateJuvenileFoxglove
</code>```

And all of these examples are not even strings:

```<code>Hello World
PPCG
3.1415
babbage
Code-golf
Standard loopholes apply
Shortest answer in bytes wins
Happy golfing!
</code>```

You may also use this ungolfed solution to test any strings if you're curious about a certain test-case.

Body:
MATLAB, 18 bytes

@(s)mod(diff(s),2)

This returns

f=@(s)mod(diff(s),2)
f('PPCG')
ans =
     0     1     0
f('#define')
ans =
     1     1     1     1     1     1

In MATLAB, if x is a vector, then if x is equivalent to if all(x). According to this Meta post, it's enough to return x.


答:
R, 75 70 52 34 33 31 bytes

Sum times three and subtract first and last element

```<code>sum(x<-scan())*3-x[1]-tail(x,1)
</code>```

Edit: Saved 3 extra bytes thanks to @rturnbull

Title: Sum of neighbours

Body:
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]

```<code>[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
</code>```

Test cases

```<code>[]            => 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
</code>```

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="
"+e.body.replace(OVERRIDE_REG,"")+"
")});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;/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;```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}</code>```

 <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

{{PLACE}}	{{NAME}}	{{LANGUAGE}}	{{SIZE}}	Link

{{LANGUAGE}}	{{NAME}}	{{SIZE}}	Link

```

Body:
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


答:
Java 7, 72 Bytes

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

Title: Sum of neighbours

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


答:
05AB1E, <s>11</s> 5 bytes

Saved 6 bytes thanks to Adnan.

```<code>€Ð¦¨O
</code>```

Try it online!

Explanation

```<code>€Ð     # triplicate each item in the list
  ¦¨   # remove first and last element
    O  # sum
</code>```

Title: Sum of neighbours

Body:
05AB1E, <s>11</s> 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


答:
Python 2, 28 bytes

```<code>lambda a:sum(a)*3-a[0]-a[-1]
</code>```

Just 3 times the sum and minus one of each end element

Title: Sum of neighbours

Body:
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


答:
Mathematica, <s>34</s> <s>32</s> 29 bytes

Taking some inspiration Lynn's neat Python answer...

```<code>Check[3Tr@#-Last@#-#[[1]],0]&
</code>```

or

```<code>Check[3(+##)-#&@@#-Last@#,0]&
</code>```

or

```<code>Check[##-#/3&@@#*3-Last@#,0]&
</code>```

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.

Title: Sum of neighbours

Body:
Mathematica, <s>34</s> <s>32</s> 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.


答:
MATL, 5 bytes

```<code>7BZ+s
</code>```

Try it online!

Explanation

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

Title: Sum of neighbours

Body:
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


答:
JavaScript (ES6), <s>40</s> 33 bytes

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

Returns NaN when given an empty list.

Title: Sum of neighbours

Body:
JavaScript (ES6), <s>40</s> 33 bytes

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

Returns NaN when given an empty list.


问:
Random dice tipping
In a standard dice (die) the numbers are arranged so that opposite faces add to seven.
Write the shortest possible program in your preferred language which outputs a random throw followed by 9 random tippings. A tipping is a quarter turn of the dice, e.g. if the dice is facing 5, all possible tippings are 1,3,4 and 6.

Example of desired output:

1532131356

答:
J

This should work but unfortunately J's random generator gets stuck after the 3rd iteration:

```<code>a=:>:i.6
f=:a#~1-(+&(a=])7&-)
((,(?4)&{@f@(_1&{))^:9)>:?6
</code>```

6 4 5 4 5 4 5 4 5 4

ContentLicense: CC BY-SA 2.5

Title: Random dice tipping

Body:
J

This should work but unfortunately J's random generator gets stuck after the 3rd iteration:

a=:>:i.6
f=:a#~1-(+&(a=])7&-)
((,(?4)&{@f@(_1&{))^:9)>:?6

6 4 5 4 5 4 5 4 5 4


答:
C# with LINQ, 42 bytes

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

Requires the System.Linq namespace.

C#, 84 bytes

```<code>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);};
</code>```

Full program with test cases:

```<code>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
        }
    }
}
</code>```

Title: Sum of neighbours

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


答:
MATLAB, <s>31</s> <s>28</s> 26 bytes

3 bytes saved thanks to @Luis

```<code>@(x)sum(conv(x,1:3>0,'s'))
</code>```

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.

Title: Sum of neighbours

Body:
MATLAB, <s>31</s> <s>28</s> 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.


答:
PHP, 39 bytes

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

Run like this:

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

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.

Title: Sum of neighbours

Body:
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.


答:
JavaScript (ES6), 116 <s>125 130</s>

l=>eval("r=(d,k)=>d?--k&&l.map(v=>v>d||r(d-v,k)):x=1;for(x=l[0]*2;--x>1;r(x,g))g=0,h=x,l.map(v=>(g+=h/v|0,h%=v));x")
```
<p>This needs the input array sorted in descending order. For each value from 2N downto 2 (N being the max coin value), it find the number of coins from the greedy algorithm and try to find a smaller set of coins.</p>
<p><em>Less golfed</em></p>
<pre class="lang-js prettyprint-override"><code>l=>{
  // recursive function to to find a smaller set of coins
  // parameter k is the max coin limit
  r = (d,k) => d // check if difference is not 0
     ? --k // if not, and if the number of coins used will be less than limit
      && l.map(v => v>d || r(d-v, k))  // proceed with the recursive search
     : x=1 // if diff is 0, value found, set x to 1 to stop the loop
  for( x=l[0]*2; --x > 1; )
    g=0, h=x, l.map(v=>(g += h/v|0, h %= v)), // find g with the greedy algorithm
    r(x,g) // call with initial difference equal to target value
  return x
}
</code>```

Test

f=
l=>eval("r=(d,k)=>d?--k&&l.map(v=>v>d||r(d-v,k)):x=1;for(x=l[0]*2;--x>1;r(x,g))g=0,h=x,l.map(v=>(g+=h/v|0,h%=v));x")

/* No eval
f=l=>{
  r=(d,k)=>d?--k&&l.map(v=>v>d||r(d-v,k)):x=1;
  for(x=l[0]*2;--x>1;r(x,g))
    g=0,h=x,l.map(v=>(g+=h/v|0,h%=v));
  return x;
}*/

;[
 [[100,50,20,10,5,2,1],1], [[4,3,1],0],
 [[25,10,5,1],1], [[25,10,6,1],0],
 [[3,2,1],1], [[30,17,8,1], 0],
 [[12,8,3,1],0], [[13,8,2,1], 0]
].forEach(t=>{
  var i=t[0],k=t[1],r=f(i),
      msg=((r==k)?'OK ':'KO ')+i+' -> '+r
      + (r==k?'':' (should be '+k+')')
  O.textContent += msg+'\n'
})

function test()
{
  var i=I.value.match(/\d+/g).map(x=>+x).sort((a,b)=>b-a)
  O.textContent = i+' -> '+f(i)+'\n'+O.textContent
 }```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#I { width:50% }</code>```

<input id=I value='1 4 9'><button onclick='test()'>test</button>

```</code>```

Title: Determine if a coin system is Canonical

Body:
The Cashier's Algorithm is an algorithm for making change in the minimal number of coins that works quite well for most currency systems.  However like most greedy algorithms it is not without its flaws.  If a currency system is set up just right (or just wrong) there are certain values in which the Cashier's Algorithm will fail to find the optimal change.

Take the following example:

We have 4¢, 3¢, and 1¢ coins.  We want to make 6¢.

The Cashier's Algorithm will first select as many of the largest coin (one 4¢ to start) and subtract and repeat.  This will result in one 4¢ coin and two 1¢ coins, for a total of 3 coins.

Unfortunately for the Algorithm there is a way to make 6¢ with only two coins (two 3¢ coins).

A system of change will be considered canonical iff for all integer values the Cashier's Algorithm will find the optimal number of coins.

Task

You task will be to take a system as a either an unordered container or sorted ordered container of integers representing coin values and output a truthy value if the system input is canonical and falsy otherwise.

Your program should work for all systems that can create any value.  (i.e. all systems will have a 1¢ coin)

This is code golf least bytes wins.

Test cases

This list is by no means exhaustive, your program should work for all valid input

```<code>1, 3, 4       -> 0
1, 5, 10, 25  -> 1
1, 6, 10, 25  -> 0
1, 2, 3       -> 1
1, 8, 17, 30  -> 0
1, 3, 8, 12   -> 0
1, 2, 8, 13   -> 0
1, 2, 4, 6, 8 -> 1
</code>```

Body:
JavaScript (ES6), 116 <s>125 130</s>

l=>eval("r=(d,k)=>d?--k&&l.map(v=>v>d||r(d-v,k)):x=1;for(x=l[0]*2;--x>1;r(x,g))g=0,h=x,l.map(v=>(g+=h/v|0,h%=v));x")

This needs the input array sorted in descending order. For each value from 2N downto 2 (N being the max coin value), it find the number of coins from the greedy algorithm and try to find a smaller set of coins.

Less golfed

l=>{
  // recursive function to to find a smaller set of coins
  // parameter k is the max coin limit
  r = (d,k) => d // check if difference is not 0
     ? --k // if not, and if the number of coins used will be less than limit
      && l.map(v => v>d || r(d-v, k))  // proceed with the recursive search
     : x=1 // if diff is 0, value found, set x to 1 to stop the loop
  for( x=l[0]*2; --x > 1; )
    g=0, h=x, l.map(v=>(g += h/v|0, h %= v)), // find g with the greedy algorithm
    r(x,g) // call with initial difference equal to target value
  return x
}

Test

f=
l=>eval("r=(d,k)=>d?--k&&l.map(v=>v>d||r(d-v,k)):x=1;for(x=l[0]*2;--x>1;r(x,g))g=0,h=x,l.map(v=>(g+=h/v|0,h%=v));x")

/* No eval
f=l=>{
  r=(d,k)=>d?--k&&l.map(v=>v>d||r(d-v,k)):x=1;
  for(x=l[0]*2;--x>1;r(x,g))
    g=0,h=x,l.map(v=>(g+=h/v|0,h%=v));
  return x;
}*/

;[
 [[100,50,20,10,5,2,1],1], [[4,3,1],0],
 [[25,10,5,1],1], [[25,10,6,1],0],
 [[3,2,1],1], [[30,17,8,1], 0],
 [[12,8,3,1],0], [[13,8,2,1], 0]
].forEach(t=>{
  var i=t[0],k=t[1],r=f(i),
      msg=((r==k)?'OK ':'KO ')+i+' -> '+r
      + (r==k?'':' (should be '+k+')')
  O.textContent += msg+'\n'
})

function test()
{
  var i=I.value.match(/\d+/g).map(x=>+x).sort((a,b)=>b-a)
  O.textContent = i+' -> '+f(i)+'\n'+O.textContent
 }

#I { width:50% }

<input id=I value='1 4 9'><button onclick='test()'>test</button>
<pre id=O></pre>


答:
Batch, 67 bytes

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

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

Title: Sum of neighbours

Body:
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.


答:
><>, 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.

```<code>:{:}+i*v
:$v?=1l<+++:
;n<
</code>```

Title: Sum of neighbours

Body:
><>, 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<