问:
The teacher is always wrong, flip his answer
Your dumb teacher is always wrong, so flip his answer.

Change these responses

```<code>True -> False
Yes -> No
0 -> 1
Yeah -> Nope
</code>```

and vice versa. Keeping punctuation and the first letter's capitalization counts. Only one condition will be passed to the program.

You only need to accept the following test cases:

```<code>True <-> False
True. <-> False.
true <-> false
true. <-> false.
Yes <-> No
Yes. <-> No.
yes <-> no
yes. <-> no.
0 <-> 1
Yeah <-> Nope
yeah <-> nope
Yeah. <-> Nope.
yeah. <-> nope.
</code>```

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

Body:
Pyth, 44 bytes

j\.XXXcz\.`M2)Jc."<unprintables>"\b)rR3J

Hexdump:

00: 6A5C 2E58 5858 637A 5C2E 604D 3229 4A63
10: 2E22 6179 0862 3C40 D23B 9A54 C2B4 A20A
20: FEE7 8701 225C 6229 7252 334A

Test suite.


ContentLicense: CC BY-SA 3.0

Title: The teacher is always wrong, flip his answer

Body:
Your dumb teacher is always wrong, so flip his answer.

Change these responses

```<code>True -> False
Yes -> No
0 -> 1
Yeah -> Nope
</code>```

and vice versa. Keeping punctuation and the first letter's capitalization counts. Only one condition will be passed to the program.

You only need to accept the following test cases:

```<code>True <-> False
True. <-> False.
true <-> false
true. <-> false.
Yes <-> No
Yes. <-> No.
yes <-> no
yes. <-> no.
0 <-> 1
Yeah <-> Nope
yeah <-> nope
Yeah. <-> Nope.
yeah. <-> nope.
</code>```

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

Body:
Pyke, <s>51</s> 44 bytes

.d̾ॗǣ/ற㻯dc2cDMl4+D.F\.+)+T`]1+Dm_+Y@

Try it here!

.d̾ॗǣ/ற㻯dc2c                         - {'yeah': 'nope', 'true': 'false', 'yes': 'no'}
             DMl4+                    - ^ += map(^, str.title())
                  D.F\.+)+            - ^ += map(^+".")
                          T`]1+       - ^ += [repr(10)]
                               Dm_+   - ^ += map(^, reversed)
                                   Y@ - dict(^)[input]


问:
Pseudofactorial
There is a rather curious number which shows up sometimes in math problems or riddles. The pseudofactorial(N) is the least (i.e. lowest) common multiple of the numbers 1 through N; in other words, it's the lowest number which has all numbers from 1 through N as factors.

For instance pseudofactorial(7) = 3 * 4 * 5 * 7, which is the same as 7! except that 2 and 6 have been removed because they are contained in other terms.

Write a program to calculate pseudofactorial(N) and as always, shortest code wins.

Here is a short list for your use. More test cases can be found in the OEIS under A003418.

Factorial:

1

2

6

24

120

720

5040

Pseudofactorial:

1

2

6

12

60

60

420

答:
GameMaker Language, 60 bytes

```<code>for(b=k=1;b;++k){b=0for(t=argument0;t;b+=k mod t--)}return k
</code>```

Based on the logic of anatolyg's answer.

Title: Pseudofactorial

Body:
GameMaker Language, 60 bytes

for(b=k=1;b;++k){b=0for(t=argument0;t;b+=k mod t--)}return k

Based on the logic of anatolyg's answer.


问:
Is my emoji dry?
This is my pet emoji, Billy:

```<code>-_-
</code>```

Emojis don't like to be in the rain, so Billy is sad... Let's draw him an umbrella to make him feel better!

```<code>  /\
 /  \
/    \

  -_-
</code>```

This is good, he is entirely covered by his umbrella! Here is an example where only part of him is covered:

```<code>  /\
 /  \
/    \

     -_-
</code>```

In this case, sections 2 and 3 of his body are exposed to the rain.

Umbrellas come in many shapes and sizes, but they're always made up from a series of ascending slashes / followed by a series of descending backslashes \. For example, these are all valid umbrellas:

```<code>  /\
 /  \
/    \

/\

    /\
   /  \
  /    \
 /      \
/        \
</code>```

And these are not:

```<code>/   \

\/

  \
 / \
/   \

 0\
/  \

//\\
/  \
</code>```

You need to determine which parts of my emoji are exposed to the rain.

Clarifications

Your program (or function) will take a 2d string as input. This can be in whatever format is most convenient or natural to your language. An array of strings, an array of arrays of characters, a string with newlines in it etc.

You must output which sections of the emoji are exposed to the rain. This can be zero-indexed or one-indexed, as long as you make this clear. Output can be in any reasonable format. If the entire emoji is protected from the rain, output nothing (or an empty array).

You can assume that all inputs will have a valid umbrella, and the same emoji: -_-. The emoji will always be on the last line of the input, however their might be several empty lines between the umbrella and the emoji.

Everything that isn't part of the umbrella or the emoji will be a space   character or newline.

The input will be padded with spaces so that the length of each line is the same.

Standard loopholes apply, and the shortest answer in bytes wins!

Test IO:

All of the sample cases will use one-indexing.

```<code>  /\
 /  \
/    \

  -_-

Outputs: []

----------------

   /\
  /  \

     -_-

Outputs: [2, 3]

----------------

    /\
   -_-

Outputs: [1]

----------------

     /\
    /  \
   /    \
  /      \
 /        \
/          \

               -_-

Outputs: [1, 2, 3]
</code>```

答:
JavaScript (ES6), 92 bytes

```<code>a=>a.map(s=>s.replace(/\S/g,(c,i)=>c>'-'&c<'_'?u[i]=3:++n&u[i]||r.push(n)),n=0,u=[],r=[])&&r
</code>```

Accepts a ragged array of lines and returns a 1-indexed result. Explanation:

```<code>a=>a.map(               Loop through all lines
 s=>s.replace(/\S/g,    Loop through all non-whitepsace
  (c,i)=>c>'-'&c<'_'    If it's part of the umbrella
   ?u[i]=3              Mark that column as dry
   :++n&                Add 1 to the emoji index
     u[i]||             If the column is not dry
      r.push(n)         Add the emoji index to the result
  ),n=0,u=[],r=[]       Initialise variables
 )&&r                   Return result
