问:
Visualize long addition with ASCII art
Totally not inspired by Visualize long division with ASCII art ;)

Your job is to show long hand addition with ASCII art. You solve longhand addition by adding up the columns right to left, placing the value of the ones place in the result, and carrying the tens place over to the top of the next column.

Input

Input can come basically in any format you want, just as long as you take from 2 to 9 numbers as input.

Output

The formatting here likely matches how you learned it in school:

```<code>carry row
 number1
 number2
     ...
+   numX
--------
  result
</code>```

You can have just about any amount of trailing whitespace you want here ;)

Examples

```<code>50, 50

1
 50
+50
---
100

1651, 9879

1111
 1651
+9879
-----
11530

6489789, 9874, 287

   1122
 6489789
    9874
+    287
--------
 6499950
</code>```

答:
JavaScript (ES6), 199 bytes

```<code>a=>[[...t=` `+a.reduce((t,n)=>t+n)].map((_,i)=>a.reduce((c,n)=>c-n[i],90+t[i])%10||` `),a=a.map(n=>(` `.repeat(l=t.length)+n).slice(-l))).join``,...a,`-`.repeat(l),t].join`\n`.replace(/ (?=.*\n-)/,`+`)
</code>```

Where the first \n represents a literal newline character, while the second one is a two-character regexp escape sequence. Explanation:

```<code>a=>[                            Accept an array of numbers
 [...                           Split the total into digits
  t=` `+a.reduce((t,n)=>t+n)    Calculate the total and add a space
 ].map((_,i)=>a.reduce((c,n)=>  For each column
  c-n[i],90+t[i])               Subtract the column from the total
  %10||` `),                    Deduce the carry that was needed
  a=a.map(n=>                   For each input value
   (` `.repeat(l=t.length)+n)   Pad to the length of the total
    .slice(-l))                 Remove excess padding
 ).join``,                      Join the carries together
 ...a,                          Append the padded input values
 `-`.repeat(l),                 Append the dividing line
 t].join`\n`                    Append the total and join together
  .replace(/ (?=.*\n-)/,`+`)    Insert the + on the line above the -
</code>```

The carry calculation works by taking the total digit, prefixing 90, subtracting all the input value digits in that column, and taking the result modulo 10. (The prefix is 90 rather than 9 so that the leading column generates a blank carry space.)

Title: Visualize long addition with ASCII art

Body:
JavaScript (ES6), 199 bytes

a=>[[...t=` `+a.reduce((t,n)=>t+n)].map((_,i)=>a.reduce((c,n)=>c-n[i],90+t[i])%10||` `),a=a.map(n=>(` `.repeat(l=t.length)+n).slice(-l))).join``,...a,`-`.repeat(l),t].join`\n`.replace(/ (?=.*\n-)/,`+`)

Where the first \n represents a literal newline character, while the second one is a two-character regexp escape sequence. Explanation:

a=>[                            Accept an array of numbers
 [...                           Split the total into digits
  t=` `+a.reduce((t,n)=>t+n)    Calculate the total and add a space
 ].map((_,i)=>a.reduce((c,n)=>  For each column
  c-n[i],90+t[i])               Subtract the column from the total
  %10||` `),                    Deduce the carry that was needed
  a=a.map(n=>                   For each input value
   (` `.repeat(l=t.length)+n)   Pad to the length of the total
    .slice(-l))                 Remove excess padding
 ).join``,                      Join the carries together
 ...a,                          Append the padded input values
 `-`.repeat(l),                 Append the dividing line
 t].join`\n`                    Append the total and join together
  .replace(/ (?=.*\n-)/,`+`)    Insert the + on the line above the -

The carry calculation works by taking the total digit, prefixing 90, subtracting all the input value digits in that column, and taking the result modulo 10. (The prefix is 90 rather than 9 so that the leading column generates a blank carry space.)


问:
Stock Time Machine

Stock Time Machine

You've gained access to a dataset, tomorrowStocks, which contains the stock prices from your favorite business on the NASDAQ. This dataset is a container indexed by minutes past opening. Each index contains the price of the stock at that time.

```<code>// Assume the stock market opens at 9:30AM EDT
// tomorrowStocks[] contains the prices of your target stock.
// If the stock is $22 @ 10:30AM EDT
tomorrowStocks[60] == 22
</code>```

Output

Your task is to determine the best possible outcome of 1 purchase and 1 sale of 1 stock from the given dataset.

Gotchas

You must buy and sell exactly 1 stock.

You may not buy and sell in the same time slot.

You must buy before you sell.

Test Data

```<code>[1,2,3,4,5]    # 4
[1,99,2,105]   # 104
[99,1,99,100]  # 99
[99,1,1,2,1,3] # 2
[5,4,3,3,1]    # 0
[5,4,3,1]      # -1
[5,2,1]        # -1
[5,4,1]        # -1
[55,45,20,1]   # -10
[5,1]          # -4
[10,7,5,1]     # -2
[7]            # Invalid input -- assume size >= 2
</code>```

This is a code-golf; submit the shortest answer in your favorite language!

答:
Clojure, 99 bytes

```<code>(fn[x](apply max(map #(-(apply max(% 1))(apply min(% 0)))(map #(split-at % x)(range 1(count x))))))
</code>```

Splits input list at first position then second and so on, so we get a list which looks like this:

[[[n1][n2 ... nk]][[n1 n2][n3 ... nk]]...[[n1...n(k-1)][nk]]] then for each pair subtracts minimum of the first elements from max of the second element and then find max from them. Would be shorter if Clojure's min max were taking sequences rather than any number of arguments.

See it online: https://ideone.com/b2nllT

ContentLicense: CC BY-SA 3.0

Title: Stock Time Machine

Body:
Clojure, 99 bytes

(fn[x](apply max(map #(-(apply max(% 1))(apply min(% 0)))(map #(split-at % x)(range 1(count x))))))

Splits input list at first position then second and so on, so we get a list which looks like this:

[[[n1][n2 ... nk]][[n1 n2][n3 ... nk]]...[[n1...n(k-1)][nk]]] then for each pair subtracts minimum of the first elements from max of the second element and then find max from them. Would be shorter if Clojure's min max were taking sequences rather than any number of arguments.

See it online: https://ideone.com/b2nllT


问:
#Hashtag_or_not
In this code golf challenge, you will verify hashtags!

#What_your_code_should_do

Input is a string. Output a truthy value if it is a valid hashtag, and a falsy value otherwise.

We define a string as a valid Hashtag if ...

It starts with a hash (#).

It doesn't have a number right after the hashtag (e.g. #2016USElection isn't a  valid hashtag).

It doesn't have any "special characters" (i.e. any character that isn't an alphabet, underscore (_) or a number).

You can assume that the input only contains ASCII characters. (It would be unfair if we did Unicode too.)

#Rules

Basic code-golf rules apply.

#Examples

Truthy:

```<code>#
#e
#_ABC
#thisisanunexpectedlylongstringxoxoxoxo
#USElection2016
</code>```

Falsy:

```<code>Hello, World!
#12thBday
#not-valid
#alsoNotValid!
#!not_a_hash
</code>```

答:
Retina, 12 bytes

```<code>^#(?!\d)\w*$
</code>```

Prints 1 for hashtags and 0 otherwise.

Try it online! (The first line enables a linefeed-separated test suite.)

Not much to explain here, this is quite a literal implementation of the definition: ^ and $ are just anchors ensuring that the match covers the entire string, # checks that the string starts with a #, (?!\d) ensures that the next character isn't a digit (without advancing the regex engine's position), \w* checks that we can reach the end of the string with zero or more letters, digits or underscores.

By default, Retina counts the number of matches of the given regex, which is why this gives 1 for valid hash tags and 0 otherwise.

Title: #Hashtag_or_not

Body:
Retina, 12 bytes

^#(?!\d)\w*$

Prints 1 for hashtags and 0 otherwise.

Try it online! (The first line enables a linefeed-separated test suite.)

Not much to explain here, this is quite a literal implementation of the definition: ^ and $ are just anchors ensuring that the match covers the entire string, # checks that the string starts with a #, (?!\d) ensures that the next character isn't a digit (without advancing the regex engine's position), \w* checks that we can reach the end of the string with zero or more letters, digits or underscores.

By default, Retina counts the number of matches of the given regex, which is why this gives 1 for valid hash tags and 0 otherwise.


答:
05AB1E, 18 bytes

Code:

```<code>¬'#Qs¦A«¬d_sDžjKQP
</code>```

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

Title: #Hashtag_or_not

Body:
In this code golf challenge, you will verify hashtags!

#What_your_code_should_do

Input is a string. Output a truthy value if it is a valid hashtag, and a falsy value otherwise.

We define a string as a valid Hashtag if ...

It starts with a hash (#).

It doesn't have a number right after the hashtag (e.g. #2016USElection isn't a  valid hashtag).

It doesn't have any "special characters" (i.e. any character that isn't an alphabet, underscore (_) or a number).

You can assume that the input only contains ASCII characters. (It would be unfair if we did Unicode too.)

#Rules

Basic code-golf rules apply.

#Examples

Truthy:

```<code>#
#e
#_ABC
#thisisanunexpectedlylongstringxoxoxoxo
#USElection2016
</code>```

Falsy:

```<code>Hello, World!
#12thBday
#not-valid
#alsoNotValid!
#!not_a_hash
</code>```

Body:
05AB1E, 18 bytes

Code:

¬'#Qs¦A«¬d_sDžjKQP

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


问:
Fibonacci reversed!

Introduction

We all know and love our Fibonacci sequence and have seen a myriad of challenge on it here already. However, we're still lacking a very simple case which this answer is going to provide: Reversed fibonacci! So given F_n your job is to find n.

Specification

Input

Your input will be a non-negative integer, which is guaranteed to be part of the fibonacci sequence.

Output

The output must be a non-negative integer as well.

What to do?

The introduction already said: Given a fibonacci number, output its index. Fiboancci number hereby is defined as F(0)=0, F(1)=1, F(n)=F(n-1)+F(n-2) and you're given F(n) and must return n.

Potential Corner Cases

0 is a valid in- and output.

If given "1" as input you may either output "1" or "2", as you prefer.

You may always assume that your input actually is a fibonacci number.

You may assume that the input is representable as a 32-bit signed integer.

Who wins?

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

Standard rules apply of course.

Test-cases

```<code>0 -> 0
2 -> 3
3 -> 4
5 -> 5
8 -> 6
13 -> 7
1836311903 -> 46
</code>```

答:
C, 62 58 bytes

g(c,a,b){return c-a?g(c,b,a+b)+1:0;}f(c){return g(c,0,1);}
```

<p><strong>Detailed</strong></p>

<pre class="lang-C prettyprint-override"><code>int g(int c, int a, int b)
{
    if (c == a)
    {
        return 0;
    }
    else
    {
        return g(c, b, a+b) + 1;
    }
}

int f(c)
{
    return g(c, 0, 1);
}
</code>```

Title: Fibonacci reversed!

Body:
C, 62 58 bytes

g(c,a,b){return c-a?g(c,b,a+b)+1:0;}f(c){return g(c,0,1);}

Detailed

int g(int c, int a, int b)
{
    if (c == a)
    {
        return 0;
    }
    else
    {
        return g(c, b, a+b) + 1;
    }
}

int f(c)
{
    return g(c, 0, 1);
}


答:
Java 8, <s>57</s> <s>54</s> 28 bytes

```<code>s->s.matches("#(?!\\d)\\w*")
</code>```

Port of Martin Ender's Retina answer to save a few bytes and match added test cases.

Not that String#matches always matches the entire String, so no need for ^...$.

Try it here.

Title: #Hashtag_or_not

Body:
Java 8, <s>57</s> <s>54</s> 28 bytes

s->s.matches("#(?!\\d)\\w*")

Port of Martin Ender's Retina answer to save a few bytes and match added test cases.

Not that String#matches always matches the entire String, so no need for ^...$.

Try it here.


答:
Mathematica, <s>52</s> <s>46</s> 43 bytes

Saved <s>6</s> 9 bytes due to @MartinEnder.

```<code>StringMatchQ@RegularExpression@"#(?!\d)\w*"
</code>```

Function. Takes a string as input, and returns True or False as output. Pretty simple, just matches against the regex /#(?!\d)\w*/.

Title: #Hashtag_or_not

Body:
Mathematica, <s>52</s> <s>46</s> 43 bytes

Saved <s>6</s> 9 bytes due to @MartinEnder.

StringMatchQ@RegularExpression@"#(?!\d)\w*"

Function. Takes a string as input, and returns True or False as output. Pretty simple, just matches against the regex /#(?!\d)\w*/.


答:
Python3 - 156 128 bytes

```<code>lambda n:n=="#"or(n[0]=="#")*all(any([47<ord(c)<58,64<ord(c)<91,ord(c)==95,96<ord(c)<123])for c in n[1:]+"0")*~(47<ord(n[1])<58)
</code>```

A solution that doesn't use regex. 0 is falsey and every other value is truthy.

Thanks to @LeakyNun for saving bytes!

Title: #Hashtag_or_not

Body:
Python3 - 156 128 bytes

lambda n:n=="#"or(n[0]=="#")*all(any([47<ord(c)<58,64<ord(c)<91,ord(c)==95,96<ord(c)<123])for c in n[1:]+"0")*~(47<ord(n[1])<58)

A solution that doesn't use regex. 0 is falsey and every other value is truthy.

Thanks to @LeakyNun for saving bytes!


答:
Perl, 22 bytes

21 bytes code +1 for -p

$_=/^#([a-z_]\w*)?$/i
```

<p>Prints 1 if it's a valid hashtag, empty string otherwise.</p>

<h3>Usage</h3>

<pre class="lang-sh prettyprint-override"><code>perl -pe '$_=/^#([a-z_]\w*)?$/i' <<< '#'
1
perl -pe '$_=/^#([a-z_]\w*)?$/i' <<< '#_test'
1
perl -pe '$_=/^#([a-z_]\w*)?$/i' <<< '#1test'
</code>```

Saved 2 bytes thanks for Martin Ender (and another 4 using his lookaround method)

Perl, 18 bytes

17 bytes code +1 for -p

Using Martin's lookaround this can be much shorter!

$_=/^#(?!\d)\w*$/
```

Title: #Hashtag_or_not

Body:
Perl, 22 bytes

21 bytes code +1 for -p

$_=/^#([a-z_]\w*)?$/i

Prints 1 if it's a valid hashtag, empty string otherwise.

Usage

perl -pe '$_=/^#([a-z_]\w*)?$/i' <<< '#'
1
perl -pe '$_=/^#([a-z_]\w*)?$/i' <<< '#_test'
1
perl -pe '$_=/^#([a-z_]\w*)?$/i' <<< '#1test'

Saved 2 bytes thanks for Martin Ender (and another 4 using his lookaround method)

Perl, 18 bytes

17 bytes code +1 for -p

Using Martin's lookaround this can be much shorter!

$_=/^#(?!\d)\w*$/


答:
Dyalog APL, <s>22</s> 20 bytes

Without RegEx:

```<code>{0≤⎕NC 1↓⍵,⎕A}∧'#'=⊃
</code>```

-2 thanks to ngn

Title: #Hashtag_or_not

Body:
Dyalog APL, <s>22</s> 20 bytes

Without RegEx:

{0≤⎕NC 1↓⍵,⎕A}∧'#'=⊃

-2 thanks to ngn


问:
Array Sandwiches
(Adapted from Problem C of the first qualifier of the ACM Programming Contest of 2012/2013)

You have several arrays, named \$A_1, A_2, ... , A_n\$, each sorted in ascending order. Every item in the array will be a 32-bit integer.

A sandwich is a set of indices \$j_1, j_2, ... , j_n\$ such that \$A_1[j_1] ≤ A_2[j_2] ≤ ... ≤ A_n[j_n]\$. \$A_i[0]\$ is the first element of \$A_i\$.

Given some arrays, output every possible sandwich that you can have from those arrays, separated by a newline.

If there is somehow a built-in function which does this in your language, don't use it.

Input can be given in any way, output must be separated with whitespace, but can given in any order.

Test Case:

```<code>[[1, 5, 7, 10], [2, 6, 6, 8, 12], [4, 5, 9]]
</code>```

Output:

```<code>0 0 0
0 0 1
0 0 2
0 1 2
0 2 2
0 3 2
1 1 2
1 2 2
1 3 2
2 3 2
</code>```

Test Case:

```<code>[[10, 20, 30], [1, 2, 3]]
</code>```

Output:

Shortest code wins.

答:
GolfScript (44 chars)

```<code>~{.,,]zip}%{{`{+}+1$\/}%\;}*{2%.$=},{(;2%}%`
</code>```

Same input and output format as Ilmari's entry.

Demo

Rough breakdown:

Map each input row into an array of pairs [value index]

```<code>{.,,]zip}%
</code>```

Fold a Cartesian product over the rows

```<code>{{`{+}+1$\/}%\;}*
</code>```

Filter to those whose 0th, 2nd, 4th, etc. entries are non-decreasing.

```<code>{2%.$=},
</code>```

Map each one down to its 1st, 3rd, 5th, etc. entries.

```<code>{(;2%}%
</code>```

ContentLicense: CC BY-SA 4.0

Title: Array Sandwiches

Body:
GolfScript (44 chars)

~{.,,]zip}%{{`{+}+1$\/}%\;}*{2%.$=},{(;2%}%`

Same input and output format as Ilmari's entry.

Demo

Rough breakdown:

Map each input row into an array of pairs [value index]

{.,,]zip}%

Fold a Cartesian product over the rows

{{`{+}+1$\/}%\;}*

Filter to those whose 0th, 2nd, 4th, etc. entries are non-decreasing.

{2%.$=},

Map each one down to its 1st, 3rd, 5th, etc. entries.

{(;2%}%


答:
Brachylog, 55 bytes

```<code>"#"|h"#",?b@lL'(eE,@A:"1234567890":"_"c'eE),@A:"_"ce~hL
</code>```

This uses no regex.

Explanation

```<code>Main predicate, Input (?) is a string

  "#"                           ? = "#"
|                             Or
  h"#",                         First character of ? is "#"
  ?b@lL                         L is the rest of the chars of ? lowercased
  '(                            It is not possible for any char of L that...
    eE,                           Call this char E
    @A:"1234567890":"_"c          Concatenate the lowercase alphabet with the digits and "_"
    'eE                           E is not a member of that concatenated string
   ),
   @A:"_"c                      Concatenate the lowercase alphabet with "_"
   e~hL                         One char of that concatenated string is the first char of L
</code>```

Title: #Hashtag_or_not

Body:
Brachylog, 55 bytes

"#"|h"#",?b@lL'(eE,@A:"1234567890":"_"c'eE),@A:"_"ce~hL

This uses no regex.

Explanation

Main predicate, Input (?) is a string

  "#"                           ? = "#"
|                             Or
  h"#",                         First character of ? is "#"
  ?b@lL                         L is the rest of the chars of ? lowercased
  '(                            It is not possible for any char of L that...
    eE,                           Call this char E
    @A:"1234567890":"_"c          Concatenate the lowercase alphabet with the digits and "_"
    'eE                           E is not a member of that concatenated string
   ),
   @A:"_"c                      Concatenate the lowercase alphabet with "_"
   e~hL                         One char of that concatenated string is the first char of L


答:
C, 80 bytes

Function f() takes the string as an argument and modifies int *b to either 1 or 0 to indicate truthy/falsy.

```<code>f(char*p,int*b){for(*b=(*p==35)&&!isdigit(p[1]);*p;++p)*b&=isalnum(*p)||*p==95;}
</code>```

If the string always has at least one character (i.e. never an empty string), a byte can be shaved off for 79 bytes:

```<code>f(char*p,int*b){for(*b=(*p==35)&&!isdigit(p[1]);*++p;)*b&=isalnum(*p)||*p==95;}
</code>```

Title: #Hashtag_or_not

Body:
C, 80 bytes

Function f() takes the string as an argument and modifies int *b to either 1 or 0 to indicate truthy/falsy.

f(char*p,int*b){for(*b=(*p==35)&&!isdigit(p[1]);*p;++p)*b&=isalnum(*p)||*p==95;}

If the string always has at least one character (i.e. never an empty string), a byte can be shaved off for 79 bytes:

f(char*p,int*b){for(*b=(*p==35)&&!isdigit(p[1]);*++p;)*b&=isalnum(*p)||*p==95;}


答:
Haskell, 45 bytes

```<code>f x=round$log(sqrt 5*x+0.9)/log((sqrt 5+1)/2)
</code>```

Title: Fibonacci reversed!

Body:
Introduction

We all know and love our Fibonacci sequence and have seen a myriad of challenge on it here already. However, we're still lacking a very simple case which this answer is going to provide: Reversed fibonacci! So given F_n your job is to find n.

Specification

Input

Your input will be a non-negative integer, which is guaranteed to be part of the fibonacci sequence.

Output

The output must be a non-negative integer as well.

What to do?

The introduction already said: Given a fibonacci number, output its index. Fiboancci number hereby is defined as F(0)=0, F(1)=1, F(n)=F(n-1)+F(n-2) and you're given F(n) and must return n.

Potential Corner Cases

0 is a valid in- and output.

If given "1" as input you may either output "1" or "2", as you prefer.

You may always assume that your input actually is a fibonacci number.

You may assume that the input is representable as a 32-bit signed integer.

Who wins?

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

Standard rules apply of course.

Test-cases

```<code>0 -> 0
2 -> 3
3 -> 4
5 -> 5
8 -> 6
13 -> 7
1836311903 -> 46
</code>```

Body:
Haskell, 45 bytes

f x=round$log(sqrt 5*x+0.9)/log((sqrt 5+1)/2)


问:
Write a program to display directory treehouse
Given a directory (such as C:/), given from stdin or read from a file, produce a directory tree, with each file/folder indented based on its depth.

Example

If I have a C:/ drive which only contains two folders foo and bar, and bar is empty while foo contains baz.txt, then running with input C:/ produces:

```<code>C:/
    bar/
    foo/
        baz.txt
</code>```

while running with input C:/foo/ should produce

```<code>foo/
    baz.txt
</code>```

As this is codegolf, lowest byte count wins. The file extensions (such as baz.txt) are optional.
Extra notes: hidden files can be ignored, directories must actually exist, it can be assumed that files do not contain unprintable characters or new lines but all other printable ASCII characters are fine (file names with spaces must be supported). Output can be written to file or stdout. The indentations can be made up of either a tab character or 4 spaces.

答:
Batch, 237 bytes

```<code>@echo off
echo %~1\
for /f %%d in ('dir/s/b %1')do call:f %1 %%~ad "%%d"
exit/b
:f
set f=%~3
call set f=%%f:~1=%%
set i=
:l
set i=\t%i%
set f=%f:*\=%
if not %f%==%f:*\=% goto l
set a=%2
if %a:~0,1%==d set f=%f%\
echo %i%%f%
</code>```

Where \t represents the literal tab character. This version includes trailing \s on directories but 41 bytes can be saved if they are not needed.

Body:
Batch, 237 bytes

@echo off
echo %~1\
for /f %%d in ('dir/s/b %1')do call:f %1 %%~ad "%%d"
exit/b
:f
set f=%~3
call set f=%%f:~1=%%
set i=
:l
set i=\t%i%
set f=%f:*\=%
if not %f%==%f:*\=% goto l
set a=%2
if %a:~0,1%==d set f=%f%\
echo %i%%f%

Where \t represents the literal tab character. This version includes trailing \s on directories but 41 bytes can be saved if they are not needed.


答:
Python 3, <s>103</s> 93 bytes

```<code>all((c=='_'or c.isalpha()*i>0)^(i<1and'#'==c)^(c.isdigit()*i>1)for i,c in enumerate(input()))
</code>```

The # being True killed me here, I had to enumerate the string to avoid an index error on the single character input.

Title: #Hashtag_or_not

Body:
Python 3, <s>103</s> 93 bytes

all((c=='_'or c.isalpha()*i>0)^(i<1and'#'==c)^(c.isdigit()*i>1)for i,c in enumerate(input()))

The # being True killed me here, I had to enumerate the string to avoid an index error on the single character input.


答:
Standard ML, <s>121</s> <s>118</s> 107 bytes

(fn#"#"::a=>(fn x::r=>x> #"@"andalso List.all(fn#"_"=>1=1|c=>Char.isAlphaNum c)a|e=>1=1)a|e=>1=0)o explode;
```

<p>Try it online!
Functional solution without using regex. Declares an anonymous function which is bond to the implicit result identifier <code>it</code>. </p>

<pre class="lang-ml prettyprint-override"><code>> val it = fn : string -> bool
- it "#valid_hash";
> val it = true : bool
</code>```

Title: #Hashtag_or_not

Body:
Standard ML, <s>121</s> <s>118</s> 107 bytes

(fn#"#"::a=>(fn x::r=>x> #"@"andalso List.all(fn#"_"=>1=1|c=>Char.isAlphaNum c)a|e=>1=1)a|e=>1=0)o explode;

Try it online!
Functional solution without using regex. Declares an anonymous function which is bond to the implicit result identifier it.

> val it = fn : string -> bool
- it "#valid_hash";
> val it = true : bool


问:
King of the Hill - Spacewar!

If you've ever played Spacewar!, you know it was a fun game. If you haven't, know this: it was (and is) one of the very first and most important computer games. And it's still fun! The clone I grew up on is this one, which is, apparently and unfortunately, Windows only. So I recreated it!

The KotH is hosted here: PPCG - Spacewar! King of the Hill. I encourage you to play as a human against at least one other bot to get a feel for how the game works.

The Game

One frame is 30 milliseconds (thus, about 33 frames per second).

The field is 800 pixels wide and 600 pixels tall.

The field is toroidal, meaning that spaceships and missiles that move outside of the field reappear on the opposite side.

There are two spaceships, red and blue.

Red is positioned at x=50 and random y between 50, (field height - 50) pixels.

Blue is positioned at x=(field width - 50) and random y between 50, (field height - 50) pixels.

Both face x = (field width)/2.

The available controls are:

Turn left - 5 degrees per frame counterclockwise.

Turn right - 5 degrees per frame clockwise.

Fire missile - travels at an extra 10 pixels per frame in addition to the velocity of the ship, in the direction the ship was pointing.

Fire engine - accelerates the spaceship at 0.30 pixels per frame in the direction the spaceship is pointing.

Hyperspace jump - teleports to some random coordinates in the field, with a 25% chance of exploding. These random coordinates may be on top of the sun.

The maximum speed for ships is 15 pixels per frame under engine power and 40 pixels per frame when gravity-boosted.

When traveling faster than 15 pixels per frame, engine thrust may only change direction or slow down.

Regarding missiles:

Missiles travel in a straight line.

Missiles may be fired at a maximum rate of 1 per 0.1 seconds.

Missiles have a lifetime of 2.25 seconds.

Ships have a maximum of 20 missiles each.

Missiles are point particles internally.

There is a sun in the very center that is extremely hazardous to your ship. The slightest contact is fatal. This sun also destroys missiles.

The sun has gravity. The resultant acceleration is 5000/(distance^2) pixels/frame^2, where distance is in pixels. Spaceships and missiles are affected.

Both ships have three strike zones: the nose, the left wing, and the right wing.

A hit on the nose is instant death.

A hit on either wing reduces the spaceship's turn rate and engine acceleration by half.

If both wings are destroyed, the spaceship cannot be maneuvered and can only fire missiles.

Ships may collide with each other.

A nose-nose impact is fatal for both ships.

A nose-wing impact destroys the wing.

A wing-wing impact destroys both wings.

Dead ships are solid and frozen until they explode 1 second later.

After at least one ship has died, the field is reset 3 seconds later. Until then, the sun and any remaining missiles are still hazardous.

The original game also has deadly and indestructible asteroids, but I won't include those.

The Rules

Your bot must be written in JavaScript.

Your bot should limit its decision to about 10 milliseconds. If I notice consistent lag because of your bot, I'll disqualify it and let you know so you can fix it.

Bots will have access to the following:

Field width and field height

Sun position and radius

The position, rotation, velocity, shape, missile stock, and in-hyperspace status of both ships

The position and velocity of all missiles

When prompted, your bot should return a list of strings.

These strings should be one of the following: turn left, turn right, fire engine, fire missile, hyperspace. Any other string will be ignored.

If there are any duplicates, only the first will be noted.

hyperspace takes precedence over all others.

turn left and turn right at the same time will have no effect.

fire engine will have no effect if the ship only has the nose or is dead.

fire missile will have no effect if a missile was fired too recently.

In a change from the usual, your bot is allowed to exploit the behavior of other bots. I want to encourage a metagame.

Bots may not emulate other bots. (I.e., no mind-reading.)

Bots may not set any variables used by the game and physics code. (I.e., no cheating.)

Bot Implementation Details

I will be storing your bot in its own JavaScript file that is automatically included, with the filename bot_<name>.js. So don't put any spaces or characters that would interfere with this or with naming a function in JavaScript. That's because you should define the following functions: <name>_setup(team) and <name>_getActions(gameInfo, botVars). Further down the page, there exist textareas for the userbot, which you can edit to test your code.

<name>_setup(team)

This function is for you to define any variables that you want to persist. team will be either "red" or "blue". This function must return an object. Define variables like so:

var vars = {};
vars['example'] = "example";
return vars;
```

<p>This <code>vars</code> object will be passed in to the other function:</p>

<h3><code><name>_getActions(gameInfo, botVars)</code></h3>

<p><code>botVars</code> is the object returned by <code><name>_setup(team)</code>. <code>gameInfo</code> is an object containing the following variables:</p>

<pre class="lang-js prettyprint-override"><code>redScore
blueScore
timeLeft

fieldWidth
fieldHeight

sun_x
sun_y
sun_r //sun's radius

gravityStrength //acceleration in pixels/frame^2 at 1 pixel away from the sun's center
engineThrust    //acceleration in pixels/frame^2

speedLimit //maximum speed under engine power
maxSpeed   //maximum speed from gravity boosts

red_x
red_y
red_rot          //rotation in degrees
red_xv           //x velocity
red_yv           //y velocity
red_shape        //one of "full ship", "left wing", "right wing", "nose only"
red_missileStock //the number of missiles red has left
red_inHyperspace //true if red is in hyperspace
red_exploded     //until red explodes, it is still solid and hazardous
red_alive
// likewise for blue //

numMissiles
missiles //this is a list of objects, each with the following variables
  x
  y
  xv
  yv
</code>```

Your bot has full access to these. I'm pretty sure that you can write to them and not affect the original variables, but don't do it anyway. A note on rotations: ships point in the +y direction, downwards, so anything that you want to align with the ship needs to be offset by 90 degrees. Also, positive rotation is clockwise.

This function must return a list of strings, representing your bot's actions. For example, ["turn right","thrust"]. More details on this are in the Rules section.

Additional Details

You may also make use of the following:

LineIntersection(L1, L2)

L1 and L2 are two-element arrays of two-element arrays. That is, L1 := [[x1,y1],[x2,y2]] and L2 := [[u1,v1],[u2,v2]]. This function computes the intersection of two lines and returns this: [[x,y], [a,b]]. [x,y] are the coordinates of the intersection point and [a,b] is a pair of ratios that express how far along each line the intersection point is. As in, a = 0.25 would mean that the intersection point is a quarter of the way from [x1,y1] to [x2,y2], and likewise for b. If there is no intersection, an empty array is returned.

window["shipShapes"]

var shipShapes = {
    'full ship': [[-8,16],[0,-8],[8,16]],
    'left wing': [[-8,16],[0,-8],[4,4],[0,8],[0,16]],
    'right wing':[[-4,4],[0,-8],[8,16],[0,16],[0,8]],
    'nose only': [[-4,4],[0,-8],[4,4],[0,8]]
};
```

<p>These are the coordinates of the ships' polygons. To make getting the current coordinates easier, you may also use...</p>

<h3><code>getShipCoords(<color>)</code></h3>

<p><code>getShipCoords("red")</code> will return the current coordinates of the vertices of Red's ship, and likewise for <code>getShipCoords("blue")</code> and Blue. These coordinates are in a list like so: <code>[[x1,y1],[x2,y2],[x3,y3],...]</code>. Polygons are implicitly closed, so there is a line between the first and last coordinate pairs.</p>

<p><strong>You may not access or alter any other variables or functions in use by the game/website.</strong> And definitely don't name your functions the same. I don't foresee that this will be a problem, but if your bot breaks the game code, that's one possibility. There is no logging or catching of exceptions.</p>

<h2>Winning</h2>

<ul>
<li>Every pairing of bots shall be played at least 10 times, both ways. (So, at least 20 games total.)</li>
<li>Aim to have the highest win/loss ratios <em>overall</em>. If your bot does super well against one other bot, but loses against the other three, that's not as good as winning against two and losing against two (as a general rule of thumb).</li>
<li>For every bot, the ratios (wins+1)/(losses+1) will be calculated, then the mean and standard deviation of these ratios will be calculated. A higher mean will have priority, and in case means are within 1 unit of each other, the lower variance will have priority.</li>
<li>Scoring will begin either in a week from today or after three days of no new submissions. This is so I don't have to repeat any pairing of bots.</li>
</ul>

<p><strong>Above all, have fun!</strong></p>

<hr>

<h2>Leaderboard (2016-01-08 05:15):</h2>

<pre class="lang-js prettyprint-override"><code>#   Name                       Mean      StdDev
1.  Helios                     13.625    6.852
2.  EdgeCase                    8.335    8.155
3.  OpponentDodger              8.415    8.186
4.  OrbitBot                    5.110    6.294
5.  SunAvoider                  5.276    6.772
6.  DangitBobby                 3.320    4.423
7.  SprayAndPray                3.118    4.642
8.  Engineer                    3.903    6.315
9.  RighthandedSpasms           1.805    2.477
10. AttackAndComeBack           2.521    2.921
11. PanicAttack                 2.622    3.102
12. FullSpeedAhead              2.058    3.295
13. UhhIDKWhatToCallThisBot     2.555    3.406
14. MissilesPlusScore           0.159    0.228
15. Hyper                       0.236    0.332
16. RandUmmm                    0.988    1.329
17. Kamikaze                    0.781    1.793
</code>```

Note: This is subject to change as I run more games. Plus, the ordering of ranks 9-13 bothers me, so I may tweak the scoring method to better match one's intuition of how they should be ranked.

(Means and standard deviations were rounded to three decimal digits. Also, Hyper should be HYPER but that messes up the highlighting. :P)

答:
Kamikaze+

Not designed to be competitive. Just for fun. Technically, it does the opposite of Spy: chase the player, hyperspace when close to the sun, fire missile 70% of the time. I sorta just want to see KamikazePlus chasing Spy and Spy running away like a madman.

```<code>function KamikazePlus_setup(team) {
  // Typical setup. Nothing to see here. ;)
  var botVars = {};
  botVars["color"] = team;
  return botVars;
}

function KamikazePlus_getActions(gameInfo, botVars) {
    var actions = [];
    var us, them, red = {
            rotation: gameInfo.red_rot,
            x: gameInfo.red_x,
            y: gameInfo.red_y,
            alive: gameInfo.blue_alive
        },
        blue = {
            rotation: gameInfo.blue_rot,
            x: gameInfo.blue_x,
            y: gameInfo.blue_y,
            alive: gameInfo.blue_alive
        };
    if (botVars.color == "red") {
        us = red;
        them = blue;
    } else if (botVars.color == "blue") {
        us = blue;
        them = red;
    }

    function distance(x1, y1, x2, y2) {
        return Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2));
    }

    // Get our ship's position
    var rotation, x, y, opponentAlive;
    if (botVars.color == "red") {
        rotation = gameInfo.red_rot;
        x = gameInfo.red_x;
        y = gameInfo.red_y;
        opponentAlive = gameInfo.blue_alive;
    } else if (botVars.color == "blue") {
        rotation = gameInfo.blue_rot;
        x = gameInfo.blue_x;
        y = gameInfo.blue_y;
        opponentAlive = gameInfo.red_alive;
    }

    // Calculate our rotation compared to the sun in degrees
    var sunX = gameInfo.sun_x,
        sunY = gameInfo.sun_y,
        angle = Math.atan2(sunY - y, sunX - x) * 180 / Math.PI,
        rotationToSun = (rotation - angle + 360) % 360;

    // Check if we need to hyperspace to avoid the sun
    var rX = x - sunX,
        rY = y - sunY,
        distanceFromSun = Math.sqrt(rX * rX + rY * rY) - gameInfo.sun_r;
    if (distanceFromSun < 30) {
        actions.push("hyperspace");
        console.log("Command Module is Hyperspacing.")
    }
    if (gameInfo[botVars["color"] + "_alive"]) {
        var angle = Math.degrees(Math.atan2(them.y - us.y, them.x - us.x)),
            rotationToOpponent = (us.rotation - angle + 360) % 360;
        if (rotationToOpponent > 90 && rotationToOpponent < 270) {
            actions.push("turn left");
        } else {
            actions.push("turn right");
        };
        actions.push("fire engine");
        if (Math.random() > 0.3) {
            actions.push("fire missile")
        }

    }
    return actions;
}
</code>```

Basically just took Spy's code and flipped "left" and "right".

Title: King of the Hill - Spacewar!

Body:
Kamikaze+

Not designed to be competitive. Just for fun. Technically, it does the opposite of Spy: chase the player, hyperspace when close to the sun, fire missile 70% of the time. I sorta just want to see KamikazePlus chasing Spy and Spy running away like a madman.

function KamikazePlus_setup(team) {
  // Typical setup. Nothing to see here. ;)
  var botVars = {};
  botVars["color"] = team;
  return botVars;
}

function KamikazePlus_getActions(gameInfo, botVars) {
    var actions = [];
    var us, them, red = {
            rotation: gameInfo.red_rot,
            x: gameInfo.red_x,
            y: gameInfo.red_y,
            alive: gameInfo.blue_alive
        },
        blue = {
            rotation: gameInfo.blue_rot,
            x: gameInfo.blue_x,
            y: gameInfo.blue_y,
            alive: gameInfo.blue_alive
        };
    if (botVars.color == "red") {
        us = red;
        them = blue;
    } else if (botVars.color == "blue") {
        us = blue;
        them = red;
    }

    function distance(x1, y1, x2, y2) {
        return Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2));
    }

    // Get our ship's position
    var rotation, x, y, opponentAlive;
    if (botVars.color == "red") {
        rotation = gameInfo.red_rot;
        x = gameInfo.red_x;
        y = gameInfo.red_y;
        opponentAlive = gameInfo.blue_alive;
    } else if (botVars.color == "blue") {
        rotation = gameInfo.blue_rot;
        x = gameInfo.blue_x;
        y = gameInfo.blue_y;
        opponentAlive = gameInfo.red_alive;
    }

    // Calculate our rotation compared to the sun in degrees
    var sunX = gameInfo.sun_x,
        sunY = gameInfo.sun_y,
        angle = Math.atan2(sunY - y, sunX - x) * 180 / Math.PI,
        rotationToSun = (rotation - angle + 360) % 360;

    // Check if we need to hyperspace to avoid the sun
    var rX = x - sunX,
        rY = y - sunY,
        distanceFromSun = Math.sqrt(rX * rX + rY * rY) - gameInfo.sun_r;
    if (distanceFromSun < 30) {
        actions.push("hyperspace");
        console.log("Command Module is Hyperspacing.")
    }
    if (gameInfo[botVars["color"] + "_alive"]) {
        var angle = Math.degrees(Math.atan2(them.y - us.y, them.x - us.x)),
            rotationToOpponent = (us.rotation - angle + 360) % 360;
        if (rotationToOpponent > 90 && rotationToOpponent < 270) {
            actions.push("turn left");
        } else {
            actions.push("turn right");
        };
        actions.push("fire engine");
        if (Math.random() > 0.3) {
            actions.push("fire missile")
        }

    }
    return actions;
}

Basically just took Spy's code and flipped "left" and "right".


答:
PowerShell v2+, 25 bytes

```<code>$args-match'^#(?!\d)\w*$'
</code>```

Using Martin's regex, just wrapped up in PowerShell's -match operator coupled with the input $args. For truthy/falsey values, this will return the string itself on a match (a truthy value) or nothing on a non-match (a falsey value). This is because when a comparison operator is applied against an array, it returns anything that satisfies that operator.

A couple examples (wrapped in a [bool] cast to make the output more clear):

```<code>PS C:\Tools\Scripts\golfing> [bool](.\hashtag-or-not.ps1 '#2016Election')
False

PS C:\Tools\Scripts\golfing> [bool](.\hashtag-or-not.ps1 'Hello, World!')
False

PS C:\Tools\Scripts\golfing> [bool](.\hashtag-or-not.ps1 '#')
True

PS C:\Tools\Scripts\golfing> [bool](.\hashtag-or-not.ps1 '')
False

PS C:\Tools\Scripts\golfing> [bool](.\hashtag-or-not.ps1 '#USElection2016')
True
</code>```

Title: #Hashtag_or_not

Body:
In this code golf challenge, you will verify hashtags!

#What_your_code_should_do

Input is a string. Output a truthy value if it is a valid hashtag, and a falsy value otherwise.

We define a string as a valid Hashtag if ...

It starts with a hash (#).

It doesn't have a number right after the hashtag (e.g. #2016USElection isn't a  valid hashtag).

It doesn't have any "special characters" (i.e. any character that isn't an alphabet, underscore (_) or a number).

You can assume that the input only contains ASCII characters. (It would be unfair if we did Unicode too.)

#Rules

Basic code-golf rules apply.

#Examples

Truthy:

```<code>#
#e
#_ABC
#thisisanunexpectedlylongstringxoxoxoxo
#USElection2016
</code>```

Falsy:

```<code>Hello, World!
#12thBday
#not-valid
#alsoNotValid!
#!not_a_hash
</code>```

Body:
PowerShell v2+, 25 bytes

$args-match'^#(?!\d)\w*$'

Using Martin's regex, just wrapped up in PowerShell's -match operator coupled with the input $args. For truthy/falsey values, this will return the string itself on a match (a truthy value) or nothing on a non-match (a falsey value). This is because when a comparison operator is applied against an array, it returns anything that satisfies that operator.

A couple examples (wrapped in a [bool] cast to make the output more clear):

PS C:\Tools\Scripts\golfing> [bool](.\hashtag-or-not.ps1 '#2016Election')
False

PS C:\Tools\Scripts\golfing> [bool](.\hashtag-or-not.ps1 'Hello, World!')
False

PS C:\Tools\Scripts\golfing> [bool](.\hashtag-or-not.ps1 '#')
True

PS C:\Tools\Scripts\golfing> [bool](.\hashtag-or-not.ps1 '')
False

PS C:\Tools\Scripts\golfing> [bool](.\hashtag-or-not.ps1 '#USElection2016')
True


问:
Dice from Changing Random Generator

Introduction

You are given a random integer generator with the following implementation

The first invocation always returns 1.

The second invocation returns a random integer between 1 and 2.

The third invocation returns a random integer between 1 and 3.

The nth invocation returns a random integer between 1 and n, inclusive.

Based on the above function, write a random dice generator that is perfectly random, returning a value between 1 and 6 (inclusive) with equal probability.

Rules

Your program/function should result in a random integer between 1 and 6, inclusive, in some usable form, i.e., to standard output or as a function return value.

The ascending random number generator above can be defined as a "free" function in your program (i.e., doesn't count toward your character count), or a separate script/program that is executed as needed, assuming the state (n) is persistent between calls.

Assume that no more than 1000 dice rolls will ever be requested in a single use case of your program, and the initial random number generator can be reset to 1 at the end of 1000 dice rolls to avoid overflow of n.

Your program may not use any other source of random numbers except the ascending random generator defined above.  You may of course request multiple random numbers from the random number generator for each single dice roll output.

This is code-golf, so winner is shortest answer or most votes in the event of a tie.  If you can generate 1000 dice rolls using less than 1000 generated random numbers, give yourself a 10-point efficiency bonus.

Example

```<code>./asc-rand
1 # random integer between 1 and 1
./asc-rand
1 # random integer between 1 and 2
./asc-rand
3 # random integer between 1 and 3
./asc-rand
4 # random integer between 1 and 4

# dice-gen generates random dice based on output of asc-rand program.
./dice-gen
3
./dice-gen
6
./dice-gen
5
./dice-gen
1
</code>```

答:
GolfScript (15 chars)

This assumes that the number of rolls required is supplied on stdin and lists that many results to stdout.

```<code># The free increasing random function
0:N;{N):N rand)}:r;