</code>```

Title: Is my emoji dry?

Body:
JavaScript (ES6), 92 bytes

a=>a.map(s=>s.replace(/\S/g,(c,i)=>c>'-'&c<'_'?u[i]=3:++n&u[i]||r.push(n)),n=0,u=[],r=[])&&r

Accepts a ragged array of lines and returns a 1-indexed result. Explanation:

a=>a.map(               Loop through all lines
 s=>s.replace(/\S/g,    Loop through all non-whitepsace
  (c,i)=>c>'-'&c<'_'    If it's part of the umbrella
   ?u[i]=3              Mark that column as dry
   :++n&                Add 1 to the emoji index
     u[i]||             If the column is not dry
      r.push(n)         Add the emoji index to the result
  ),n=0,u=[],r=[]       Initialise variables
 )&&r                   Return result


答:
Hoon, 67 bytes

```<code>|*
*
(roll (gulf 1 +<) |=({a/@ b/_1} (div (mul a b) d:(egcd a b))))
</code>```

Create the list [1..n], fold over the list with lcm. Unfortunately, the Hoon stdlib doesn't have a pre-built one I can use :/

Title: Pseudofactorial

Body:
There is a rather curious number which shows up sometimes in math problems or riddles. The pseudofactorial(N) is the least (i.e. lowest) common multiple of the numbers 1 through N; in other words, it's the lowest number which has all numbers from 1 through N as factors.

For instance pseudofactorial(7) = 3 * 4 * 5 * 7, which is the same as 7! except that 2 and 6 have been removed because they are contained in other terms.

Write a program to calculate pseudofactorial(N) and as always, shortest code wins.

Here is a short list for your use. More test cases can be found in the OEIS under A003418.

Factorial:

1

2

6

24

120

720

5040

Pseudofactorial:

1

2

6

12

60

60

420

Body:
Hoon, 67 bytes

|*
*
(roll (gulf 1 +<) |=({a/@ b/_1} (div (mul a b) d:(egcd a b))))

Create the list [1..n], fold over the list with lcm. Unfortunately, the Hoon stdlib doesn't have a pre-built one I can use :/


问:
Return the integers with square digit-sums

Introduction and Credit

We all know and love our awesome rules to test whether a number is divisble by 11 or 3, which is just some clever sum over the digits of the number. Now this challenge takes this to a new level, by requiring you to compute the sum of the digits and then checking whether the result is a perfect integer square, neither of which operations usually can be done very short. As this property is also very hard to see when looking at a number, we want this to be done for entire lists of numbers so we can save human work. So this is your challenge now!

This was an assignment at my university functional programming course. This assignment is now closed and has been discussed in class and I have my professor's permission to post it here (I asked explicitely).

Specification

Input

Your input is a list of non-negative integers, in any standard I/O format.

You may choose the list format as your language needs it

Output

The output is a list of integers, in any standard I/O format.

What to do?

Filter out every integer from the input list for which the sum of the digits is not a a square (of an integer).

The order of the elements may not be changed, e.g. if you get [1,5,9] you may not return [9,1]

Potential corner cases

0 is a non-negative integer and thus a valid input and 0 is also a valid integer root, e.g. 0 counts as an integer square.

The empty list is a valid input and output as well.

Who wins?

This is code-golf so the shortest answer in bytes wins!

Standard rules apply of course.

Test Cases

```<code>[1,4,9,16,25,1111] -> [1,4,9,1111]
[1431,2,0,22,999999999] -> [1431,0,22,999999999]
[22228,4,113125,22345] -> [22228,4,22345]
[] -> []
[421337,99,123456789,1133557799] -> []
</code>```

Step-by-Step Example

```<code>Example input: [1337,4444]
Handling first number:
Sum of the digits of 1337: 1+3+3+7=14
14 is not an integer square, thus will be dropped!
Handling second number:
Sum of the digits of 4444: 4+4+4+4=16
16 is an integer square because 4*4=16, can get into the output list!
Example output: [4444]
</code>```

答:
TXR Lisp: <s>85 81</s> 72 byte (op ...) denoting anon. function:

```<s>(op keep-if (opip tostring (mapcar chr-digit) (apply +) (= @1 [[dup *] (isqrt @1)])))</s>
<s>(op keep-if (opip `@1` (mapcar chr-digit) (apply +) (= @1 [[dup *] (isqrt @1)])))</s>
(op keep-if(opip`@1`(mapcar chr-digit)(apply +)(=@1[[dup *](isqrt@1)])))
```

```<code>$ txr -i
1> (op keep-if(opip`@1`(mapcar chr-digit)(apply +)(=@1[[dup *](isqrt@1)])))
#<interpreted fun: lambda #:rest-0117>
2> [*1 '(1 4 9 16 25 1111)]
(1 4 9 1111)
3> [*1 '(1431 2 0 22 999999999)]
(1431 0 22 999999999)
4> [*1 ()]
nil
5> [*1 '(22228 4 113125 22345)]
(22228 4 22345)
6> [*1 '(421337 99 123456789 1133557799)]
nil
7>
</code>```

isqrt is integer square root. This will handle large integers; no floating-point hacks here.

TXR Lisp is fundamentally a Lisp-2 dialect, like ANSI Common Lisp or Emacs Lisp. However, the square brackets [whatever ...] notation is syntactic sugar for the operator (dwim whatever ...) which evaluates using a form of Lisp-1 namespace semantics rather than Lisp-2: functions and variable bindings in one space rather than separate spaces. dwim is "deep"; it's not a macro transforming Lisp-2 to Lisp-2; it has visibility into the lexical environments to deliver the actual Lisp-1-like semantics.

In [dup *], the dup combinator takes a binary function (or a function that can be used as binary), and returns a unary function which applies two copies of its argument to that function as two arguments; i.e [dup *] denotes a squaring function.

op is a rich partial evaluation macro, and opip combines left-to-right pipeline with op: op pipe. (op mapcar +) curries the mapcar function. In (opip (mapcar +) ...),mapcaris similarly curried (theop` is implicit), and part of a pipeline.

The TXR Lisp REPL allows numbered references to prior results, modulo 100: *1 is the value produced in the most recent command line numbered 1, or 101, or 201, ...

Body:
TXR Lisp: <s>85 81</s> 72 byte (op ...) denoting anon. function:

<s>(op keep-if (opip tostring (mapcar chr-digit) (apply +) (= @1 [[dup *] (isqrt @1)])))</s>
<s>(op keep-if (opip `@1` (mapcar chr-digit) (apply +) (= @1 [[dup *] (isqrt @1)])))</s>
(op keep-if(opip`@1`(mapcar chr-digit)(apply +)(=@1[[dup *](isqrt@1)])))

$ txr -i
1> (op keep-if(opip`@1`(mapcar chr-digit)(apply +)(=@1[[dup *](isqrt@1)])))
#<interpreted fun: lambda #:rest-0117>
2> [*1 '(1 4 9 16 25 1111)]
(1 4 9 1111)
3> [*1 '(1431 2 0 22 999999999)]
(1431 0 22 999999999)
4> [*1 ()]
nil
5> [*1 '(22228 4 113125 22345)]
(22228 4 22345)
6> [*1 '(421337 99 123456789 1133557799)]
nil
7>

isqrt is integer square root. This will handle large integers; no floating-point hacks here.

TXR Lisp is fundamentally a Lisp-2 dialect, like ANSI Common Lisp or Emacs Lisp. However, the square brackets [whatever ...] notation is syntactic sugar for the operator (dwim whatever ...) which evaluates using a form of Lisp-1 namespace semantics rather than Lisp-2: functions and variable bindings in one space rather than separate spaces. dwim is "deep"; it's not a macro transforming Lisp-2 to Lisp-2; it has visibility into the lexical environments to deliver the actual Lisp-1-like semantics.

In [dup *], the dup combinator takes a binary function (or a function that can be used as binary), and returns a unary function which applies two copies of its argument to that function as two arguments; i.e [dup *] denotes a squaring function.

op is a rich partial evaluation macro, and opip combines left-to-right pipeline with op: op pipe. (op mapcar +) curries the mapcar function. In (opip (mapcar +) ...),mapcaris similarly curried (theop` is implicit), and part of a pipeline.

The TXR Lisp REPL allows numbered references to prior results, modulo 100: *1 is the value produced in the most recent command line numbered 1, or 101, or 201, ...


答:
05AB1E, <s>45</s> <s>41</s> <s>40</s> <s>39</s> 38 bytes

Code:

```<code>“‰¦žä¥æ€¸pe…Ü€¸“ð¡2ôDí«D€™«vy`:D_D¹Êiq
</code>```

Explanation:

It first starts with the compression:

```<code>“‰¦žä¥æ€¸pe…Ü€¸“
</code>```

This is a compressed version of "true false yeah nope yes no". After that, we split on the spaces with ð¡, resulting into:

```<code>['true', 'false', 'yeah', 'nope', 'yes', 'no']
</code>```

We slice this array into pieces of 2 with 2ô, resulting into:

```<code>[['true', 'false'], ['yeah', 'nope'], ['yes', 'no']]
</code>```

We duplicate this array and reverse each element of it with Dí. Then we append this to our first array with «, resulting into:

```<code>[['true', 'false'], ['yeah', 'nope'], ['yes', 'no'], ['false', 'true'], ['nope', 'yeah'], ['no', 'yes']]
</code>```

To get the titlecased words, we duplicate the array again and convert each word to titlecase with €™. Finally, this is appended to the initial array. So, the final list is:

```<code>[['true', 'false'],
 ['yeah', 'nope'],
 ['yes', 'no'],
 ['false', 'true'],
 ['nope', 'yeah'],
 ['no', 'yes'],
 ['True', 'False'],
 ['Yeah', 'Nope'],
 ['Yes', 'No'],
 ['False', 'True'],
 ['Nope', 'Yeah'],
 ['No', 'Yes']]
</code>```

The imporant part here is that Nope comes before No. Eventually, we get to this part of the code:

```<code>vy`:D_D¹Êiq
</code>```

Explanation:

```<code>v            # For each in the array...
 y`          #   Push the array (containing 2 words) and flatten.
   :         #   Replace the first word with the second.
    D_       #   Duplicate and negate (resulting 0 into 1 and 1 into 0).
                 If this is not possible, this results into nothing.
      D      #   Duplicate the top of the stack again.
       ¹Ê    #   If it's not equal to the inital input string...
         iq  #     Quit the program and implicitly print the processed string.
</code>```

Uses the CP-1252 encoding. Try it online!.

Body:
05AB1E, <s>45</s> <s>41</s> <s>40</s> <s>39</s> 38 bytes

Code:

“‰¦žä¥æ€¸pe…Ü€¸“ð¡2ôDí«D€™«vy`:D_D¹Êiq

Explanation:

It first starts with the compression:

“‰¦žä¥æ€¸pe…Ü€¸“

This is a compressed version of "true false yeah nope yes no". After that, we split on the spaces with ð¡, resulting into:

['true', 'false', 'yeah', 'nope', 'yes', 'no']

We slice this array into pieces of 2 with 2ô, resulting into:

[['true', 'false'], ['yeah', 'nope'], ['yes', 'no']]

We duplicate this array and reverse each element of it with Dí. Then we append this to our first array with «, resulting into:

[['true', 'false'], ['yeah', 'nope'], ['yes', 'no'], ['false', 'true'], ['nope', 'yeah'], ['no', 'yes']]

To get the titlecased words, we duplicate the array again and convert each word to titlecase with €™. Finally, this is appended to the initial array. So, the final list is:

[['true', 'false'],
 ['yeah', 'nope'],
 ['yes', 'no'],
 ['false', 'true'],
 ['nope', 'yeah'],
 ['no', 'yes'],
 ['True', 'False'],
 ['Yeah', 'Nope'],
 ['Yes', 'No'],
 ['False', 'True'],
 ['Nope', 'Yeah'],
 ['No', 'Yes']]

The imporant part here is that Nope comes before No. Eventually, we get to this part of the code:

vy`:D_D¹Êiq

Explanation:

v            # For each in the array...
 y`          #   Push the array (containing 2 words) and flatten.
   :         #   Replace the first word with the second.
    D_       #   Duplicate and negate (resulting 0 into 1 and 1 into 0).
                 If this is not possible, this results into nothing.
      D      #   Duplicate the top of the stack again.
       ¹Ê    #   If it's not equal to the inital input string...
         iq  #     Quit the program and implicitly print the processed string.

Uses the CP-1252 encoding. Try it online!.


问:
Cat goes "Meow"

cat goes  "Meow"

We are all familiar with the concept of a cat program. The user types something in, it is echoed back to the user. Easy. But all cat programs I've seen so far have missed one fact: a cat goes "Meow". So your task is to write a program that copies all STDIN to STDOUT UNLESS the input is cat, in which case your program should output cat goes "Meow".

Scoring

This is code-golf, so your score is your byte count, with a few modifiers:

If your program works for any additional animals other than cat (e.g. cow: cow goes "Moo"), for each additional animal: -10

If your program doesn't use the word "cat": -15

If your program responds to fox with "What does the fox say": -25

Animals and sounds that go together:

cow goes moo
duck goes quack
sheep goes baa
bees go buzz
frogs go croak

Anything else on this list is allowed.

Rules

Standard loopholes apply

You must not write anything to STDERR

You can use single quotes/no quotes instead of double quotes.

Leaderboard

Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language.

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=62500;var OVERRIDE_USER=46470;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

```

答:
Java, 174 - 15 = 159 bytes

```<code>interface a{static void main(String[]A){for(String s="";;s=new java.util.Scanner(System.in).nextLine())System.out.println(s+(s.equalsIgnoreCase("ca"+"t")?" goes meow":""));}}
</code>```

Ungolfed:

```<code>interface a {
    static void main(String[] A){
        for (String s = "";;s = new java.util.Scanner(System.in).nextLine())
            System.out.println(s + (s.equalsIgnoreCase("ca"+"t") ? " goes meow" : ""));
    }
}
</code>```

Title: Cat goes "Meow"

Body:
Java, 174 - 15 = 159 bytes

interface a{static void main(String[]A){for(String s="";;s=new java.util.Scanner(System.in).nextLine())System.out.println(s+(s.equalsIgnoreCase("ca"+"t")?" goes meow":""));}}

Ungolfed:

interface a {
    static void main(String[] A){
        for (String s = "";;s = new java.util.Scanner(System.in).nextLine())
            System.out.println(s + (s.equalsIgnoreCase("ca"+"t") ? " goes meow" : ""));
    }
}


问:
Is this figure connected?
You are given a list of (x,y) grid coordinates.  Your function should decide whether the figure obtained by coloring in the squares of the grid with the given coordinates is connected or not.

Squares adjacent diagonally are not considered connected.

Example input:

```<code>(0,0),(1,0),(2,0),(3,0),(3,1),(3,2),(2,2),
(1,2),(0,2),(0,3),(0,4),(1,4),(2,4),(3,4)
</code>```

which looks like:

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

Output:

```<code>YES
</code>```

Example input:

```<code>(0,0),(1,0),(2,0),(0,1),(0,2),(2,2),(3,2),(4,2),(0,3),
(4,3),(0,4),(1,4),(2,4),(4,4),(4,5),(2,6),(3,6),(4,6)
</code>```

which looks like:

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

Output:

```<code>NO
</code>```

Your function must take as input a list of pairs of integers (e.g. in C++, maybe vector<pair<int,int>>) and return a boolean.  You may not assume any particular ordering of the input points.  The coordinates will be between 0 and 99 inclusive.

Smallest code wins.

ContentLicense: CC BY-SA 2.5

Title: Is this figure connected?

Body:
Haskell 98, 98

g p@(x,y)z|elem p z=foldr g(filter(/=p)z)[(x-1,y),(x+1,y),(x,y-1),(x,y+1)]|0<1=z
f z=null$g(z!!0)z

Sample use:

*Main> f [(0,0),(1,0),(2,0),(3,0),(3,1),(3,2),(2,2),
          (1,2),(0,2),(0,3),(0,4),(1,4),(2,4),(3,4)]
True
*Main> f [(0,0),(1,0),(2,0),(0,1),(0,2),(2,2),(3,2),(4,2),(0,3),
          (4,3),(0,4),(1,4),(2,4),(4,4),(4,5),(2,6),(3,6),(4,6)]
False


答:
TI-Basic, 217 bytes

Longer than I thought it would be...

```<code>Input Str1
If Str1="0
Then
Disp 1
Stop
End
"e"=sub(Str1,2,1
sub("FalsefalseNopenope",1+5not(Ans)(sub(Str1,1,1)="t")+10Ans+4Ans(sub(Str1,1,1)="y"),5-Ans-2(sub(Str1,3,1)="s"))+sub(" .",1+(sub(Str1,length(Str1),1)="."),1
</code>```

Body:
TI-Basic, 217 bytes

Longer than I thought it would be...

Input Str1
If Str1="0
Then
Disp 1
Stop
End
"e"=sub(Str1,2,1
sub("FalsefalseNopenope",1+5not(Ans)(sub(Str1,1,1)="t")+10Ans+4Ans(sub(Str1,1,1)="y"),5-Ans-2(sub(Str1,3,1)="s"))+sub(" .",1+(sub(Str1,length(Str1),1)="."),1


问:
Cities: Sightlines
I'm at position (0, 0) of an infinite two-dimensional city, which is perfectly divided into blocks centered at each lattice point, some of which contain buildings. A building at a certain point (x, y) takes up the entire square with opposite corners at (x-.5, y-.5) and  (x+.5, y+.5), including its border. A building is visible iff there is some line segment from (0, 0) to a point in the building which does not intersect any other building.

For example, I (the @) can see 6 buildings (*) in the following city:

```<code>  *
 *
*
*@
x**
 *  y
</code>```

I can't see the building marked with an x, at (-1, -1) because it's obstructed by the two adjacent to it; or the one marked with a y at (3, -2) because it's obstructed by the edge of the (1, -1) building.

Input

A multiline string, or list of lines, optionally padded with spaces into a rectangle. It will contain only:

a single @ (my position)

Spaces

*, which represent buildings.

There will always be at least one building, and therefore at least one visible building.

Output

The number of visible buildings.

Test cases

```<code>*@
1

* *******
 @     *
7

*****
**@**
*****
4

   *
  **
@ **
2

*      *
 *    *
@
4

@
 *
  ***
1
</code>```

Thanks to @Geobits for the title.

答:
Unity + C#, 589 bytes

This is probably the worst language to do a code golf in (read: worse than Java), but Unity comes with a lot a helpful features for this challenge.

EDIT: missed a couple of spaces, returns list length, not counter

Golfed:

```<code>using UnityEngine;using System.Collections;public class c:MonoBehaviour{public int h(string[]i){ArrayList k=new ArrayList();for(int y=0;y<i.Length;y++){char[]l=i[y].ToCharArray();int x=0;foreach(char c in l){if(c=='*'){GameObject b=GameObject.CreatePrimitive(PrimitiveType.Cube);b.transform.position=new Vector3(x,y);}if(c=='@')transform.position=new Vector3(x,y);x++;}}for(int n=0;n<3600;n++){RaycastHit h;Physics.Raycast(transform.position,Quaternion.Euler(0,0,n/10)*Vector3.up,out h);if(h.collider!=null){GameObject o=h.collider.gameObject;if(!k.Contains(o))k.Add(o);}}return k.Count;}}
</code>```

Ungolfed:

```<code>using UnityEngine;
using System.Collections;

public class citiessightlines : MonoBehaviour {

    public ArrayList todelete;   // Anything concerning this array just has to do with cleanup of
                                 //objects for testing, and doesn't contribute to the byte count.
    void Start()
    {
        todelete = new ArrayList();
    }
    public int calcSight(string[]input)
    {
        todelete = new ArrayList();
        int total = 0;
        ArrayList check = new ArrayList();
        for (int y=0;y < input.Length; y++)
        {
            char[] line = input[y].ToCharArray();
            for (int x = 0; x < line.Length; x++)
            {
                char c = line[x];
                if (c == '*')
                {
                    GameObject cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
                    cube.transform.position = new Vector3(x, y);
                    todelete.Add(cube);
                }
                if (c == '@')
                {
                    transform.position = new Vector3(x, y);
                }
            }
        }
        for (int angle=0; angle < 3600; angle++)
        {
            RaycastHit hit;
            Physics.Raycast(transform.position, Quaternion.Euler(0, 0, angle/10) * Vector3.up, out hit);
            if (hit.collider!=null)
            {
                GameObject hitObject = hit.collider.gameObject;
                if (!check.Contains(hitObject)&&hitObject!=this)
                {
                    total += 1;
                    check.Add(hitObject);
                }
           }
        }
        return total;
    }
}
</code>```

I used 3600 raycasts because it fails the 5th test case with lower. It still might fail for even larger/more precise test cases.

Unfortunately, both webgl and desktop builds seem to break, so all I have is the source code to test with on github.

Title: Cities: Sightlines

Body:
Unity + C#, 589 bytes

This is probably the worst language to do a code golf in (read: worse than Java), but Unity comes with a lot a helpful features for this challenge.

EDIT: missed a couple of spaces, returns list length, not counter

Golfed:

using UnityEngine;using System.Collections;public class c:MonoBehaviour{public int h(string[]i){ArrayList k=new ArrayList();for(int y=0;y<i.Length;y++){char[]l=i[y].ToCharArray();int x=0;foreach(char c in l){if(c=='*'){GameObject b=GameObject.CreatePrimitive(PrimitiveType.Cube);b.transform.position=new Vector3(x,y);}if(c=='@')transform.position=new Vector3(x,y);x++;}}for(int n=0;n<3600;n++){RaycastHit h;Physics.Raycast(transform.position,Quaternion.Euler(0,0,n/10)*Vector3.up,out h);if(h.collider!=null){GameObject o=h.collider.gameObject;if(!k.Contains(o))k.Add(o);}}return k.Count;}}

Ungolfed:

using UnityEngine;
using System.Collections;

public class citiessightlines : MonoBehaviour {

    public ArrayList todelete;   // Anything concerning this array just has to do with cleanup of
                                 //objects for testing, and doesn't contribute to the byte count.
    void Start()
    {
        todelete = new ArrayList();
    }
    public int calcSight(string[]input)
    {
        todelete = new ArrayList();
        int total = 0;
        ArrayList check = new ArrayList();
        for (int y=0;y < input.Length; y++)
        {
            char[] line = input[y].ToCharArray();
            for (int x = 0; x < line.Length; x++)
            {
                char c = line[x];
                if (c == '*')
                {
                    GameObject cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
                    cube.transform.position = new Vector3(x, y);
                    todelete.Add(cube);
                }
                if (c == '@')
                {
                    transform.position = new Vector3(x, y);
                }
            }
        }
        for (int angle=0; angle < 3600; angle++)
        {
            RaycastHit hit;
            Physics.Raycast(transform.position, Quaternion.Euler(0, 0, angle/10) * Vector3.up, out hit);
            if (hit.collider!=null)
            {
                GameObject hitObject = hit.collider.gameObject;
                if (!check.Contains(hitObject)&&hitObject!=this)
                {
                    total += 1;
                    check.Add(hitObject);
                }
           }
        }
        return total;
    }
}

I used 3600 raycasts because it fails the 5th test case with lower. It still might fail for even larger/more precise test cases.

Unfortunately, both webgl and desktop builds seem to break, so all I have is the source code to test with on github.


问:
Ain't there nothing up my sleeves

Note: reference to Nothing up my sleeve number.

Your task is to take no input and generate this exact output:

d76aa478 e8c7b756 242070db c1bdceee f57c0faf 4787c62a a8304613 fd469501
698098d8 8b44f7af ffff5bb1 895cd7be 6b901122 fd987193 a679438e 49b40821
f61e2562 c040b340 265e5a51 e9b6c7aa d62f105d 02441453 d8a1e681 e7d3fbc8
21e1cde6 c33707d6 f4d50d87 455a14ed a9e3e905 fcefa3f8 676f02d9 8d2a4c8a
fffa3942 8771f681 6d9d6122 fde5380c a4beea44 4bdecfa9 f6bb4b60 bebfbc70
289b7ec6 eaa127fa d4ef3085 04881d05 d9d4d039 e6db99e5 1fa27cf8 c4ac5665
f4292244 432aff97 ab9423a7 fc93a039 655b59c3 8f0ccc92 ffeff47d 85845dd1
6fa87e4f fe2ce6e0 a3014314 4e0811a1 f7537e82 bd3af235 2ad7d2bb eb86d391
```
<p>A trailing newline is optional.</p>
<p>The MD5 hash for the version <strong>with</strong> trailing newline is:</p>
<ul>
<li><code>FC1D37B5295177E7F28509EC9197688F</code></li>
</ul>
<p>The MD5 hash for the version <strong>without</strong> trailing newline is:</p>
<ul>
<li><code>FAC194EC5EFD2E5A5AC07C2A4925699B</code></li>
</ul>
<h3>How the string is generated</h3>
<p>Those 64 strings are actually the 64 hexadecimal numbers used in the MD5 hash.</p>
<p>The pseudocode for them:</p>
<pre class="lang-python prettyprint-override"><code>numbers = floor(2^32 × abs(sin(i))) for i in [1,2,...,64]
</code>```

The reference Python code:

from math import*
for i in range(8):print" ".join("{:08x}".format(int(abs(2**32*sin(-~j))))for j in range(8*i,8*i+8))
```
<p>Ungolfed:</p>
<pre class="lang-python prettyprint-override"><code>from math import*
for i in range(8):
    temp = []
    for j in range(8*i,8*i+8):
        temp += ["{:08x}".format(int(abs(2**32*sin(j+1))))]
    print " ".join(temp)
</code>```

答:
Python 2, <s>86</s> <s>77</s> 76 bytes

import math
n=0;exec(",\nn+=1;print'%08x'%(2**32*abs(math.sin(n)))"*8)[1:]*8
```

<p>Test it on Ideone.</p>

<h3>How it works</h3>

<p>Python 2's <code>print</code> statement has a quirk: It appends a newline to the result of its expression, unless it is followed by a trailing <code>,</code>; in this case, it appends a space. While that's usually annoying when golfing (as there's no short way to print without trailing whitespace), it's perfect for this task.</p>

<p>We repeat the string <code>,\nn+=1;print'%08x'%(2**32*abs(math.sin(n)))</code> eight times, chop off the leading comma with <code>[1:]</code>, and repeat the result eight times. The string that <code>exec</code> executes composed of eight identical copies of the following code.</p>

<pre class="lang-python prettyprint-override"><code>
n+=1;print'%08x'%(2**32*abs(math.sin(n))),
n+=1;print'%08x'%(2**32*abs(math.sin(n))),
n+=1;print'%08x'%(2**32*abs(math.sin(n))),
n+=1;print'%08x'%(2**32*abs(math.sin(n))),
n+=1;print'%08x'%(2**32*abs(math.sin(n))),
n+=1;print'%08x'%(2**32*abs(math.sin(n))),
n+=1;print'%08x'%(2**32*abs(math.sin(n))),
n+=1;print'%08x'%(2**32*abs(math.sin(n)))
</code>```

Each line increments the variable n (initialized by n=0), applies the format string %08x (lowercase hexadecimal representation, left-padded with zeroes to length 8, of the integer part of its argument) to 232 times the absolute value of the sine of n, and prints the resulting string either with a trailing space or a trailing linefeed.

Title: Ain't there nothing up my sleeves

Body:
Python 2, <s>86</s> <s>77</s> 76 bytes

import math
n=0;exec(",\nn+=1;print'%08x'%(2**32*abs(math.sin(n)))"*8)[1:]*8

Test it on Ideone.

How it works

Python 2's print statement has a quirk: It appends a newline to the result of its expression, unless it is followed by a trailing ,; in this case, it appends a space. While that's usually annoying when golfing (as there's no short way to print without trailing whitespace), it's perfect for this task.

We repeat the string ,\nn+=1;print'%08x'%(2**32*abs(math.sin(n))) eight times, chop off the leading comma with [1:], and repeat the result eight times. The string that exec executes composed of eight identical copies of the following code.

n+=1;print'%08x'%(2**32*abs(math.sin(n))),
n+=1;print'%08x'%(2**32*abs(math.sin(n))),
n+=1;print'%08x'%(2**32*abs(math.sin(n))),
n+=1;print'%08x'%(2**32*abs(math.sin(n))),
n+=1;print'%08x'%(2**32*abs(math.sin(n))),
n+=1;print'%08x'%(2**32*abs(math.sin(n))),
n+=1;print'%08x'%(2**32*abs(math.sin(n))),
n+=1;print'%08x'%(2**32*abs(math.sin(n)))

Each line increments the variable n (initialized by n=0), applies the format string %08x (lowercase hexadecimal representation, left-padded with zeroes to length 8, of the integer part of its argument) to 232 times the absolute value of the sine of n, and prints the resulting string either with a trailing space or a trailing linefeed.


答:
C: <s>113 </s> 111 — based on other C answer.

This is a complete program with main. The input list is the argument list.

Old style C is used, but with the C99 fmod function.

```
<s>q(char*n){double m=0;while(*n)m+=*n++-48;return!fmod(sqrt(m),1);}main(c,v)char**v;{while(*++v)if(q(*v))puts(*v);}</s>
q(char*n){double m=0;while(*n)m+=*n++-48;return!fmod(sqrt(m),1);}main(c,v)char**v;{while(*++v)q(*v)&&puts(*v);}
```

Run:

```
$ gcc golf.c -o golf -lm
golf.c:1:1: warning: data definition has no type or storage class [enabled by default]
golf.c: In function ‘q’:
golf.c:1:52: warning: incompatible implicit declaration of built-in function ‘fmod’ [enabled by default]
golf.c:1:57: warning: incompatible implicit declaration of built-in function ‘sqrt’ [enabled by default]
$ ./golf 1 4 9 16 25 1111
1
4
9
1111
$ ./golf
$ ./golf 421337 99 123456 1133557799
$```

Title: Return the integers with square digit-sums

Body:
Introduction and Credit

We all know and love our awesome rules to test whether a number is divisble by 11 or 3, which is just some clever sum over the digits of the number. Now this challenge takes this to a new level, by requiring you to compute the sum of the digits and then checking whether the result is a perfect integer square, neither of which operations usually can be done very short. As this property is also very hard to see when looking at a number, we want this to be done for entire lists of numbers so we can save human work. So this is your challenge now!

This was an assignment at my university functional programming course. This assignment is now closed and has been discussed in class and I have my professor's permission to post it here (I asked explicitely).

Specification

Input

Your input is a list of non-negative integers, in any standard I/O format.

You may choose the list format as your language needs it

Output

The output is a list of integers, in any standard I/O format.

What to do?

Filter out every integer from the input list for which the sum of the digits is not a a square (of an integer).

The order of the elements may not be changed, e.g. if you get [1,5,9] you may not return [9,1]

Potential corner cases

0 is a non-negative integer and thus a valid input and 0 is also a valid integer root, e.g. 0 counts as an integer square.

The empty list is a valid input and output as well.

Who wins?

This is code-golf so the shortest answer in bytes wins!

Standard rules apply of course.

Test Cases

```<code>[1,4,9,16,25,1111] -> [1,4,9,1111]
[1431,2,0,22,999999999] -> [1431,0,22,999999999]
[22228,4,113125,22345] -> [22228,4,22345]
[] -> []
[421337,99,123456789,1133557799] -> []
</code>```

Step-by-Step Example

```<code>Example input: [1337,4444]
Handling first number:
Sum of the digits of 1337: 1+3+3+7=14
14 is not an integer square, thus will be dropped!
Handling second number:
Sum of the digits of 4444: 4+4+4+4=16
16 is an integer square because 4*4=16, can get into the output list!
Example output: [4444]
</code>```

Body:
C: <s>113 </s> 111 — based on other C answer.

This is a complete program with main. The input list is the argument list.

Old style C is used, but with the C99 fmod function.

<s>q(char*n){double m=0;while(*n)m+=*n++-48;return!fmod(sqrt(m),1);}main(c,v)char**v;{while(*++v)if(q(*v))puts(*v);}</s>
q(char*n){double m=0;while(*n)m+=*n++-48;return!fmod(sqrt(m),1);}main(c,v)char**v;{while(*++v)q(*v)&&puts(*v);}

Run:

$ gcc golf.c -o golf -lm
golf.c:1:1: warning: data definition has no type or storage class [enabled by default]
golf.c: In function ‘q’:
golf.c:1:52: warning: incompatible implicit declaration of built-in function ‘fmod’ [enabled by default]
golf.c:1:57: warning: incompatible implicit declaration of built-in function ‘sqrt’ [enabled by default]
$ ./golf 1 4 9 16 25 1111
1
4
9
1111
$ ./golf
$ ./golf 421337 99 123456 1133557799
$


问:
Sum It Up with a Digital Triangle
Well, sum it down really.

Write a program or function that takes in a nonempty list of decimal integers (0-9) and outputs a downward pointing "triangle" of digits with the input list at the top where every digit after the first line is the sum of the two digits above it modulo 10.

For example, the input [7, 5, 0, 9] has output

```<code>7 5 0 9
 2 5 9
  7 4
   1
</code>```

because 2 is (7 + 5) mod 10, 5 is (5 + 0) mod 10, 9 is (0 + 9) mod 10, etc. all the way to 1 being (7 + 4) mod 10.

If the list has only one item, then the output matches the input; e.g. an input of [4] will yield

```<code>4
</code>```

Here are some additional examples:

```<code>[0]

0

[1, 2]

1 2
 3

[8, 7]

8 7
 5

[0, 0]

0 0
 0

[1, 4, 2]

1 4 2
 5 6
  1

[0, 1, 0]

0 1 0
 1 1
  2

[1, 0, 0, 0]

1 0 0 0
 1 0 0
  1 0
   1

[1, 2, 3, 4]

1 2 3 4
 3 5 7
  8 2
   0

[1, 2, 3, 5, 8]

1 2 3 5 8
 3 5 8 3
  8 3 1
   1 4
    5

[9, 2, 4, 5, 3, 2, 2]

9 2 4 5 3 2 2
 1 6 9 8 5 4
  7 5 7 3 9
   2 2 0 2
    4 2 2
     6 4
      0
</code>```

Note that in the output:

The first line does not have leading spaces.

Each subsequent line has one more leading space than the line previous.

Digits are separated by a single space.

Each line is allowed to have up to one trailing space.

There may be a single optional trailing newline.

You must use the characters for normal decimal digits (0 through 9).

The shortest code in bytes wins. Tiebreaker is earlier answer.

答:
C#, 167 bytes

Im actually pretty proud of this solution, lambda expressions are so fun once you get the hang of them

```<code>void f(List<int> a){int x=a.Count;for(int s=0;s<x;s++){Console.WriteLine(new String(' ',s)+string.Join(" ",a));a=a.Take(x-s-1).Select((v,i)=>(a[i+1]+v)%10).ToList();}}
</code>```

here ungolfed for further improvements:

```<code>void f(List<int> a)
{
int x = a.Count;
for (int s = 0; s<x ;s++)
{
    Console.WriteLine(new String(' ',s)+string.Join(" ",a));
    a=a.Take(x-s-1).Select((v,i)=>(a[i+1]+v)%10).ToList();
}
}
</code>```

try it out here

Title: Sum It Up with a Digital Triangle

Body:
C#, 167 bytes

Im actually pretty proud of this solution, lambda expressions are so fun once you get the hang of them

void f(List<int> a){int x=a.Count;for(int s=0;s<x;s++){Console.WriteLine(new String(' ',s)+string.Join(" ",a));a=a.Take(x-s-1).Select((v,i)=>(a[i+1]+v)%10).ToList();}}

here ungolfed for further improvements:

void f(List<int> a)
{
int x = a.Count;
for (int s = 0; s<x ;s++)
{
    Console.WriteLine(new String(' ',s)+string.Join(" ",a));
    a=a.Take(x-s-1).Select((v,i)=>(a[i+1]+v)%10).ToList();
}
}

try it out here


答:
CJam, 25 bytes

```<code>q~{_2ew::+Af%}h;]eeSff*N*
</code>```

Try it online!

Explanation

This uses a fairly neat trick to generate the triangle layout.

```<code>q~      e# Read and evaluate input.
{       e# While the list of digits is non-empty...
  _2ew  e#   Duplicate and get all sublists of length 2.
  ::+   e#   Sum each pair.
  Af%   e#   Take each result modulo 10.
}h
;]      e# Discard the final empty list and wrap the others in an array.
ee      e# Enumerate the array. E.g. for input `[7 5 0 9]` we now get this:
        e# [[0 [7 5 0 9]]
        e#  [1 [2 5 9]]
        e#  [2 [7 4]]
        e#  [3 [1]]]
Sff*    e# Perform S* on each element at depth two. For the integers from the
        e# enumeration this gives a string of that many spaces, i.e. the correct
        e# indentation. For the lists of digits this inserts a space character
        e# between every two digits, thereby spacing out the digits as necessary.
N*      e# Put linefeeds between the pairs of indentation and digit list.
</code>```

Title: Sum It Up with a Digital Triangle

Body:
Well, sum it down really.

Write a program or function that takes in a nonempty list of decimal integers (0-9) and outputs a downward pointing "triangle" of digits with the input list at the top where every digit after the first line is the sum of the two digits above it modulo 10.

For example, the input [7, 5, 0, 9] has output

```<code>7 5 0 9
 2 5 9
  7 4
   1
</code>```

because 2 is (7 + 5) mod 10, 5 is (5 + 0) mod 10, 9 is (0 + 9) mod 10, etc. all the way to 1 being (7 + 4) mod 10.

If the list has only one item, then the output matches the input; e.g. an input of [4] will yield

```<code>4
</code>```

Here are some additional examples:

```<code>[0]

0

[1, 2]

1 2
 3

[8, 7]

8 7
 5

[0, 0]

0 0
 0

[1, 4, 2]

1 4 2
 5 6
  1

[0, 1, 0]

0 1 0
 1 1
  2

[1, 0, 0, 0]

1 0 0 0
 1 0 0
  1 0
   1

[1, 2, 3, 4]

1 2 3 4
 3 5 7
  8 2
   0

[1, 2, 3, 5, 8]

1 2 3 5 8
 3 5 8 3
  8 3 1
   1 4
    5

[9, 2, 4, 5, 3, 2, 2]

9 2 4 5 3 2 2
 1 6 9 8 5 4
  7 5 7 3 9
   2 2 0 2
    4 2 2
     6 4
      0
</code>```

Note that in the output:

The first line does not have leading spaces.

Each subsequent line has one more leading space than the line previous.

Digits are separated by a single space.

Each line is allowed to have up to one trailing space.

There may be a single optional trailing newline.

You must use the characters for normal decimal digits (0 through 9).

The shortest code in bytes wins. Tiebreaker is earlier answer.

Body:
CJam, 25 bytes

q~{_2ew::+Af%}h;]eeSff*N*

Try it online!

Explanation

This uses a fairly neat trick to generate the triangle layout.

q~      e# Read and evaluate input.
{       e# While the list of digits is non-empty...
  _2ew  e#   Duplicate and get all sublists of length 2.
  ::+   e#   Sum each pair.
  Af%   e#   Take each result modulo 10.
}h
;]      e# Discard the final empty list and wrap the others in an array.
ee      e# Enumerate the array. E.g. for input `[7 5 0 9]` we now get this:
        e# [[0 [7 5 0 9]]
        e#  [1 [2 5 9]]
        e#  [2 [7 4]]
        e#  [3 [1]]]
Sff*    e# Perform S* on each element at depth two. For the integers from the
        e# enumeration this gives a string of that many spaces, i.e. the correct
        e# indentation. For the lists of digits this inserts a space character
        e# between every two digits, thereby spacing out the digits as necessary.
N*      e# Put linefeeds between the pairs of indentation and digit list.


问:
Same length sub arrays

Background:

Here's a little simple challenge. You want to be able to find out whether the arrays inside an array have the same length.

Input:

Your input should consist of exactly one array (this is the value passed to the function, not a user input). Your function takes exactly 1 parameter.  It could contain arrays or be empty. No error checking needed, assume only list is ever passed in. Assume a 1-D array such as [1] or [1,2,3,4,5] is never passed in.

Output:

Return true if all the list elements have the same length, false if they don't, and the parameter itself if the list is empty (or null if your language doesn't support multiple return types).

Some test cases:

```<code>List: [] - [] (or null/your language equivalent)
List: [[1], [1], [2]] - True
List: [[1]] - True
List: [[1, 2, 3, 4]] - True
List: [[1, 2, 3, 4, 5], [2], [12, 314123]] - False
List: [[1, 2, 3, 4], [1]] - False
</code>```

No std(in/out) input/output needed (however, it is allowed, just not required!), the function only needs to return boolean values true or false; or the parameter itself if the function is passed an empty list (or null/your language equivalent). Only one return value is returned.

Rules:

Shortest byte count wins, only function is necessary (full programs are allowed if you desire).

答:
C#, 80 bytes

Im checking length 4 times in this golf. i wish there was a better way to be honest.

```<code>bool f(List<int[]>a){return a.Where(m=>m.Length==a[0].Length).Count()==a.Count;}
</code>```

alternative version also 80 bytes..

```<code>bool f(List<int[]>a){return a.Where(m=>m.Length==a[0].Length).SequenceEqual(a);}
</code>```

Title: Same length sub arrays

Body:
C#, 80 bytes

Im checking length 4 times in this golf. i wish there was a better way to be honest.

bool f(List<int[]>a){return a.Where(m=>m.Length==a[0].Length).Count()==a.Count;}

alternative version also 80 bytes..

bool f(List<int[]>a){return a.Where(m=>m.Length==a[0].Length).SequenceEqual(a);}


问:
Approximation of e
We all know that the Euler's number, denoted by \$e\$, to the power of some variable \$x\$, can be approximated by using the Maclaurin Series expansion:

$$e^x=\sum_{k=0}^{\infty}{\frac{x^k}{k!}}=1+x+\frac{x^2}{2!}+\frac{x^3}{3!}+\frac{x^4}{4!}+\dots$$

By letting \$x\$ equal \$1\$, we obtain

$$\sum_{k=0}^{\infty}{\frac{1}{k!}{=\frac{1}{0!}+\frac{1}{1!}+\frac{1}{2!}+\frac{1}{3!}+\frac{1}{4!}+\dots\\=1+1+\frac{1}{2}+\frac{1}{6}+\frac{1}{24}+\dots}}$$

Challenge

Write a program in any language which approximates Euler's number by taking in an input \$n\$ and calculates the series to the \$n\$th term. Note that the first term has denominator \$0!\$, not \$1!\$, i.e. \$n=1\$ corresponds to \$\frac{1}{0!}\$.

Scoring

Program with least amount of bytes wins.

ContentLicense: CC BY-SA 4.0

Title: Approximation of e

Body:
Perl 5, 37 bytes

Not a winner, but nice and straightforward:

$e=$p=1;$e+=1/($p*=$_)for 1..<>;say$e

Outputs for inputs from 0 to 10:

1
2
2.5
2.66666666666667
2.70833333333333
2.71666666666667
2.71805555555556
2.71825396825397
2.71827876984127
2.71828152557319
2.71828180114638


Title: Display a cribbage score in ASCII

Body:
Cribbage is an interesting game, because you need a specific board to score your game.
A cribbage board looks like this:

Notice how the first column is on the left as it goes up, then on the right as it goes down, then back on the left as it goes up again.

And here is what a poorly <s>drawn</s> rendered ASCII art of a cribbage board looks like:

```<code>                     * * *
   -----------      -------
  /     *     \     |*|*|*|
 /*     *     *\    |*|*|*|
/   *   *   *   \   |*|*|*|
|     *   *     |   |*|*|*|
|* * *     * * *|   |*|*|*|
-------   -------   -------
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
-------   -------   -------
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
-------   -------   -------
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
-------   -------   -------
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
-------   -------   -------
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
-------   -------   -------
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
-------   -------   -------
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
-------   -------   -------
 * * *    |* * *     * * *|
          |     *   *     |
          \   *   *   *   /
           \*     *     */
            \     *     /
             -----------
</code>```

Here is your challenge:

Step 1: Draw this ASCII art of a cribbage board. Trailing whitespace is OK, provided that there is no visible difference.

Step 2: Given three integers as input, display each peg in the correct hole. The pegs can be 0-indexed or 1-indexed. The inputs will be in [0-121] inclusive. You can take these inputs in any reasonable manner, for example, 3 separate inputs, an array, command line arguments, etc. Here's an example for the input (0, 37, 100) (1-indexed):

```<code>                     * * *
   -----------      -------
  /     *     \     |*|*|*|
 /*     *     *\    |*|*|*|
/   2   *   *   \   |*|*|*|
|     *   *     |   |*|*|*|
|* * *     * * *|   |*|*|*|
-------   -------   -------
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
-------   -------   -------
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
-------   -------   -------
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
-------   -------   -------
|*|*|*|   |*|*|*|   |*|*|3|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
-------   -------   -------
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
-------   -------   -------
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
-------   -------   -------
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
-------   -------   -------
 1 * *    |* * *     * * *|
          |     *   *     |
          \   *   *   *   /
           \*     *     */
            \     *     /
             -----------
</code>```

Step 3: Output the whole thing.

Test IO:

Since each of these is pretty vertically tall, I will only include 2, but you can see more at this github gist.

```<code>#Input: (56, 56, 56)
#Output:
                     * * *
   -----------      -------
  /     *     \     |*|*|*|
 /*     *     *\    |*|*|*|
/   *   *   *   \   |*|*|*|
|     *   *     |   |*|*|*|
|* * *     * * *|   |*|*|*|
-------   -------   -------
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
-------   -------   -------
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
-------   -------   -------
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
-------   -------   -------
|*|*|*|   |3|2|1|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
-------   -------   -------
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
-------   -------   -------
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
-------   -------   -------
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
-------   -------   -------
 * * *    |* * *     * * *|
          |     *   *     |
          \   *   *   *   /
           \*     *     */
            \     *     /
             -----------

#Input: (120, 89, 23)
#Output:
                     * * *
   -----------      -------
  /     *     \     |1|*|*|
 /*     *     *\    |*|*|*|
/   *   *   *   \   |*|*|*|
|     *   *     |   |*|*|*|
|* * *     * * *|   |*|*|*|
-------   -------   -------
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
-------   -------   -------
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
-------   -------   -------
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|3|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
-------   -------   -------
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
-------   -------   -------
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
-------   -------   -------
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|2|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
-------   -------   -------
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
|*|*|*|   |*|*|*|   |*|*|*|
-------   -------   -------
 * * *    |* * *     * * *|
          |     *   *     |
          \   *   *   *   /
           \*     *     */
            \     *     /
             -----------
</code>```

Standard loopholes apply, and the shortest answer in bytes wins!

Body:
Python 2, 615 bytes

def f(a):
 D="-";S=" ";A=S*55+D+S;B="|/4 /41/4 - 2  -4-3   -|/4 /43/4 - 2  -4-1   -".replace("4","    ");C=B.replace("/","\\");s=t=u="";d={"1":0,"2":0,"3":0}
 for i in range(23):j=15>i>7;k=i-i/8;x=k%7*5;y=(6-k%7)*5;M=A+S*52+("123","321")[i<8]+D+S+A;N=chr((x,y)[j]/10+49);Q=("|"+N)[i%2]*5+D;s+=(S+S*5*(i<7)+C[x+39:x+34:-1]*j+B[y+39:y+34:-1]*(i>15)+("| "[i<7]+N)[i%2]+D+Q*(7+(i>15))+("|"+N)[i%2]+B[x:x+5]*(i<7)+C[y:y+5]*j+S*(i<16),(M[::-1],M)[i<8])[i%8==7]
 for x in s:
    if "4">x>"0":d[x]+=1;x=("*"+x)[d[x]==a[x]+1]
    t+=x
 for i in range(1512):j=i/27;k=i%27;u+=t[k*57+(56-j,j)[16>k>10and 51>j>5]]+"\n"*(k>25)
 print u

The function is called by passing in a dictionary that contains the scores.  For example:

f({"1":40, "2":70, "3":76})

The byte count reflects indenting the "for x" loop with tabs instead of spaces.

Explanation

The first loop builds the board horizontally into a 57x27 string, with track numbers instead of "holes".

       -|||||-|||||-|||||-|||||-|||||-|||||-|||||-||/
      1-11111-11111-11111-11111-11111-11111-11111-1  /
       -|||||-|||||-|||||-|||||-|||||-|||||-|||||-|  1/
      2-22222-22222-22222-22222-22222-22222-22222-2    -
       -|||||-|||||-|||||-|||||-|||||-|||||-|||||-| 2  -
      3-33333-33333-33333-33333-33333-33333-33333-3    -
       -|||||-|||||-|||||-|||||-|||||-|||||-|||||-|3   -
                                                       -
                                                    321-
                                                       -
    \||-|||||-|||||-|||||-|||||-|||||-|||||-|||||-|3   -
   \  3-33333-33333-33333-33333-33333-33333-33333-3    -
  \3  |-|||||-|||||-|||||-|||||-|||||-|||||-|||||-| 2  -
 -    2-22222-22222-22222-22222-22222-22222-22222-2    -
 -  2 |-|||||-|||||-|||||-|||||-|||||-|||||-|||||-|  1\
 -    1-11111-11111-11111-11111-11111-11111-11111-1  \
 -   1|-|||||-|||||-|||||-|||||-|||||-|||||-|||||-||\
 -
 -321
 -
 -   1|-|||||-|||||-|||||-|||||-|||||-|||||-|||||-|||||-|
 -    1-11111-11111-11111-11111-11111-11111-11111-11111-1
 -  2 |-|||||-|||||-|||||-|||||-|||||-|||||-|||||-|||||-|
 -    2-22222-22222-22222-22222-22222-22222-22222-22222-2
  /3  |-|||||-|||||-|||||-|||||-|||||-|||||-|||||-|||||-|
   /  3-33333-33333-33333-33333-33333-33333-33333-33333-3
    /||-|||||-|||||-|||||-|||||-|||||-|||||-|||||-|||||-|

The second loop copies the string, replacing the numbers with asterisks except at the scoring peg locations.  The peg locations in the straight lines in the middle of the track come out backward.

The third loop changes the orientation to vertical, correcting the pegs in the middle track and adding newline characters.

Try it here


问:
Solve Einstein's riddle
Einstein wrote a riddle. He said that 98% of the world could not solve it.

I solved this riddle in about 25 minutes while on the train to work.
It's basically just deduction.

The riddle

There are 5 houses in 5 different colors in a row.

In each house lives a person with a different nationality.

The 5 owners drink a certain type of beverage, smoke a certain brand of cigar, and keep a certain pet.

No owners have the same pet, smoke the same brand of cigar, or drink the same beverage.

Question: Who owns the fish?

To solve this riddle Einstein provides 15 hints:

The Brit lives in the red house.

The Swede keeps dogs as pets.

The Dane drinks tea.

The green house is on the immediate left of the white house.

The green house's owner drinks coffee.

The owner who smokes Pall Mall rears birds.

The owner of the yellow house smokes Dunhill.

The owner living in the center house drinks milk.

The Norwegian lives in the first house.

The owner who smokes Blends lives next to the one who keeps cats.

The owner who keeps the horse lives next to the one who smokes Dunhill.

The owner who smokes Bluemasters drinks beer.

The German smokes Prince.

The Norwegian lives next to the blue house.

The owner who smokes Blends lives next to the one who drinks water.

With these hints you can come to a solution.

Your task:
Make a program that will solve this riddle for you.
Hard coding the solution isn't allowed (duh)

It is allowed to hardcode the hints in any format.

Example format:

```<code>//Hints in order
(Nationality:Brit)==(Color:Red)
(Nationality:Swede)==(Pet:Dogs)
(Nationality:Dane)==(Drink: Tea)
(Color:Green)/(Color:White)
(Color:Green)==(Drink:Coffee)
(Smoke:PallMall)==(Pet:Birds)
(Color:Yellow)==(Smoke:Dunhill)
(House:3)==(Drink:Milk)
(Nationality:Norwegian)==(House:1)
(Smoke:Blend)/\(Pet:Cats)
</code>```

== means equals to

/ means on left side of

\ means on right side of

/\ means left or right of

Like I said its allowed to either hardcode hints or have them as input.

Output:
Output should be in the following format (With the correct values, just saying for the trolls ;) )

```<code> _____________    _____________    _____________    _____________    _____________
|   Number    |  |   Number    |  |   Number    |  |   Number    |  |   Number    |
| Nationality |  | Nationality |  | Nationality |  | Nationality |  | Nationality |
|    Color    |  |    Color    |  |    Color    |  |    Color    |  |    Color    |
|    Drink    |  |    Drink    |  |    Drink    |  |    Drink    |  |    Drink    |
|    Smoke    |  |    Smoke    |  |    Smoke    |  |    Smoke    |  |    Smoke    |
|     Pet     |  |     Pet     |  |     Pet     |  |     Pet     |  |     Pet     |
---------------  ---------------  ---------------  ---------------  ---------------

The <Nationality> in the <Color> house owns the fish!
</code>```

Ascii art boxes can be changed by you, as long as they are boxes, doesn't matter what symbols you use.

Any knowledge on this riddle and solution can not be used in the program.
It should use pure logic and deduction to solve the riddle.

Tagged this as a codegolf but might be a code challenge, not sure.
Any thoughts on winning criteria for a code challenge feel free to share :)

For now this is code-golf so the program with the lowest bytecount wins.

Good luck and Happy coding :)

Title: Solve Einstein's riddle

Body:
Prolog, 653 characters

a([],L,L).
a([H|T],L2,[H|L3]):-a(T,L2,L3).
m(X,L):-a(_,[X|_],L).
r(X,Y,L):-a(_,[X,Y|_],L).
n(X,Y,L):-r(X,Y,L);r(Y,X,L).
s:-s(S),w(S).
s(S):-length(S,5),m([b,r,_,_,_],S),m([s,_,_,_,d],S),m([d,_,t,_,_],S),r([_,g,_,_,_],[_,w,_,_,_],S),m([_,g,c,_,_],S),m([_,_,_,p,b],S),m([_,y,_,d,_],S),S=[_,_,[_,_,m,_,_],_,_],S=[[n,_,_,_,_],_,_,_,_],n([_,_,_,b,_],[_,_,_,_,c],S),n([_,_,_,d,_],[_,_,_,_,h],S),m([_,_,b,l,_],S),m([g,_,_,r,_],S),n([n,_,_,_,_],[_,b,_,_,_],S),n([_,_,_,b,_],[_,_,w,_,_],S),m([_,_,_,_,f],S).
b:-write('----------------+'),nl.
z(Y,A):-write(Y),writef('|%2L|%2L|%2L|%2L|%2L|',A),nl.
w([S1,S2,S3,S4,S5]):-b,z(1,S1),z(2,S2),z(3,S3),z(4,S4),z(5,S5),b.


答:
Wistful-C - 336 bytes

My first real wistful- program! There is actually a little golfing I did, with using someday instead of wait for because the first had a shorter length.

```<code>if only <stdio.h> were included...
if only int f were 1...
if only int N were 0...
wish for "%d",&N upon a star
if only int i were 0...
if only double e were 0...
someday i will be N...
        if only e were e+1./f...
        if only i were i+1...
        if only f were f*i...
*sigh*
wish "%f\n",e upon a star
if wishes were horses...
</code>```

Title: Approximation of e

Body:
We all know that the Euler's number, denoted by \$e\$, to the power of some variable \$x\$, can be approximated by using the Maclaurin Series expansion:

$$e^x=\sum_{k=0}^{\infty}{\frac{x^k}{k!}}=1+x+\frac{x^2}{2!}+\frac{x^3}{3!}+\frac{x^4}{4!}+\dots$$

By letting \$x\$ equal \$1\$, we obtain

$$\sum_{k=0}^{\infty}{\frac{1}{k!}{=\frac{1}{0!}+\frac{1}{1!}+\frac{1}{2!}+\frac{1}{3!}+\frac{1}{4!}+\dots\\=1+1+\frac{1}{2}+\frac{1}{6}+\frac{1}{24}+\dots}}$$

Challenge

Write a program in any language which approximates Euler's number by taking in an input \$n\$ and calculates the series to the \$n\$th term. Note that the first term has denominator \$0!\$, not \$1!\$, i.e. \$n=1\$ corresponds to \$\frac{1}{0!}\$.

Scoring

Program with least amount of bytes wins.

Body:
Wistful-C - 336 bytes

My first real wistful- program! There is actually a little golfing I did, with using someday instead of wait for because the first had a shorter length.

if only <stdio.h> were included...
if only int f were 1...
if only int N were 0...
wish for "%d",&N upon a star
if only int i were 0...
if only double e were 0...
someday i will be N...
        if only e were e+1./f...
        if only i were i+1...
        if only f were f*i...
*sigh*
wish "%f\n",e upon a star
if wishes were horses...


Title: Display a cribbage score in ASCII

Body:
Batch, <s>1302</s> <s>1099</s> <s>1096</s> 1079 bytes

@set s= set
@%s%o=echo
@%o%off
%s%x=41
%s%y=35
%s%z=121
%s%m=-------
%s%w=
%s%p=if %1==
%s%q=if %2==
%s%r=if %3==
%s%l=call:l
%l%
%o%%w%%w%%w%%w% %g% %h% %i%
%o%   %m%---- %w%%m%
%l%
%p%38%s%j=1
%o%  /%w%%j%%w%\  %n%
%l%
%q%38%s%j=2
%o% /%f%%w%%j%%w%%a%\ %n%
%l%
%q%37%s%j=2
%q%39%s%k=2
%o%/   %j%   %c%   %k%   \%n%
%l%
%o%^|%w%%c%   %d%%w%^|%n%
%l%
%o%^|%a% %b% %c%%w%%d% %e% %f%^|%n%
%l%
for /l %%a in (1,1,7)do call:b
%o%%m%   %m%   %m%
%o% %a% %b% %c%    ^|%d% %e% %f%%w%%g% %h% %i%^|
%l%
%o%%w%%w%^|%w%%f%   %g%%w%^|
%l%
%q%77%s%j=2
%q%79%s%k=2
%o%%w%%w%\   %j%   %g%   %k%   /
%l%
%q%78%s%j=2
%o%%w%%w% \%i%%w%%j%%w%%d%/
%r%78%s%j=3
%o%%w%%w%  \%w%%j%%w%/
%o%%w%%w%   %m%----
exit/b
:b
%o%%m%   %m%   %m%
for /l %%a in (1,1,4)do call:o
:o
%o%^|%a%^|%b%^|%c%^|   ^|%d%^|%e%^|%f%^|%n%
:l
for %%a in (a b c d e f g h i j k) do%s%%%a=*
%p%%x%%s%a=1
%q%%x%%s%b=2
%r%%x%%s%c=3
%r%%y%%s%d=3
%q%%y%%s%e=2
%p%%y%%s%f=1
%p%%z%%s%g=1
%q%%z%%s%h=2
%r%%z%%s%i=3
%s%n=   ^^^|%g%^^^|%h%^^^|%i%^^^|
set/ax-=1,y+=1,z-=1

Ungolfed:

@echo off
@rem values that pegs at the very top of each column would be
set x=41
set y=35
set z=121
rem deal with the four custom pegs on the top curve
call :loop
echo                      %g% %h% %i%
echo    -----------      -------
call :loop
if %1==38 (set j=1) else set j=*
echo   /     %j%     \     ^|%g%^|%h%^|%i%^|
call :loop
if %2==38 (set j=2) else set j=*
echo  /%f%     %j%     %a%\    ^|%g%^|%h%^|%i%^|
call :loop
if %2==37 (set j=2) else set j=*
if %2==39 (set k=2) else set k=*
echo /   %j%   %c%   %k%   \   ^|%g%^|%h%^|%i%^|
call :loop
echo ^|     %c%   %d%     ^|   ^|%g%^|%h%^|%i%^|
call :loop
echo ^|%a% %b% %c%     %d% %e% %f%^|   ^|%g%^|%h%^|%i%^|
call :loop
rem deal with the 7 sets of 5 standard rows
call :block
call :block
call :block
call :block
call :block
call :block
call :block
rem deal with the four custom pegs on the bottom curve
echo -------   -------   -------
echo  %a% %b% %c%    ^|%d% %e% %f%     %g% %h% %i%^|
call :loop
echo           ^|     %f%   %g%     ^|
call :loop
if %2==77 (set j=2) else set j=*
if %2==79 (set k=2) else set k=*
echo           \   %j%   %g%   %k%   /
call :loop
if %2==78 (set j=2) else set j=*
echo            \%i%     %j%     %d%/
if %3==78 (set j=3) else set j=*
echo             \     %j%     /
echo              -----------
exit/b
:block
echo -------   -------   -------
call :output
call :output
call :output
call :output
:output
rem prints each of the 35 main rows
echo ^|%a%^|%b%^|%c%^|   ^|%d%^|%e%^|%f%^|   ^|%g%^|%h%^|%i%^|
:loop
rem check for pegs in the current row, also works for some of the curve
if %1==%x% (set a=1) else set a=*
if %2==%x% (set b=2) else set b=*
if %3==%x% (set c=3) else set c=*
if %3==%y% (set d=3) else set d=*
if %2==%y% (set e=2) else set e=*
if %1==%y% (set f=1) else set f=*
if %1==%z% (set g=1) else set g=*
if %2==%z% (set h=2) else set h=*
if %3==%z% (set i=3) else set i=*
rem decrement the first and third columns, increment the second column
set/a x-=1
set/a y+=1
set/a z-=1


问:
Stack Exchange Vote Counter
Write a program/function that returns the vote count of its own Stack Exchange answer at the time of its execution.

Your program/function may access this page (codegolf.stackexchange.com/questions/82609) off the internet, however:

Your program/function may not accept any user input and

The use of URL shorteners is not allowed

Your program/function may use only its own source as a reference point to its vote count (for example: no referencing strings of text in its contained answer but not in its own source)

Your program/function must output its own vote count and only its own vote count (for example: no returning all vote counts on this page)

This is code-golf, shortest code wins.

答:
Convex 0.5, 63 bytes

```<code>0000000: 22 d1 2e 46 91 32 e5 69 5d b2 66 81 12 a4 8d d1  "..F.2.i].f.....
0000010: 27 40 b5 32 47 68 97 2c b9 5c 22 05 16 49 10 31  '@.2Gh.,.\"..I.1
0000020: 44 9e f3 0a 6a 16 b0 68 91 93 35 0b 96 dc 91 0a  D...j..h..5.....
0000030: 3c 18 80 22 dc 67 27 3c 2f 32 36 39 3d 37 3e     <..".g'</269=7>
</code>```

This retrieves the score from the search page instead of the API, specifically from the query https://codegolf.stackexchange.com/search?q=inquestion:82714. Fortunately, inquestion also works for answers.

Verification

```<code>$ echo $LANG
en_US
$ cat gen.convex
"codegolf.stackexchange.com:80/search?q=inquestion:82714"Ö`"Üg'</269=7>"
$ java -jar Convex/out/builds/convex-0.5/convex/convex.jar gen.conv > count.conv
$ cksum count.conv
2414634109 63 count.conv
$ java -jar Convex/out/builds/convex-0.5/convex/convex.jar count.conv
1
</code>```

How it works

```<code>"..."Ü           e# Use the built-in string compression to push
                 e# "codegolf.stackexchange.com:80/search?q=inquestion:82714".
      g          e# Retrieve the HTML page at that URL.
       '</       e# Split at occurrences of '<'.
          269=   e# Select the chunk at index 269.
                 e# This pushes "strong>", followed by the vote count.
              7> e# Discard the leading seven characters.
</code>```

Title: Stack Exchange Vote Counter

Body:
Convex 0.5, 63 bytes

0000000: 22 d1 2e 46 91 32 e5 69 5d b2 66 81 12 a4 8d d1  "..F.2.i].f.....
0000010: 27 40 b5 32 47 68 97 2c b9 5c 22 05 16 49 10 31  '@.2Gh.,.\"..I.1
0000020: 44 9e f3 0a 6a 16 b0 68 91 93 35 0b 96 dc 91 0a  D...j..h..5.....
0000030: 3c 18 80 22 dc 67 27 3c 2f 32 36 39 3d 37 3e     <..".g'</269=7>

This retrieves the score from the search page instead of the API, specifically from the query https://codegolf.stackexchange.com/search?q=inquestion:82714. Fortunately, inquestion also works for answers.

Verification

$ echo $LANG
en_US
$ cat gen.convex
"codegolf.stackexchange.com:80/search?q=inquestion:82714"Ö`"Üg'</269=7>"
$ java -jar Convex/out/builds/convex-0.5/convex/convex.jar gen.conv > count.conv
$ cksum count.conv
2414634109 63 count.conv
$ java -jar Convex/out/builds/convex-0.5/convex/convex.jar count.conv
1

How it works

"..."Ü           e# Use the built-in string compression to push
                 e# "codegolf.stackexchange.com:80/search?q=inquestion:82714".
      g          e# Retrieve the HTML page at that URL.
       '</       e# Split at occurrences of '<'.
          269=   e# Select the chunk at index 269.
                 e# This pushes "strong>", followed by the vote count.
              7> e# Discard the leading seven characters.


问:
Write a program that reverses the name of its source file
In a single file, write a program that requires no input and produces no output. When run it should reverse the name of the file it is contained in, regardless of what the name is, without altering the code or producing other lasting side effects.

Any way of achieving this is fine. It only matters that once the program is run the only lasting change is that its file name has been reversed. e.g. no new files should be in the directory.

Running the program again should reverse the name back. Indeed, the program should be able to be run arbitrarily many times.

For the purposes of this challenge:

You may assume filenames are always strings of lowercase letters (a-z) between 1 and 127 characters long. (If your language requires files to have extensions to run then just reverse the part before the extension, e.g. mycode.bat → edocym.bat.)

You may assume the code file is in a directory by itself so it will not have naming conflicts (except with itself).

You may not assume the filename is not a palindrome, i.e. the same when reversed. Filenames that are palindromes should work just as well as those that aren't.

You may read your file's contents or metadata. There are no quine restrictions here.

You may assume your program will be run on a particular, modern, commonplace operating system (e.g. Windows/Linux), since not all shells have the same command set.

As a concrete example, say you have a Python program in a file called
  mycode in its own directory. Running

```<code>python mycode
</code>```

in the terminal should result in the filename being reversed to
  edocym. The file edocym should be alone in its directory - no file
  named mycode should exist anymore. Running

```<code>python edocym
</code>```

will reverse the name back to mycode, at which point the process can
  be repeated indefinitely.

If the same Python file was renamed racecar (without changing the code) and then run

```<code>python racecar
</code>```

nothing should visibly change since "racecar" is a palindrome.
  That same goes if the filename were, say, a or xx.

The shortest code in bytes wins. Tiebreaker is higher voted answer.

答:
JavaScript ES6 (Node.js) 70 Bytes

No Regex Yay!

```<code>require("fs").rename(a=__filename,[...a].reverse().join``.split`/`[0])
</code>```

Any help is appreciated

Body:
JavaScript ES6 (Node.js) 70 Bytes

No Regex Yay!

require("fs").rename(a=__filename,[...a].reverse().join``.split`/`[0])

Any help is appreciated


问:
Detect Duplicate Questions

Detect Duplicate Questions

Once upon a time, there was a golfing site. It had a problem: people would post similar or identical questions again and again. You have been chosen selected forced conscripted blackmailed requested to automate the process of deciding whether a question is a duplicate of an existing one, by whatever means necessary (see Rules).

Input

Your program must accept a single URL as input. It may assume that this leads to a question on codegolf.stackexchange.com.

Output

Search the site for similar questions. If you think that the input question is a duplicate of an existing question (or vice versa), output the other question's URL. You may output multiple URLs, separated by new lines. At the end of your output, output end (on a separate line).

Scoring

If a question that you output was indeed marked as a duplicate of the input question (or vice versa), you score 4 points. This is a "correct guess".

For each false positive (aka "incorrect guess"), you lose 2 points.

For each question that was actually a duplicate but does not appear in your output (aka "missing guess"), lose 1 point.

The highest score after handling 32 input questions wins. These 32 questions are a "round". At the beginning of each round, the scores will be reset to 0. One round will be run every few days, and the leaderboard updated after each round.

Rules

If questions A and C are both closed as duplicates of B, A will count as a duplicate of C and vice versa.

At the start of each round, your program may not possess any data about any questions (i.e. no hardcoding), except on how to parse the website.

However, you may keep data in external files during a round.

No data may be kept between rounds.

Your output must have a trailing new line.

You may not use any data from the website except search results and the URL, title, tags and text of a question, with or without formatting. For example, you may not use the text "marked as duplicate by foo, bar..." that appears on duplicate questions.

You may retrieve this data directly from the site, via data.SE or via the API.

Each submission must have a name.

Each submission must have clear version numbering.

If a submission does not produce output after a time limit (to be decided; please state how long your submission takes) it will be killed and lose 8 points.

答:
Python 3

I am giving this entry the name The Differ.

Code:

```<code>import urllib.request, gzip, re, json, difflib, sys
API_URL = "https://api.stackexchange.com/"
qurl = input()
qid = int(re.search("\d+",qurl).group(0))
def request(url,wrapper=False,**params):
    params.setdefault("filter","withbody")
    params.setdefault("site","codegolf")
    url = API_URL + url + "?"+"&".join([str(k)+"="+str(v) for k,v in params.items()])
    compressed_response = urllib.request.urlopen(url)
    response = gzip.decompress(compressed_response.read()).decode("utf8")
    response_object = json.loads(response)
    if wrapper:
        return response_object
    else:
        return response_object["items"]
question = request("questions/%s"%qurl)[0]
tags = ";".join(question["tags"])
title = question["title"]
escaped = title.replace(" ","%20")
related = request("similar",title=escaped,pagesize=100)
hasmore = False
length = sys.maxsize
for tag in question["tags"]:
    result = request("search",tagged=tag,
                     wrapper=True,
                     filter="!-*f(6rc.cI8O",
                     pagesize=100)
    if result["total"] < length:
        length = result["total"]
        related.extend(result["items"])
        hasmore = result["has_more"]
        besttag = tag
related.extend(best)
if length < 1500:
    for page in itertools.count(2):
        if not hasmore:
            break
        response = request("search",
                           tagged=besttag,
                           page=page,
                           pagesize=100,
                           filter="!-*f(6rc.cI8O",
                           wrapper=True)
        hasmore = response["has_more"]
        related.extend(result["items"])
matcher = difflib.SequenceMatcher(None, question["body"], None)
titlematcher = difflib.SequenceMatcher(None, question["title"], None)
seen = set()
seen.add(question["question_id"])
for possible in related:
    matcher.set_seq2(possible["body"])
    titlematcher.set_seq2(possible["title"])
    score = matcher.ratio()+titlematcher.ratio()
    qid = possible["question_id"]
    if score > .85 and qid not in seen:
        print(qid)
        seen.add(qid)
print("end")
</code>```

The filter "!-*f(6rc.cI8O" included the total parameter on the global wrapper object and the body parameter on questions.

This entry makes two API requests plus one per tag on the question plus one per hundred questions in its least used tag. If it hits an api throttle (which it doesn't check for), it will raise an urllib.error.HTTPError: HTTP Error 400: Bad Request

Title: Detect Duplicate Questions

Body:
Python 3

I am giving this entry the name The Differ.

Code:

import urllib.request, gzip, re, json, difflib, sys
API_URL = "https://api.stackexchange.com/"
qurl = input()
qid = int(re.search("\d+",qurl).group(0))
def request(url,wrapper=False,**params):
    params.setdefault("filter","withbody")
    params.setdefault("site","codegolf")
    url = API_URL + url + "?"+"&".join([str(k)+"="+str(v) for k,v in params.items()])
    compressed_response = urllib.request.urlopen(url)
    response = gzip.decompress(compressed_response.read()).decode("utf8")
    response_object = json.loads(response)
    if wrapper:
        return response_object
    else:
        return response_object["items"]
question = request("questions/%s"%qurl)[0]
tags = ";".join(question["tags"])
title = question["title"]
escaped = title.replace(" ","%20")
related = request("similar",title=escaped,pagesize=100)
hasmore = False
length = sys.maxsize
for tag in question["tags"]:
    result = request("search",tagged=tag,
                     wrapper=True,
                     filter="!-*f(6rc.cI8O",
                     pagesize=100)
    if result["total"] < length:
        length = result["total"]
        related.extend(result["items"])
        hasmore = result["has_more"]
        besttag = tag
related.extend(best)
if length < 1500:
    for page in itertools.count(2):
        if not hasmore:
            break
        response = request("search",
                           tagged=besttag,
                           page=page,
                           pagesize=100,
                           filter="!-*f(6rc.cI8O",
                           wrapper=True)
        hasmore = response["has_more"]
        related.extend(result["items"])
matcher = difflib.SequenceMatcher(None, question["body"], None)
titlematcher = difflib.SequenceMatcher(None, question["title"], None)
seen = set()
seen.add(question["question_id"])
for possible in related:
    matcher.set_seq2(possible["body"])
    titlematcher.set_seq2(possible["title"])
    score = matcher.ratio()+titlematcher.ratio()
    qid = possible["question_id"]
    if score > .85 and qid not in seen:
        print(qid)
        seen.add(qid)
print("end")

The filter "!-*f(6rc.cI8O" included the total parameter on the global wrapper object and the body parameter on questions.

This entry makes two API requests plus one per tag on the question plus one per hundred questions in its least used tag. If it hits an api throttle (which it doesn't check for), it will raise an urllib.error.HTTPError: HTTP Error 400: Bad Request


问:
Turn an Array into a Math Problem
Given a nonempty list of nonnegative integers, consider rewriting it as an arithmetic problem where:

A plus sign (+) is inserted between pairs of numbers that increase from left to right (a.k.a. from the start of the list to the end).

A minus sign (-) is inserted between pairs of numbers that decrease from left to right.

A multiplication sign (*) is inserted between pairs of numbers that are equal.

Said another way: any sublist a,b becomes a+b if a<b, a-b if  a>b, and a*b if a==b.

For example, the list

```<code>[12, 0, 7, 7, 29, 10, 2, 2, 1]
</code>```

would become the expression

```<code>12 - 0 + 7*7 + 29 - 10 - 2*2 - 1
</code>```

which evaluates to 75.

Write a program or function that takes in such a list and evaluates it, printing or returning the result.

Order of operations matters. Multiplications should be done before any addition or subtraction.

If the input list has one number, that should be what it evaluates to. e.g. [64] should give 64.

Use of eval or exec or similar constructs is allowed.

Here are some additional examples:

```<code>[list]
expression
value

[0]
0
0

[1]
1
1

[78557]
78557
78557

[0,0]
0*0
0

[1,1]
1*1
1

[2,2]
2*2
4

[0,1]
0+1
1

[1,0]
1-0
1

[1,2]
1+2
3

[2,1]
2-1
1

[15,4,4]
15-4*4
-1

[9,8,1]
9-8-1
0

[4,2,2,4]
4-2*2+4
4

[10,9,9,12]
10-9*9+12
-59

[1,1,2,2,3,3]
1*1+2*2+3*3
14

[5,5,4,4,3,3]
5*5-4*4-3*3
0

[3,1,4,1,5,9,2,6,5,3,5,9]
3-1+4-1+5+9-2+6-5-3+5+9
29

[7637,388,389,388,387,12,0,0,34,35,35,27,27,2]
7637-388+389-388-387-12-0*0+34+35*35-27*27-2
7379
</code>```

The shortest code in bytes wins. Tiebreaker is earlier answer.

答:
Pyth, <s>31</s> <s>26</s> <s>19</s> <s>17</s> <s>16</s> 15 bytes

Expressions with * won't evaluate online, but they would theoretically work.

2 bytes thanks to Maltysen.

```<code>vsm+@"*-+"._-~k
</code>```

Test suite (with evaluation).

The other cases (without evaluation).

History

31 bytes: M+G@"*-+"->GH<GHv+sgMC,JsMQtJ\x60e

26 bytes: M+G@"*-+"->GH<GHv+sgVQtQ\x60e

19 bytes: vtssVm@"*-+"->Zd<~Z

17 bytes: vtssVm@"*-+"._-~Z

16 bytes: vssVm@"*-+"._-~k

15 bytes: vsm+@"*-+"._-~k

Title: Turn an Array into a Math Problem

Body:
Pyth, <s>31</s> <s>26</s> <s>19</s> <s>17</s> <s>16</s> 15 bytes

Expressions with * won't evaluate online, but they would theoretically work.

2 bytes thanks to Maltysen.

vsm+@"*-+"._-~k

Test suite (with evaluation).

The other cases (without evaluation).

History

31 bytes: M+G@"*-+"->GH<GHv+sgMC,JsMQtJ\x60e

26 bytes: M+G@"*-+"->GH<GHv+sgVQtQ\x60e

19 bytes: vtssVm@"*-+"->Zd<~Z

17 bytes: vtssVm@"*-+"._-~Z

16 bytes: vssVm@"*-+"._-~k

15 bytes: vsm+@"*-+"._-~k


答:
Python 2, 63 bytes

p=s='print-'
for x in input():s+='*+-'[cmp(x,p)]+`x`;p=x
exec s
```

Constructs and evals the expression string. The arithmetic symbol is chosen by comparing the previous number p to the current one x. The symbol is appended followed by the current number.

The first number is handled with a clever trick from Sp3000. The initial value of p is set to a string, which is bigger than any number and therefore causes a - before the first number. But, s is initialized to print- at the same time that makes the result start with print-- (thanks to xsot for saving 2 bytes by initializing with print.)

Title: Turn an Array into a Math Problem

Body:
Given a nonempty list of nonnegative integers, consider rewriting it as an arithmetic problem where:

A plus sign (+) is inserted between pairs of numbers that increase from left to right (a.k.a. from the start of the list to the end).

A minus sign (-) is inserted between pairs of numbers that decrease from left to right.

A multiplication sign (*) is inserted between pairs of numbers that are equal.

Said another way: any sublist a,b becomes a+b if a<b, a-b if  a>b, and a*b if a==b.

For example, the list

```<code>[12, 0, 7, 7, 29, 10, 2, 2, 1]
</code>```

would become the expression

```<code>12 - 0 + 7*7 + 29 - 10 - 2*2 - 1
</code>```

which evaluates to 75.

Write a program or function that takes in such a list and evaluates it, printing or returning the result.

Order of operations matters. Multiplications should be done before any addition or subtraction.

If the input list has one number, that should be what it evaluates to. e.g. [64] should give 64.

Use of eval or exec or similar constructs is allowed.

Here are some additional examples:

```<code>[list]
expression
value

[0]
0
0

[1]
1
1

[78557]
78557
78557

[0,0]
0*0
0

[1,1]
1*1
1

[2,2]
2*2
4

[0,1]
0+1
1

[1,0]
1-0
1

[1,2]
1+2
3

[2,1]
2-1
1

[15,4,4]
15-4*4
-1

[9,8,1]
9-8-1
0

[4,2,2,4]
4-2*2+4
4

[10,9,9,12]
10-9*9+12
-59

[1,1,2,2,3,3]
1*1+2*2+3*3
14

[5,5,4,4,3,3]
5*5-4*4-3*3
0

[3,1,4,1,5,9,2,6,5,3,5,9]
3-1+4-1+5+9-2+6-5-3+5+9
29

[7637,388,389,388,387,12,0,0,34,35,35,27,27,2]
7637-388+389-388-387-12-0*0+34+35*35-27*27-2
7379
</code>```

The shortest code in bytes wins. Tiebreaker is earlier answer.

Body:
Python 2, 63 bytes

p=s='print-'
for x in input():s+='*+-'[cmp(x,p)]+`x`;p=x
exec s

Constructs and evals the expression string. The arithmetic symbol is chosen by comparing the previous number p to the current one x. The symbol is appended followed by the current number.

The first number is handled with a clever trick from Sp3000. The initial value of p is set to a string, which is bigger than any number and therefore causes a - before the first number. But, s is initialized to print- at the same time that makes the result start with print-- (thanks to xsot for saving 2 bytes by initializing with print.)


答:
, 7 chars / 9 bytes

```<code>Мū…⩤⁽1ï
</code>```

Try it here (ES6 only).

Just a LCM of inclusive range from 1 to input.

Title: Pseudofactorial

Body:
There is a rather curious number which shows up sometimes in math problems or riddles. The pseudofactorial(N) is the least (i.e. lowest) common multiple of the numbers 1 through N; in other words, it's the lowest number which has all numbers from 1 through N as factors.

For instance pseudofactorial(7) = 3 * 4 * 5 * 7, which is the same as 7! except that 2 and 6 have been removed because they are contained in other terms.

Write a program to calculate pseudofactorial(N) and as always, shortest code wins.

Here is a short list for your use. More test cases can be found in the OEIS under A003418.

Factorial:

1

2

6

24

120

720

5040

Pseudofactorial:

1

2

6

12

60

60

420

Body:
, 7 chars / 9 bytes

Мū…⩤⁽1ï

Try it here (ES6 only).

Just a LCM of inclusive range from 1 to input.


答:
Pyth - <s>23</s> <s>22</s> 20 bytes

As with Kenny's, multiplication doesn't work online.

```<code>vs.i+\+@L"*+-"._M-Vt
</code>```

Test Suite without doing eval.

Title: Turn an Array into a Math Problem

Body:
Pyth - <s>23</s> <s>22</s> 20 bytes

As with Kenny's, multiplication doesn't work online.

vs.i+\+@L"*+-"._M-Vt

<a href="http://pyth.herokuapp.com/?code=s.i%2B%5C%2B%40L%22%2a%2B-%22._M-Vt&test_suite=1&test_suite_input=%5B0%5D%0A%5B1%5D%0A%5B78557%5D+%0A%5B0%2C0%5D%0A%5B1%2C1%5D%0A%5B2%2C2%5D%0A%5B0%2C1%5D%0A%5B1%2C0%5D%0A%5B1%2C2%5D%0A%5B2%2C1%5D%0A%5B15%2C4%2C4%5D%0A%5B9%2C8%2C1%5D%0A%5B4%2C2%2C2%2C4%5D%0A%5B10%2C9%2C9%2C12%5D%0A%5B1%2C1%2C2%2C2%2C3%2C3%5D%0A%5B5%2C5%2C4%2C4%2C3%2C3%5D%0A%5B3%2C1%2C4%2C1%2C5%2C9%2C2%2C6%2C5%2C3%2C5%2C9%5D%0A%5B7637%2C388%2C389%2C388%2C387%2C12%2C0%2C0%2C34%2C35%2C35%2C27%2C27%2C2%5D&debug=0" rel="nofollow noreferrer">Test Suite without doing eval.


答:
TI-BASIC, 146 bytes

I'll format it nicely when not on mobile. Sleep escapes me, so you get this. Enjoy.

```<code>Prompt L₁
"(→Str1
For(A,1,dim(L₁
{0,1→L₂
{0,L₁(A→L₃
LinReg(ax+b) L₁,L₃,Y₁
Equ►String(Y₁,Str2
sub(Str2,1,-1+inString(Str2,"X→Str2
If A>1
Then
L₁(A-1
2+(Ans>L₁(A))-(Ans<L₁(A
Str1+sub("+*-",Ans,1→Str1
End
Str1+Str2→Str2
End
expr(Str1
</code>```

Title: Turn an Array into a Math Problem

Body:
TI-BASIC, 146 bytes

I'll format it nicely when not on mobile. Sleep escapes me, so you get this. Enjoy.

Prompt L₁
"(→Str1
For(A,1,dim(L₁
{0,1→L₂
{0,L₁(A→L₃
LinReg(ax+b) L₁,L₃,Y₁
Equ►String(Y₁,Str2
sub(Str2,1,-1+inString(Str2,"X→Str2
If A>1
Then
L₁(A-1
2+(Ans>L₁(A))-(Ans<L₁(A
Str1+sub("+*-",Ans,1→Str1
End
Str1+Str2→Str2
End
expr(Str1


答:
Jelly, <s>18</s> <s>16</s> <s>15</s> 14 bytes

```<code>I0;ð1g×⁹⁸œṗP€S
</code>```

Uses no built-in eval. Try it online! or verify all test cases.

How it works

```<code>I0;ð1g×⁹⁸œṗP€S  Main link. Input: A (list)

I               Increments; compute the deltas of all adjacent items of A.
 0;             Prepend a 0.
   ð            Begin a new, dyadic chain.
                Left argument: D (0 plus deltas). Right argument: A
    1g          Compute the GCD of 1 and each item in D.
                This yields 1 for non-negative items, -1 for negative ones.
      ×⁹        Multiply each 1 or -1 with the corresponding item of A.
                This negates every item in A that follows a - sign.
        ⁸œṗ     Partition the result by D. This splits at occurrences of non-zero
                values of D, grouping items with identical absolute value.
           P€   Take the product of each group.
             S  Sum; add the results.
</code>```

Title: Turn an Array into a Math Problem

Body:
Jelly, <s>18</s> <s>16</s> <s>15</s> 14 bytes

I0;ð1g×⁹⁸œṗP€S

Uses no built-in eval. Try it online! or verify all test cases.

How it works

I0;ð1g×⁹⁸œṗP€S  Main link. Input: A (list)

I               Increments; compute the deltas of all adjacent items of A.
 0;             Prepend a 0.
   ð            Begin a new, dyadic chain.
                Left argument: D (0 plus deltas). Right argument: A
    1g          Compute the GCD of 1 and each item in D.
                This yields 1 for non-negative items, -1 for negative ones.
      ×⁹        Multiply each 1 or -1 with the corresponding item of A.
                This negates every item in A that follows a - sign.
        ⁸œṗ     Partition the result by D. This splits at occurrences of non-zero
                values of D, grouping items with identical absolute value.
           P€   Take the product of each group.
             S  Sum; add the results.


问:
Generate combinations with replacement
List all of the combinations with replacement (or combinations with repetition) of size k from a set of n elements.

A combination with replacement is an unordered multiset that every element in it are also in the set of n elements. Note that:

It is unordered. So a previously printed set with a different order shouldn't be printed again.

It is a multiset. The same element can (but isn't required to) appear more than once. This is the only difference between a combination with replacement and a normal combination.

The set should have exactly k elements.

Alternatively, it is also a size-k subset of the multiset which contains each of the n elements k times.

The input should be either n and k, where the elements are the first n positive or non-negative integers, or the n elements and k, where you can assume the n elements are all different from each other.

The output should be a list of all the combinations with replacement with size k from the given set. You can print them and the elements in each of them in any order.

You may not use builtins generating combinations with replacement. But you can use builtins to generate normal combinations, permutations, tuples, etc.

This is code-golf, shortest code wins.

Example

```<code>Input: 4 2
Output: [0 0] [0 1] [0 2] [0 3] [1 1] [1 2] [1 3] [2 2] [2 3] [3 3]
</code>```

答:
J, 18 bytes

```<code>[:~.#~<@/:~@#:i.@^
</code>```

Similar approach used in @Adám's solution.

Another approach using Cartesian product { for 24 bytes. Takes k on the LHS and n on the RHS.

```<code>~.@:(/:~&.>)@,@{@(#<@i.)
</code>```

Usage

```<code>   f =: [:~.#~<@/:~@#:i.@^
   4 f 2
┌───┬───┬───┬───┬───┬───┬───┬───┬───┬───┐
│0 0│0 1│0 2│0 3│1 1│1 2│1 3│2 2│2 3│3 3│
└───┴───┴───┴───┴───┴───┴───┴───┴───┴───┘
</code>```

Explanation

```<code>[:~.#~<@/:~@#:i.@^ Input: n on LHS and k on RHS
                 ^ Compute n^k
              i.@  Create a range [0, 1, ... n^k-1]
    #~             Create k copies on n
            #:     On each value in the range above, convert each digit to base-n
                   and take the last k digits of it
        /:~@       For each array of digits, sort it in ascending order
      <@           Box each array of digits
[:~.               Take the distinct values in the array of boxes and return it
</code>```

Title: Generate combinations with replacement

Body:
J, 18 bytes

[:~.#~<@/:~@#:i.@^

Similar approach used in @Adám's solution.

Another approach using Cartesian product { for 24 bytes. Takes k on the LHS and n on the RHS.

~.@:(/:~&.>)@,@{@(#<@i.)

Usage

   f =: [:~.#~<@/:~@#:i.@^
   4 f 2
┌───┬───┬───┬───┬───┬───┬───┬───┬───┬───┐
│0 0│0 1│0 2│0 3│1 1│1 2│1 3│2 2│2 3│3 3│
└───┴───┴───┴───┴───┴───┴───┴───┴───┴───┘

Explanation

[:~.#~<@/:~@#:i.@^ Input: n on LHS and k on RHS
                 ^ Compute n^k
              i.@  Create a range [0, 1, ... n^k-1]
    #~             Create k copies on n
            #:     On each value in the range above, convert each digit to base-n
                   and take the last k digits of it
        /:~@       For each array of digits, sort it in ascending order
      <@           Box each array of digits
[:~.               Take the distinct values in the array of boxes and return it


答:
CJam, 20

```<code>q~e`{~_W-g\:W@#*}%:+
</code>```

Try it online

Explanation:

```<code>q~       read and evaluate the input (array of numbers)
e`       RLE encode, obtaining [count number] pairs
{…}%     map each pair
  ~_     dump the count and number on the stack, and duplicate the number
  W-     subtract the previous number (W is initially -1 by default)
  g      get the sign of the result
  \      swap with the other copy of the number
  :W     store it in W (for next iteration)
  @#     bring the count to the top, and raise the number to that power
  *      multiply with the sign
:+       add all the results together
</code>```

Title: Turn an Array into a Math Problem

Body:
CJam, 20

q~e`{~_W-g\:W@#*}%:+

Try it online

Explanation:

q~       read and evaluate the input (array of numbers)
e`       RLE encode, obtaining [count number] pairs
{…}%     map each pair
  ~_     dump the count and number on the stack, and duplicate the number
  W-     subtract the previous number (W is initially -1 by default)
  g      get the sign of the result
  \      swap with the other copy of the number
  :W     store it in W (for next iteration)
  @#     bring the count to the top, and raise the number to that power
  *      multiply with the sign
:+       add all the results together


Title: Turn an Array into a Math Problem

Body:
Java, 384 bytes

int s(int[]l){int n=l[0],m;for(int i=0;i<l.length-1;i++)if(l[i]<l[i+1])if(i<l.length-2&&l[i+1]!=l[i+2])n+=l[i+1];else{m=l[i+1];while(i<l.length-2&&l[i+1]==l[i+2])m*=l[(i++)+1];n+=m;}else if(l[i]>l[i+1])if(i<l.length-2&&l[i+1]!=l[i+2])n-=l[i+1];else{m=l[i+1];while(i<l.length-2&&l[i+1]==l[i+2])m*=l[(i++)+1];n-=m;}else{m=l[i];while(i<l.length-1&&l[i]==l[i+1])m*=l[i++];n+=m;}return n;}

Ungolfed try online

int s(int[] l)
{
    int n=l[0], m;

    for(int i=0; i<l.length-1; i++)
    {
        if(l[i] < l[i+1])
        {
            if (i<l.length-2 && l[i+1]!=l[i+2])
            {
                n += l[i+1];
            }
            else
            {
                m = l[i+1];
                while(i<l.length-2 && l[i+1]==l[i+2]) m *= l[(i++)+1];
                n += m;
            }
        }
        else if(l[i] > l[i+1])
        {
            if (i<l.length-2 && l[i+1]!=l[i+2])
            {
                n -= l[i+1];
            }
            else
            {
                m = l[i+1];
                while(i<l.length-2 && l[i+1]==l[i+2]) m *= l[(i++)+1];
                n -= m;
            }
        }
        else
        {
            m = l[i];
            while(i<l.length-1 && l[i]==l[i+1]) m *= l[i++];
            n += m;
        }
    }

    return n;
}