~{r{;r}5*6%)n}*
</code>```

Online demo

While I could get the 10 point bonus for using fewer than 1000 rolls to generate 1000 numbers, it would cost me far more than 10 characters. The trivial approach of extracting suitable entropy when N is a multiple of a power of 2 or 3 falls well short because the number of results available mod 3 is only 333 + 111 + 37 + 12 + 4 + 1 = 498. Therefore it's necessary to take a sample-and-reject approach. Using this approach you can get an expected 2242 rolls from 1000 calls to r, but there's extra overhead from the book-keeping and base is a very long function name.

Title: Dice from Changing Random Generator

Body:
GolfScript (15 chars)

This assumes that the number of rolls required is supplied on stdin and lists that many results to stdout.

# The free increasing random function
0:N;{N):N rand)}:r;

~{r{;r}5*6%)n}*

Online demo

While I could get the 10 point bonus for using fewer than 1000 rolls to generate 1000 numbers, it would cost me far more than 10 characters. The trivial approach of extracting suitable entropy when N is a multiple of a power of 2 or 3 falls well short because the number of results available mod 3 is only 333 + 111 + 37 + 12 + 4 + 1 = 498. Therefore it's necessary to take a sample-and-reject approach. Using this approach you can get an expected 2242 rolls from 1000 calls to r, but there's extra overhead from the book-keeping and base is a very long function name.


答:
Pyke, 19 bytes

```<code>\#.^It,!It\_D-PRkq|
</code>```

Try it here!

Quick fix for tonight

Title: #Hashtag_or_not

Body:
Pyke, 19 bytes

\#.^It,!It\_D-PRkq|

Try it here!

Quick fix for tonight


答:
PHP, 180 bytes

first argument: path must have a trailing slash (or backslash)

second argument: level defaults to NULL and will be interpreted as 0 by str_repeat; will throw a warning if not provided

```<code>function d($p,$e){$s=opendir($p);echo$b=str_repeat("\t",$e++),$e?basename($p)."/":$p,"
";while($f=readdir($s))echo preg_match("#^\.#",$f)?"":is_dir($p.$f)?d("$p$f/",$e):"$b\t$f
";}
</code>```

displays hidden files and directories, but does not recurse hidden directories

add parentheses around is_dir(...)?d(...):"..." to remove hidden entries from output (+2)

replace "#^\.#" with #^\.+$# to display/recurse hidden entries but skip dot entries (+2)

may throw errors when directories are nested too deep. Insert closedir($s); before the final } to fix (+13)

will fail if a directory contains an entry with no name, prepend false!== to the while condition to fix (+8)

with glob, 182 bytes (probably 163 in future php)

```<code>function g($p,$e){echo$b=str_repeat("\t",$e),$e++?basename($p)."/":$p,"
";foreach(glob(preg_replace("#[*?[]#","[$1]",$p)."*",2)as$f)echo is_dir($f)?g($f,$e):"$b\t".basename($f)."
";}
</code>```

does not display or recurse hidden files/directories

2 stands for GLOB_MARK, will append a slash to all directory names, as does ls -F

the preg_replace escapes glob special characters

I could have abused preg_quote for this (-19); but that would fail on Windows systems, as the backslash is the directory separator there.

php may soon include a function glob_quote, which will allow the same golfing as preg_quote and work on all systems.

with iterators, 183 bytes

(well, not purely iterators: I used implicit SplFileInfo::__toString() to golf $f->getBaseName() and $f->isDir() to the old PHP 4 functions.)

```<code>function i($p){echo"$p
";foreach($i=new RecursiveIteratorIterator(new RecursiveDirectoryIterator($p),1)as$f)echo str_repeat("\t",1+$i->getDepth()),basename($f),is_dir($f)?"/":"","
";}
</code>```

no trailing slash required

displays and recurses hidden entries (ls -a)

insert ,4096 or ,FilesystemIterator::SKIP_DOTS before ),1 to skip dot entries (+5) (ls -A)

flag 1 stands for RecursiveIteratorIterator::SELF_FIRST

Title: Write a program to display directory treehouse

Body:
Given a directory (such as C:/), given from stdin or read from a file, produce a directory tree, with each file/folder indented based on its depth.

Example

If I have a C:/ drive which only contains two folders foo and bar, and bar is empty while foo contains baz.txt, then running with input C:/ produces:

```<code>C:/
    bar/
    foo/
        baz.txt
</code>```

while running with input C:/foo/ should produce

```<code>foo/
    baz.txt
</code>```

As this is codegolf, lowest byte count wins. The file extensions (such as baz.txt) are optional.
Extra notes: hidden files can be ignored, directories must actually exist, it can be assumed that files do not contain unprintable characters or new lines but all other printable ASCII characters are fine (file names with spaces must be supported). Output can be written to file or stdout. The indentations can be made up of either a tab character or 4 spaces.

Body:
PHP, 180 bytes

first argument: path must have a trailing slash (or backslash)

second argument: level defaults to NULL and will be interpreted as 0 by str_repeat; will throw a warning if not provided

function d($p,$e){$s=opendir($p);echo$b=str_repeat("\t",$e++),$e?basename($p)."/":$p,"
";while($f=readdir($s))echo preg_match("#^\.#",$f)?"":is_dir($p.$f)?d("$p$f/",$e):"$b\t$f
";}

displays hidden files and directories, but does not recurse hidden directories

add parentheses around is_dir(...)?d(...):"..." to remove hidden entries from output (+2)

replace "#^\.#" with #^\.+$# to display/recurse hidden entries but skip dot entries (+2)

may throw errors when directories are nested too deep. Insert closedir($s); before the final } to fix (+13)

will fail if a directory contains an entry with no name, prepend false!== to the while condition to fix (+8)

with glob, 182 bytes (probably 163 in future php)

function g($p,$e){echo$b=str_repeat("\t",$e),$e++?basename($p)."/":$p,"
";foreach(glob(preg_replace("#[*?[]#","[$1]",$p)."*",2)as$f)echo is_dir($f)?g($f,$e):"$b\t".basename($f)."
";}

does not display or recurse hidden files/directories

2 stands for GLOB_MARK, will append a slash to all directory names, as does ls -F

the preg_replace escapes glob special characters

I could have abused preg_quote for this (-19); but that would fail on Windows systems, as the backslash is the directory separator there.

php may soon include a function glob_quote, which will allow the same golfing as preg_quote and work on all systems.

with iterators, 183 bytes

(well, not purely iterators: I used implicit SplFileInfo::__toString() to golf $f->getBaseName() and $f->isDir() to the old PHP 4 functions.)

function i($p){echo"$p
";foreach($i=new RecursiveIteratorIterator(new RecursiveDirectoryIterator($p),1)as$f)echo str_repeat("\t",1+$i->getDepth()),basename($f),is_dir($f)?"/":"","
";}

no trailing slash required

displays and recurses hidden entries (ls -a)

insert ,4096 or ,FilesystemIterator::SKIP_DOTS before ),1 to skip dot entries (+5) (ls -A)

flag 1 stands for RecursiveIteratorIterator::SELF_FIRST


问:
"Hello, World!"
So... uh... this is a bit embarrassing. But we don't have a plain "Hello, World!" challenge yet (despite having 35 variants tagged with hello-world, and counting). While this is not the most interesting code golf in the common languages, finding the shortest solution in certain esolangs can be a serious challenge. For instance, to my knowledge it is not known whether the shortest possible Brainfuck solution has been found yet.

Furthermore, while all of <s>Wikipedia</s> (the Wikipedia entry has been deleted but there is a copy at archive.org
), esolangs and Rosetta Code have lists of "Hello, World!" programs, none of these are interested in having the shortest for each language (there is also this GitHub repository). If we want to be a significant site in the code golf community, I think we should try and create the ultimate catalogue of shortest "Hello, World!" programs (similar to how our basic quine challenge contains some of the shortest known quines in various languages). So let's do this!

The Rules

Each submission must be a full program.

The program must take no input, and print Hello, World! to STDOUT (this exact byte stream, including capitalization and punctuation) plus an optional trailing newline, and nothing else.

The program must not write anything to STDERR.

If anyone wants to abuse this by creating a language where the empty program prints Hello, World!, then congrats, they just paved the way for a very boring answer.

Note that there must be an interpreter so the submission can be tested. It is allowed (and even encouraged) to write this interpreter yourself for a previously unimplemented language.

Submissions are scored in bytes, in an appropriate (pre-existing) encoding, usually (but not necessarily) UTF-8. Some languages, like Folders, are a bit tricky to score - if in doubt, please ask on Meta.

This is not about finding the language with the shortest "Hello, World!" program. This is about finding the shortest "Hello, World!" program in every language. Therefore, I will not mark any answer as "accepted".

If your language of choice is a trivial variant of another (potentially more popular) language which already has an answer (think BASIC or SQL dialects, Unix shells or trivial Brainfuck-derivatives like Alphuck), consider adding a note to the existing answer that the same or a very similar solution is also the shortest in the other language.

As a side note, please don't downvote boring (but valid) answers in languages where there is not much to golf - these are still useful to this question as it tries to compile a catalogue as complete as possible. However, do primarily upvote answers in languages where the authors actually had to put effort into golfing the code.

For inspiration, check the Hello World Collection.

The Catalogue

The Stack Snippet at the bottom of this post generates the catalogue from the answers a) as a list of shortest solution per language and b) as an overall leaderboard.

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

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

/* Configuration */

var QUESTION_ID = 55422; // Obtain this from the url
// It will be like https://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page
var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";
var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk";
var OVERRIDE_USER = 8478; // This should be the user ID of the challenge author.

/* App */

var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page;

function answersUrl(index) {
  return "https://api.stackexchange.com/2.2/questions/" +  QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER;
}

function commentUrl(index, answers) {
  return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER;
}

function getAnswers() {
  jQuery.ajax({
    url: answersUrl(answer_page++),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      answers.push.apply(answers, data.items);
      answers_hash = [];
      answer_ids = [];
      data.items.forEach(function(a) {
        a.comments = [];
        var id = +a.share_link.match(/\d+/);
        answer_ids.push(id);
        answers_hash[id] = a;
      });
      if (!data.has_more) more_answers = false;
      comment_page = 1;
      getComments();
    }
  });
}

function getComments() {
  jQuery.ajax({
    url: commentUrl(comment_page++, answer_ids),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      data.items.forEach(function(c) {
        if (c.owner.user_id === OVERRIDE_USER)
          answers_hash[c.post_id].comments.push(c);
      });
      if (data.has_more) getComments();
      else if (more_answers) getAnswers();
      else process();
    }
  });
}

getAnswers();

var SCORE_REG = /<h\d>\s*([^\n,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/;

var OVERRIDE_REG = /^Override\s*header:\s*/i;

function getAuthorName(a) {
  return a.owner.display_name;
}

function process() {
  var valid = [];

  answers.forEach(function(a) {
    var body = a.body;
    a.comments.forEach(function(c) {
      if(OVERRIDE_REG.test(c.body))
        body = '
' + c.body.replace(OVERRIDE_REG, '') + '
';
    });

    var match = body.match(SCORE_REG);
    if (match)
      valid.push({
        user: getAuthorName(a),
        size: +match[2],
        language: match[1],
        link: a.share_link,
      });
    else console.log(body);
  });

  valid.sort(function (a, b) {
    var aB = a.size,
        bB = b.size;
    return aB - bB
  });

  var languages = {};
  var place = 1;
  var lastSize = null;
  var lastPlace = 1;
  valid.forEach(function (a) {
    if (a.size != lastSize)
      lastPlace = place;
    lastSize = a.size;
    ++place;

    var answer = jQuery("#answer-template").html();
    answer = answer.replace("{{PLACE}}", lastPlace + ".")
                   .replace("{{NAME}}", a.user)
                   .replace("{{LANGUAGE}}", a.language)
                   .replace("{{SIZE}}", a.size)
                   .replace("{{LINK}}", a.link);
    answer = jQuery(answer);
    jQuery("#answers").append(answer);

    var lang = a.language;
    lang = jQuery(''+lang+'').text();

    languages[lang] = languages[lang] || {lang: a.language, lang_raw: lang, user: a.user, size: a.size, link: a.link};
  });

  var langs = [];
  for (var lang in languages)
    if (languages.hasOwnProperty(lang))
      langs.push(languages[lang]);

  langs.sort(function (a, b) {
    if (a.lang_raw.toLowerCase() > b.lang_raw.toLowerCase()) return 1;
    if (a.lang_raw.toLowerCase() < b.lang_raw.toLowerCase()) return -1;
    return 0;
  });

  for (var i = 0; i < langs.length; ++i)
  {
    var language = jQuery("#language-template").html();
    var lang = langs[i];
    language = language.replace("{{LANGUAGE}}", lang.lang)
                       .replace("{{NAME}}", lang.user)
                       .replace("{{SIZE}}", lang.size)
                       .replace("{{LINK}}", lang.link);
    language = jQuery(language);
    jQuery("#languages").append(language);
  }

}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  text-align: left !important;
  display: block !important;
}

#answer-list {
  padding: 10px;
  width: 290px;
  float: left;
}

#language-list {
  padding: 10px;
  width: 500px;
  float: left;
}

table thead {
  font-weight: bold;
}

table td {
  padding: 5px;
}</code>```

<link rel="stylesheet" type="text/css" href="https://cdn.sstatic.net/Sites/codegolf/all.css?v=ffb5d0584c5f">

Shortest Solution by Language

Language	User	Score

Leaderboard

	Author	Language	Size

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

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

```

答:
Standard ML, 20 bytes

```<code>print"Hello, World!"
</code>```

This works with Moscow ML by calling mosml hello.sml or with Standard ML of New Jersey and sml hello.sml. In both cases an interactive session is started and Hello, World! is printed.

Inside a running session print"Hello, World!"; produces the desired output. The ; is needed to tell the interpreter to evaluate the expression.

For a compiled version

```<code>val _=print"Hello, World!"
</code>```

works with mosmlc and MLton. Try it online!

However, MLton appears to accept interpreter-style programs too, so

```<code>print"Hello, World!";
</code>```

works with a trailing ;. Try it online!

Title: "Hello, World!"

Body:
Standard ML, 20 bytes

print"Hello, World!"

This works with Moscow ML by calling mosml hello.sml or with Standard ML of New Jersey and sml hello.sml. In both cases an interactive session is started and Hello, World! is printed.

Inside a running session print"Hello, World!"; produces the desired output. The ; is needed to tell the interpreter to evaluate the expression.

For a compiled version

val _=print"Hello, World!"

works with mosmlc and MLton. Try it online!

However, MLton appears to accept interpreter-style programs too, so

print"Hello, World!";

works with a trailing ;. Try it online!


答:
J, <s>32</s> <s>27</s> 17 bytes

```<code>i.~0,+/@(!|.)\@i.
</code>```

Computes the first n Fibonacci numbers and then finds the index of n in that list.

Usage

Extra commands are used for formatting multiple input/output. The last test case is omitted since it will require much more time to compute.

```<code>   f =: i.~0,+/@(!|.)\@i.
   (,.f"0) 0 1 2 3 5 8 13
 0 0
 1 1
 2 3
 3 4
 5 5
 8 6
13 7
</code>```

Explanation

```<code>i.~0,+/@(!|.)\@i.  Input: n
               i.  Get the range [0, 1, ..., n-1]
             \@    For each prefix of that range
          |.         Reverse the prefix
         !           Find the binomial coefficient between each value in the original
                     prefix and the reversed prefix
     +/@             Sum those binomial coefficients
                   This will create the Fibonacci numbers from 1 to n
   0,              Prepend a 0 to the list of Fibonacci numbers
i.~                Find the index of n in that list and return
</code>```

Title: Fibonacci reversed!

Body:
J, <s>32</s> <s>27</s> 17 bytes

i.~0,+/@(!|.)\@i.

Computes the first n Fibonacci numbers and then finds the index of n in that list.

Usage

Extra commands are used for formatting multiple input/output. The last test case is omitted since it will require much more time to compute.

   f =: i.~0,+/@(!|.)\@i.
   (,.f"0) 0 1 2 3 5 8 13
 0 0
 1 1
 2 3
 3 4
 5 5
 8 6
13 7

Explanation

i.~0,+/@(!|.)\@i.  Input: n
               i.  Get the range [0, 1, ..., n-1]
             \@    For each prefix of that range
          |.         Reverse the prefix
         !           Find the binomial coefficient between each value in the original
                     prefix and the reversed prefix
     +/@             Sum those binomial coefficients
                   This will create the Fibonacci numbers from 1 to n
   0,              Prepend a 0 to the list of Fibonacci numbers
i.~                Find the index of n in that list and return


问:
Remove duplicated & switched case

Goal

The goal of this challenge is: given a string as input, remove duplicate pairs of letters, if the second item in the pair is of opposite capitalization. (i.e. uppercase becomes lowercase and vice-versa).

Pairs should be replaced from left to right. For example, aAa should become aa and not aA.

Inputs & outputs:

```<code>Input:         Output:
bBaAdD         bad
NniIcCeE       Nice
Tt eE Ss tT    T e S t
sS Ee tT       s E t
1!1!1sStT!     1!1!1st!
nN00bB         n00b
(eE.gG.)       (e.g.)
Hh3lL|@!       H3l|@!
Aaa            Aa
aaaaa          aaaaa
aaAaa          aaaa
</code>```

The input consists of printable ASCII symbols.

You shouldn't remove duplicated digits or other non-letter characters.

Acknowledgement

This challenge is the opposite of @nicael 's "Duplicate & switch case". Can you reverse it?

Thank you for all contributors from the sandbox!

Catalogue

The Stack Snippet at the bottom of this post generates the catalogue from the answers a) as a list of shortest solution per language and b) as an overall leaderboard.

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

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

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

Shortest Solution by Language

Language	User	Score

Leaderboard

	Author	Language	Size

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

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

```

答:
Java 7, 66 bytes

```<code>String c(String i){return i.replaceAll("(.)(?!\\1)(?i)\\1","$1");}
</code>```

Used Martin Ender's regex from his Retina answer.

Ungolfed & test code:

Try it here.

```<code>class Main{
  static String c(String i){
    return i.replaceAll("(.)(?!\\1)(?i)\\1", "$1");
  }

  public static void main(String[] a){
    System.out.println(c("bBaAdD"));
    System.out.println(c("NniIcCeE"));
    System.out.println(c("Tt eE Ss tT"));
    System.out.println(c("sS Ee tT"));
    System.out.println(c("1!1!1sStT!"));
    System.out.println(c("nN00bB"));
    System.out.println(c("(eE.gG.)"));
    System.out.println(c("Hh3lL|@!"));
    System.out.println(c("Aaa"));
    System.out.println(c("aaaaa"));
    System.out.println(c("aaAaa"));
  }
}
</code>```

Output:

```<code>bad
Nice
T e S t
s E t
1!1!1st!
n00b
(e.g.)
H3l|@!
Aa
aaaaa
aaaa
</code>```

Title: Remove duplicated & switched case

Body:
Java 7, 66 bytes

String c(String i){return i.replaceAll("(.)(?!\\1)(?i)\\1","$1");}

Used Martin Ender's regex from his Retina answer.

Ungolfed & test code:

Try it here.

class Main{
  static String c(String i){
    return i.replaceAll("(.)(?!\\1)(?i)\\1", "$1");
  }

  public static void main(String[] a){
    System.out.println(c("bBaAdD"));
    System.out.println(c("NniIcCeE"));
    System.out.println(c("Tt eE Ss tT"));
    System.out.println(c("sS Ee tT"));
    System.out.println(c("1!1!1sStT!"));
    System.out.println(c("nN00bB"));
    System.out.println(c("(eE.gG.)"));
    System.out.println(c("Hh3lL|@!"));
    System.out.println(c("Aaa"));
    System.out.println(c("aaaaa"));
    System.out.println(c("aaAaa"));
  }
}

Output:

bad
Nice
T e S t
s E t
1!1!1st!
n00b
(e.g.)
H3l|@!
Aa
aaaaa
aaaa


问:
Find numbers within the Copeland–Erdős constant

Background

The Copeland–Erdős constant is the concatenation of "0." with the base 10 representations of the prime numbers in order. Its value is

```<code>0.23571113171923293137414...
</code>```

See also OEIS A033308.

Copeland and Erdős proved that this is a normal number. This implies that every natural number can be found at some point in the decimal expansion of the Copeland-Erdős  constant.

The challenge

Given a positive integer, express it in base 10 (without leading zeros) and output the index of its first appearance within the sequence of decimal digits of the Copeland–Erdős constant.

Any reasonable input and output format is allowed, but input and output should be in base 10. In particular, the input can be read as a string; and in that case it can be assumed not to contain leading zeros.

Output may be 0-based or 1-based, starting from the first decimal of the constant.

The actual results may be limited by data type, memory or computing power, and thus the program may fail for some test cases. But:

It should work in theory (i.e. not taking those limitations into account) for any input.

It should work in practice for at least the first four cases, and for each of them the result should be produced in less than a minute.

Test cases

Output is here given as 1-based.

```<code>13       -->         7   # Any prime is of course easy to find
997      -->        44   # ... and seems to always appear at a position less than itself
999      -->      1013   # Of course some numbers do appear later than themselves
314      -->       219   # Approximations to pi are also present
31416    -->     67858   # ... although one may have to go deep to find them
33308    -->     16304   # Number of the referred OEIS sequence: check
36398    -->     39386   # My PPCG ID. Hey, the result is a permutation of the input!
1234567  -->  11047265   # This one may take a while to find
</code>```

答:
PowerShell v2+, 90 bytes

```<code>for($a="0.";!($b=$a.IndexOf($args)+1)){for(;'1'*++$i-match'^(?!(..+)\1+$)..'){$a+=$i}}$b-2
</code>```

Combines the logic of my Find the number in the Champernowne constant answer, coupled with the prime generation method of my Print the nth prime that contains n answer, then subtracts 2 to output the index appropriately (i.e., not counting the 0. at the start).

Takes input as a string. Finds the 999 one in about seven seconds on my machine, but the 33308 one in quite a bit longer (edit - I gave up after 90 minutes). Should theoretically work for any value up to index [Int32]::Maxvalue aka 2147483647, as that's the maximum length of .NET strings. Will likely run into memory issues long before that happens, however.

Body:
PowerShell v2+, 90 bytes

for($a="0.";!($b=$a.IndexOf($args)+1)){for(;'1'*++$i-match'^(?!(..+)\1+$)..'){$a+=$i}}$b-2

Combines the logic of my Find the number in the Champernowne constant answer, coupled with the prime generation method of my Print the nth prime that contains n answer, then subtracts 2 to output the index appropriately (i.e., not counting the 0. at the start).

Takes input as a string. Finds the 999 one in about seven seconds on my machine, but the 33308 one in quite a bit longer (edit - I gave up after 90 minutes). Should theoretically work for any value up to index [Int32]::Maxvalue aka 2147483647, as that's the maximum length of .NET strings. Will likely run into memory issues long before that happens, however.


问:
Select the word around the given index in a given string
In Windows, when you perform double-click in a text, the word around your cursor in the text will be selected.

(This feature has more complicated properties, but they will not be required to be implemented for this challenge.)

For example, let | be your cursor in abc de|f ghi.

Then, when you double click, the substring def will be selected.

Input/Output

You will be given two inputs: a string and an integer.

Your task is to return the word-substring of the string around the index specified by the integer.

Your cursor can be right before or right after the character in the string at the index specified.

If you use right before, please specify in your answer.

Specifications (Specs)

The index is guaranteed to be inside a word, so no edge cases like abc |def ghi or abc def| ghi.

The string will only contain printable ASCII characters (from U+0020 to U+007E).

The word "word" is defined by the regex (?<!\w)\w+(?!\w), where \w is defined by [abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_], or "alphanumeric characters in ASCII including underscore".

The index can be 1-indexed or 0-indexed.

If you use 0-indexed, please specify it in your answer.

Testcases

The testcases are 1-indexed, and the cursor is right after the index specified.

The cursor position is for demonstration purpose only, which will not be required to be outputted.

```<code>string    index     output    cursor position
abc def   2         abc       ab|c def
abc def   5         def       abc d|ef
abc abc   2         abc       ab|c abc
ab cd ef  4         cd        ab c|d ef
ab   cd   6         cd        ab   c|d
ab!cd     1         ab        a|b!cd
</code>```

答:
V, <s>10, 9</s> 7 bytes

```<code>À|diwVp
</code>```

Try it online!

This answer uses 1-based indexing.

This could be shorter if we do exactly what the title says: "Select the word around the given index in a string". We could do

```<code>À|viw
</code>```

Which literally selects the word, but unfortunately doesn't change the output at all. So we need a little workaround to make it work by cutting it into a register, deleting the rest of the text, then pasting the register back in.

Explanation:

```<code>À|          " Jump the position of argument 1
  diw       " (d)elete (i)nside this (w)ord.
     V      " Select this line
      p     " And replace it with the word we just deleted
</code>```

Body:
V, <s>10, 9</s> 7 bytes

À|diwVp

Try it online!

This answer uses 1-based indexing.

This could be shorter if we do exactly what the title says: "Select the word around the given index in a string". We could do

À|viw

Which literally selects the word, but unfortunately doesn't change the output at all. So we need a little workaround to make it work by cutting it into a register, deleting the rest of the text, then pasting the register back in.

Explanation:

À|          " Jump the position of argument 1
  diw       " (d)elete (i)nside this (w)ord.
     V      " Select this line
      p     " And replace it with the word we just deleted


问:
Forecast Palindromic Dates
Palindromic dates are dates that appear as palindromes: the string of digits can be read the same way backwards as forwards. For the North American date format (MM/DD/YYYY), the next few palindromic dates are:

02/02/2020

12/02/2021

03/02/2030

The Challenge

Create a function that returns all palindromic dates in a consistent, common date format (of your choosing) that fall within a range of dates (edit: including the range itself).

Rules

To qualify as a palindrome, only the numeric characters of the date should be
checked.

The date can be in any common format (MM/DD/YYYY, DD-MM-YYYY), as
long as it uses two digits for both the month and day and four for
the year, and it uses a character to separate parts of the date. The output must preserve seperating characters (/, -, etc.). Your function only needs to handle one distinct date format. Please include the format in your answer.

If there are more than one dates returned, they should be comma or
new-line separated.

Shortest answer wins!

Example

```<code>date_palindrome('05/02/2050', '12/12/2060')
>>>['05/02/2050', '06/02/2060']
</code>```

答:
C#, <s>97</s> 94 bytes

```<code>(a,b)=>{for(;a<b;a=a.AddDays(1))if($"{a:yyy}".SequenceEqual($"{a:MMdd}".Reverse()))a.Dump();};
</code>```

C# lambda (Action) where inputs are DateTime and the output is printed by using the .Dump() method (@EvilFonti's trick).

C#, <s>115</s> 112 bytes

```<code>(a,b)=>{var r="";for(;a<b;a=a.AddDays(1))if($"{a:yyy}".SequenceEqual($"{a:MMdd}".Reverse()))r+=a+",";return r;};
</code>```

C# lambda (Func) where inputs are DateTime and output is a string.

Code:

```<code>(a,b)=> {
    var r="";
    for(;a<b;a=a.AddDays(1)) {
        if($"{a:yyy}".SequenceEqual($"{a:MMdd}".Reverse()))
            r+=a+",";
    }
    return r;
};
</code>```

Try them online!

Title: Forecast Palindromic Dates

Body:
C#, <s>97</s> 94 bytes

(a,b)=>{for(;a<b;a=a.AddDays(1))if($"{a:yyy}".SequenceEqual($"{a:MMdd}".Reverse()))a.Dump();};

C# lambda (Action) where inputs are DateTime and the output is printed by using the .Dump() method (@EvilFonti's trick).

C#, <s>115</s> 112 bytes

(a,b)=>{var r="";for(;a<b;a=a.AddDays(1))if($"{a:yyy}".SequenceEqual($"{a:MMdd}".Reverse()))r+=a+",";return r;};

C# lambda (Func) where inputs are DateTime and output is a string.

Code:

(a,b)=> {
    var r="";
    for(;a<b;a=a.AddDays(1)) {
        if($"{a:yyy}".SequenceEqual($"{a:MMdd}".Reverse()))
            r+=a+",";
    }
    return r;
};

Try them online!


答:
Python, 56

r is defined as:

```<code>from random import randint
n=0
def r(z):
    global n;n+=1
    return randint(1,n)
</code>```

the dice generator d:

```<code>import math;d=lambda:math.ceil(6.*r(r(r(r(r(r(0))))))/n)
</code>```

usage, eg, for 100 rolls:

```<code>for i in range(100):print d()
</code>```

Title: Dice from Changing Random Generator

Body:
Introduction

You are given a random integer generator with the following implementation

The first invocation always returns 1.

The second invocation returns a random integer between 1 and 2.

The third invocation returns a random integer between 1 and 3.

The nth invocation returns a random integer between 1 and n, inclusive.

Based on the above function, write a random dice generator that is perfectly random, returning a value between 1 and 6 (inclusive) with equal probability.

Rules

Your program/function should result in a random integer between 1 and 6, inclusive, in some usable form, i.e., to standard output or as a function return value.

The ascending random number generator above can be defined as a "free" function in your program (i.e., doesn't count toward your character count), or a separate script/program that is executed as needed, assuming the state (n) is persistent between calls.

Assume that no more than 1000 dice rolls will ever be requested in a single use case of your program, and the initial random number generator can be reset to 1 at the end of 1000 dice rolls to avoid overflow of n.

Your program may not use any other source of random numbers except the ascending random generator defined above.  You may of course request multiple random numbers from the random number generator for each single dice roll output.

This is code-golf, so winner is shortest answer or most votes in the event of a tie.  If you can generate 1000 dice rolls using less than 1000 generated random numbers, give yourself a 10-point efficiency bonus.

Example

```<code>./asc-rand
1 # random integer between 1 and 1
./asc-rand
1 # random integer between 1 and 2
./asc-rand
3 # random integer between 1 and 3
./asc-rand
4 # random integer between 1 and 4

# dice-gen generates random dice based on output of asc-rand program.
./dice-gen
3
./dice-gen
6
./dice-gen
5
./dice-gen
1
</code>```

Body:
Python, 56

r is defined as:

from random import randint
n=0
def r(z):
    global n;n+=1
    return randint(1,n)

the dice generator d:

import math;d=lambda:math.ceil(6.*r(r(r(r(r(r(0))))))/n)

usage, eg, for 100 rolls:

for i in range(100):print d()


答:
C, 115 bytes

Function f() requires the string and index (1-indexed) as parameters and prints the result to stdout. Cursor should be after the specified character.

```<code>f(char*p,int n){char*s=p+n;for(;s>=p&&isalnum(*s)+(*s==95);--s);for(p=s+1;*p&&isalnum(*p)+(*p==95);putchar(*p++));}
</code>```

Title: Select the word around the given index in a given string

Body:
In Windows, when you perform double-click in a text, the word around your cursor in the text will be selected.

(This feature has more complicated properties, but they will not be required to be implemented for this challenge.)

For example, let | be your cursor in abc de|f ghi.

Then, when you double click, the substring def will be selected.

Input/Output

You will be given two inputs: a string and an integer.

Your task is to return the word-substring of the string around the index specified by the integer.

Your cursor can be right before or right after the character in the string at the index specified.

If you use right before, please specify in your answer.

Specifications (Specs)

The index is guaranteed to be inside a word, so no edge cases like abc |def ghi or abc def| ghi.

The string will only contain printable ASCII characters (from U+0020 to U+007E).

The word "word" is defined by the regex (?<!\w)\w+(?!\w), where \w is defined by [abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_], or "alphanumeric characters in ASCII including underscore".

The index can be 1-indexed or 0-indexed.

If you use 0-indexed, please specify it in your answer.

Testcases

The testcases are 1-indexed, and the cursor is right after the index specified.

The cursor position is for demonstration purpose only, which will not be required to be outputted.

```<code>string    index     output    cursor position
abc def   2         abc       ab|c def
abc def   5         def       abc d|ef
abc abc   2         abc       ab|c abc
ab cd ef  4         cd        ab c|d ef
ab   cd   6         cd        ab   c|d
ab!cd     1         ab        a|b!cd
</code>```

Body:
C, 115 bytes

Function f() requires the string and index (1-indexed) as parameters and prints the result to stdout. Cursor should be after the specified character.

f(char*p,int n){char*s=p+n;for(;s>=p&&isalnum(*s)+(*s==95);--s);for(p=s+1;*p&&isalnum(*p)+(*p==95);putchar(*p++));}


答:
MATL, <s>16</s> 15 bytes

```<code>'\w+'5B#XXi>)1)
</code>```

Cursor is 1-indexed and after the character (as in the test cases).

Try it online! Or verify all test cases.

```<code>'\w+'    % Push string to be used as regex pattern
5B#XX    % Take input string implicitly. Apply regex. Push matches and ending indices
i>       % Take input number. Compare with obtained ending indices. Gives true for
         % ending indices that exceed the input number
)        % Use as logical index to select the corresponding matches
1)       % Select the first match. Implicitly display
</code>```

Body:
MATL, <s>16</s> 15 bytes

'\w+'5B#XXi>)1)

Cursor is 1-indexed and after the character (as in the test cases).

Try it online! Or verify all test cases.

'\w+'    % Push string to be used as regex pattern
5B#XX    % Take input string implicitly. Apply regex. Push matches and ending indices
i>       % Take input number. Compare with obtained ending indices. Gives true for
         % ending indices that exceed the input number
)        % Use as logical index to select the corresponding matches
1)       % Select the first match. Implicitly display


答:
C, 104 bytes

```<code>p[99];i,d;main(l){for(scanf("%d",&i);scanf("%[^a-zA-Z0-9_]%[a-zA-Z0-9_]%n",&d,&p,&l),i>l;i-=l);puts(p);}
</code>```

Expects the input on stdin to be the 0-based index followed by one space or newline, followed by the string. Maximal length for a word is 99 characters. E.g.:

```<code>2 abc def
</code>```

Body:
C, 104 bytes

p[99];i,d;main(l){for(scanf("%d",&i);scanf("%[^a-zA-Z0-9_]%[a-zA-Z0-9_]%n",&d,&p,&l),i>l;i-=l);puts(p);}

Expects the input on stdin to be the 0-based index followed by one space or newline, followed by the string. Maximal length for a word is 99 characters. E.g.:

2 abc def


答:
PowerShell v3+, <s>103</s> 101 bytes

```<code>param($a,$n)for(;$n[++$a]-match'\w'){}$i=$a--;for(;$n[--$a]-match'\w'-and$a-ge0){}-join$n[++$a..--$i]
</code>```

Kind of a goofy solution, but a different approach than others.

Takes input $a as the 0-based index of the string $n. Then, we find the boundaries of our word. While we've not reached the end of the string and/or we're still matching word-characters, we ++$a. Then, because of fenceposting, we set $i=$a--. Next, we crawl backwards, decrementing $a until it's either 0 or we hit a non-word-character. We then slice the input string based on those two demarcations (with some increment/decrements to account for OBOE), and -join it together to produce the result.

Examples

```<code>PS C:\Tools\Scripts\golfing> .\select-the-word-around-the-index.ps1 2 'This!test'
This

PS C:\Tools\Scripts\golfing> .\select-the-word-around-the-index.ps1 5 'This!test'
test
</code>```

Body:
PowerShell v3+, <s>103</s> 101 bytes

param($a,$n)for(;$n[++$a]-match'\w'){}$i=$a--;for(;$n[--$a]-match'\w'-and$a-ge0){}-join$n[++$a..--$i]

Kind of a goofy solution, but a different approach than others.

Takes input $a as the 0-based index of the string $n. Then, we find the boundaries of our word. While we've not reached the end of the string and/or we're still matching word-characters, we ++$a. Then, because of fenceposting, we set $i=$a--. Next, we crawl backwards, decrementing $a until it's either 0 or we hit a non-word-character. We then slice the input string based on those two demarcations (with some increment/decrements to account for OBOE), and -join it together to produce the result.

Examples

PS C:\Tools\Scripts\golfing> .\select-the-word-around-the-index.ps1 2 'This!test'
This

PS C:\Tools\Scripts\golfing> .\select-the-word-around-the-index.ps1 5 'This!test'
test


答:
Clojure, 92 bytes

```<code>(fn[x k](let[[u i](map #(re-seq #"\w+"(apply str %))(split-at k x))](str(last u)(nth i 0))))
</code>```

First, splits input string at position k into two strings. Then for these strings find occurrences of "\w+" and return them as list. Then concatenate the last element of first list and the first element of second list.

See it online: https://ideone.com/Dk2FIs

Body:
Clojure, 92 bytes

(fn[x k](let[[u i](map #(re-seq #"\w+"(apply str %))(split-at k x))](str(last u)(nth i 0))))

First, splits input string at position k into two strings. Then for these strings find occurrences of "\w+" and return them as list. Then concatenate the last element of first list and the first element of second list.

See it online: https://ideone.com/Dk2FIs


答:
PowerShell, 147 bytes

```<code>param($a)function z{param($n,$d)ls $n.fullname|%{$f=$_.mode[0]-ne"d";Write-Host(" "*$d*4)"$($_.name)$(("\")[$f])";If(!$f){z $_($d+1)}}}$a;z(gi $a)1
</code>```

Man, I feel like PS should be able to do something like the bash answer, but I'm not coming up with anything shorter than what I've got here.

Explanation:

```<code>param($a)                     # assign first passed parameter to $a
function z{param($n,$d) ... } # declare function z with $n and $d as parameters
ls $n.fullname                # list out contents of directory
|%{ ... }                     # foreach
$f=$_.namde[0]-ne"d"          # if current item is a file, $f=true
Write-Host                    # writes output to the console
(" "*$d*4)                    # multiplies a space by the depth ($d) and 4
"$($_.name)$(("\")[$f])"      # item name + the trailing slash if it is a directory
;if(!$f){z $_($d+1)}          # if it is a directory, recursively call z
$a                            # write first directory to console
z(gi $a)1                     # call z with $a as a directoryinfo object and 1 as the starting depth
</code>```

Body:
PowerShell, 147 bytes

param($a)function z{param($n,$d)ls $n.fullname|%{$f=$_.mode[0]-ne"d";Write-Host(" "*$d*4)"$($_.name)$(("\")[$f])";If(!$f){z $_($d+1)}}}$a;z(gi $a)1

Man, I feel like PS should be able to do something like the bash answer, but I'm not coming up with anything shorter than what I've got here.

Explanation:

param($a)                     # assign first passed parameter to $a
function z{param($n,$d) ... } # declare function z with $n and $d as parameters
ls $n.fullname                # list out contents of directory
|%{ ... }                     # foreach
$f=$_.namde[0]-ne"d"          # if current item is a file, $f=true
Write-Host                    # writes output to the console
(" "*$d*4)                    # multiplies a space by the depth ($d) and 4
"$($_.name)$(("\")[$f])"      # item name + the trailing slash if it is a directory
;if(!$f){z $_($d+1)}          # if it is a directory, recursively call z
$a                            # write first directory to console
z(gi $a)1                     # call z with $a as a directoryinfo object and 1 as the starting depth


答:
JavaScript (ES6), 57 bytes

```<code>f=(s,n)=>s.slice(0,n).match(/\w*$/)+s.slice(n).match(/\w*/)
</code>```

Simply slices the string at the cursor point (which is before the 0-indexed character, which works out the same as after the 1-indexed character), then extracts and concatenates the adjacent word fragments. Even returns a sensible result when the cursor is at the start, end, or nowhere near a word.

Body:
JavaScript (ES6), 57 bytes

f=(s,n)=>s.slice(0,n).match(/\w*$/)+s.slice(n).match(/\w*/)

Simply slices the string at the cursor point (which is before the 0-indexed character, which works out the same as after the 1-indexed character), then extracts and concatenates the adjacent word fragments. Even returns a sensible result when the cursor is at the start, end, or nowhere near a word.


答:
PHP, 98 bytes

```<code>function f($s,$p){foreach(preg_split('#\W+#',$s,-1,4)as$m)if($m[1]+strlen($m[0])>=$p)return$m[0];}
</code>```

splits the string by non-word-characters, remembering their position (4 == PREG_SPLIT_OFFSET_CAPTURE), loops through the words until position is reached.

PHP strings are 0-indexed, cursor before character, but may be before or after the word

Body:
PHP, 98 bytes

function f($s,$p){foreach(preg_split('#\W+#',$s,-1,4)as$m)if($m[1]+strlen($m[0])>=$p)return$m[0];}

splits the string by non-word-characters, remembering their position (4 == PREG_SPLIT_OFFSET_CAPTURE), loops through the words until position is reached.

PHP strings are 0-indexed, cursor before character, but may be before or after the word


答:
Octave, <s>37</s> <s>56</s> <s>54</s> 43 bytes

Thanks to @LuisMendo for removing 8 bytes!

```<code>@(s)s(1)==35&(isvarname(s(2:end))|nnz(s)<2)
</code>```

Not very golfy, but very built-inny.

Edit: The original code accepted strings with no leading '#'. I guess I should have stuck with regex.

Test suite on ideone.

Title: #Hashtag_or_not

Body:
In this code golf challenge, you will verify hashtags!

#What_your_code_should_do

Input is a string. Output a truthy value if it is a valid hashtag, and a falsy value otherwise.

We define a string as a valid Hashtag if ...

It starts with a hash (#).

It doesn't have a number right after the hashtag (e.g. #2016USElection isn't a  valid hashtag).

It doesn't have any "special characters" (i.e. any character that isn't an alphabet, underscore (_) or a number).

You can assume that the input only contains ASCII characters. (It would be unfair if we did Unicode too.)

#Rules

Basic code-golf rules apply.

#Examples

Truthy:

```<code>#
#e
#_ABC
#thisisanunexpectedlylongstringxoxoxoxo
#USElection2016
</code>```

Falsy:

```<code>Hello, World!
#12thBday
#not-valid
#alsoNotValid!
#!not_a_hash
</code>```

Body:
Octave, <s>37</s> <s>56</s> <s>54</s> 43 bytes

Thanks to @LuisMendo for removing 8 bytes!

@(s)s(1)==35&(isvarname(s(2:end))|nnz(s)<2)

Not very golfy, but very built-inny.

Edit: The original code accepted strings with no leading '#'. I guess I should have stuck with regex.

Test suite on ideone.


答:
Python 3, <s>112</s> 140 bytes

```<code>from string import*
p='_'+printable[:62]
def f(s,h,r=''):
 while s[h]in p and h>-1:h-=1
 while h+1<len(s)and s[h]in p:h+=1;r+=s[h]
 return r
</code>```

0-indexed.

Seeks backward to the first alphanumeric character from the index, then goes forward to the last alphanumeric character after the index. There's probably a smarter way to do this.

Try it

Body:
Python 3, <s>112</s> 140 bytes

from string import*
p='_'+printable[:62]
def f(s,h,r=''):
 while s[h]in p and h>-1:h-=1
 while h+1<len(s)and s[h]in p:h+=1;r+=s[h]
 return r

0-indexed.

Seeks backward to the first alphanumeric character from the index, then goes forward to the last alphanumeric character after the index. There's probably a smarter way to do this.

Try it


问:
Forecast the weather
Write the shortest program to forecast the weather for the next 7 days

The input (from stdin) is the weekday and the season

The output (to stdout) is seven lines weekday and the temperature in centigrade

The weekdays begin on the input weekday

The temperatures are random numbers with the range depending on the season

```
Spring 10 - 30 degrees
Summer 20 - 40 degrees
Autumn  5 - 25 degrees  (Fall is a synonym for autumn)
Winter -5 - 15 degrees
```

Sample Input

Thursday Winter

Sample Output

```
Thursday -1
Friday 3
Saturday 8
Sunday 7
Monday 10
Tuesday 10
Wednesday -1
```

Your program must not have identical output every time it is run with the same input

答:
Javascript - 251 chars

```<code>d=['Mon','Tues','Wednes','Thurs','Fri','Satur','Sun'],g=function(c){return Math.random()*21+c|0},p=prompt();for(i=0,j=7,t=true;i<j;i++){t=t&&p.indexOf(d[i])!=0;t?j++:console.log(d[i>6?i-7:i]+'day '+g(/mm/.test(p)?20:/g/.test(p)?10:/te/.test(p)?-5:5))}
</code>```

Unfortunately the script does not meet the stdin/stdout requirement but it accepts Fall as a synonym for Autumn.

Whitespaced:

```<code>  d = [
    'Mon'
  , 'Tues'
  , 'Wednes'
  , 'Thurs'
  , 'Fri'
  , 'Satur'
  , 'Sun'
  ]
, g = function(c) {
    return Math.random()*21+c|0
  }
, p = prompt()

  ;

  for(i = 0, j = 7, t = true; i < j; i++) {
    t = t && p.indexOf(d[i]) != 0;
    t ?
      j++ :
      console.log(d[i > 6 ? i - 7 : i] + 'day ' + g(/mm/.test(p) ?
                                                      20 :
                                                    /g/.test(p) ?
                                                      10 :
                                                    /te/.test(p) ?
                                                      -5 :
                                                      5
                                                    )
                  )
  }
</code>```

ContentLicense: CC BY-SA 2.5

Title: Forecast the weather

Body:
Javascript - 251 chars

d=['Mon','Tues','Wednes','Thurs','Fri','Satur','Sun'],g=function(c){return Math.random()*21+c|0},p=prompt();for(i=0,j=7,t=true;i<j;i++){t=t&&p.indexOf(d[i])!=0;t?j++:console.log(d[i>6?i-7:i]+'day '+g(/mm/.test(p)?20:/g/.test(p)?10:/te/.test(p)?-5:5))}

Unfortunately the script does not meet the stdin/stdout requirement but it accepts Fall as a synonym for Autumn.

Whitespaced:

  d = [
    'Mon'
  , 'Tues'
  , 'Wednes'
  , 'Thurs'
  , 'Fri'
  , 'Satur'
  , 'Sun'
  ]
, g = function(c) {
    return Math.random()*21+c|0
  }
, p = prompt()

  ;

  for(i = 0, j = 7, t = true; i < j; i++) {
    t = t && p.indexOf(d[i]) != 0;
    t ?
      j++ :
      console.log(d[i > 6 ? i - 7 : i] + 'day ' + g(/mm/.test(p) ?
                                                      20 :
                                                    /g/.test(p) ?
                                                      10 :
                                                    /te/.test(p) ?
                                                      -5 :
                                                      5
                                                    )
                  )
  }


答:
C#, 92 bytes

```<code>s=>s[0]=='#'&s.Length>1&&(s[1]<48|s[1]>57)&s.Skip(1).All(x=>char.IsLetterOrDigit(x)|x=='_');
</code>```

C# lambda (Predicate) where input is a string and output is a bool.

Try it online!

Title: #Hashtag_or_not

Body:
C#, 92 bytes

s=>s[0]=='#'&s.Length>1&&(s[1]<48|s[1]>57)&s.Skip(1).All(x=>char.IsLetterOrDigit(x)|x=='_');

C# lambda (Predicate) where input is a string and output is a bool.

Try it online!


答:
Retina, 22

```
(1)+¶(?<-1>.)*\b|\W.+

```

Try it online! or verify all test cases. The regular program takes the cursor position in unary followed by a newline and then the string. The test suite has additional code to run in per line mode, and uses a \ as a delimiter, and it uses decimal, for convenience.

Uses balancing groups to find the cursor position, then backtracks up to a word boundary. Deletes the text up to the word, and then after the word.

Body:
Retina, 22

(1)+¶(?<-1>.)*\b|\W.+

Try it online! or verify all test cases. The regular program takes the cursor position in unary followed by a newline and then the string. The test suite has additional code to run in per line mode, and uses a \ as a delimiter, and it uses decimal, for convenience.

Uses balancing groups to find the cursor position, then backtracks up to a word boundary. Deletes the text up to the word, and then after the word.


答:
Python 2, 138 bytes

Modified from this SO answer. Those are tabs for indentation, not spaces. Input will be taken like "C:/".

import os
p=input()
for r,d,f in os.walk(p):
    t=r.replace(p,'').count('/');print' '*t+os.path.basename(r)
    for i in f:print'   '*-~t+i
```
<p><strong>Try it online</strong> - <em>It's pretty interesting that I'm allowed to browse the directory on Ideone...</em></p>
<p>Same length:</p>
<pre class="lang-python prettyprint-override"><code>from os import*
p=input()
for r,d,f in walk(p):
    t=r.replace(p,'').count(sep);print' '*t+path.basename(r)
    for i in f:print'   '*-~t+i
</code>```

Body:
Given a directory (such as C:/), given from stdin or read from a file, produce a directory tree, with each file/folder indented based on its depth.

Example

If I have a C:/ drive which only contains two folders foo and bar, and bar is empty while foo contains baz.txt, then running with input C:/ produces:

```<code>C:/
    bar/
    foo/
        baz.txt
</code>```

while running with input C:/foo/ should produce

```<code>foo/
    baz.txt
</code>```

As this is codegolf, lowest byte count wins. The file extensions (such as baz.txt) are optional.
Extra notes: hidden files can be ignored, directories must actually exist, it can be assumed that files do not contain unprintable characters or new lines but all other printable ASCII characters are fine (file names with spaces must be supported). Output can be written to file or stdout. The indentations can be made up of either a tab character or 4 spaces.

Body:
Python 2, 138 bytes

Modified from this SO answer. Those are tabs for indentation, not spaces. Input will be taken like "C:/".

import os
p=input()
for r,d,f in os.walk(p):
    t=r.replace(p,'').count('/');print' '*t+os.path.basename(r)
    for i in f:print'   '*-~t+i

Try it online - It's pretty interesting that I'm allowed to browse the directory on Ideone...

Same length:

from os import*
p=input()
for r,d,f in walk(p):
    t=r.replace(p,'').count(sep);print' '*t+path.basename(r)
    for i in f:print'   '*-~t+i