问:
Reduce and generalize a list of string
The goal of this challenge is to reduce a list of string to a shorter more general list of string.

Input

The Input is provided with space between the string (a b c) or in list form (["a","b", "c"]). It's a list list of string that can be of the following form :

aaa

aaaX

aaaX/Y

With aaa any set of non capital alphabetic letter, and X or Y any digit between 0 and 9.

Ouput

A list of generalized string that can be separated by anything. String are of the form :

aaa

aaaX

aaaX/Y

With aaa any set of non capital alphabetic letter that were in the input list. X and Y stay the same and symbolise the digit. The goal of the challenge is to reduce the input list of string into their generic representation.

Examples

Two strings can be reduced :

```<code>Input : regex1 regex2 split1/0
Output : regexX splitX/Y
</code>```

Full example :

```<code>Input : toto toto titi titi1 titi2 titi5 tutu tutu0 tutu1 tutu1/2 tutu0/1
Output : toto titi titiX tutu tutuX tutuX/Y
</code>```

Another example :

```<code>Input: ["foo0","bar0","baz0/0","eth0/0","eth0/1","eth1/0","eth1/1","vlan8","modem0"]

Output: ["fooX","barX","bazX/Y","ethX/Y","vlanX","modemX"]
</code>```

Scoring

This is code-golf; shortest code in bytes wins.

答:
Retina, <s>25</s> <s>18</s> 13 bytes

6 byte thanks to FryAmTheEggman, and for inspiration of extra 1 byte.

```<code>\d
X
/X
/Y
D`
</code>```

Try it online!

Title: Reduce and generalize a list of string

Body:
Retina, <s>25</s> <s>18</s> 13 bytes

6 byte thanks to FryAmTheEggman, and for inspiration of extra 1 byte.

\d
X
/X
/Y
D`

Try it online!


答:
Python, 69 bytes

```<code>import re
lambda s:set(re.sub("\d","X",s).replace("/X","/Y").split())
</code>```

ContentLicense: CC BY-SA 3.0

Title: Reduce and generalize a list of string

Body:
The goal of this challenge is to reduce a list of string to a shorter more general list of string.

Input

The Input is provided with space between the string (a b c) or in list form (["a","b", "c"]). It's a list list of string that can be of the following form :

aaa

aaaX

aaaX/Y

With aaa any set of non capital alphabetic letter, and X or Y any digit between 0 and 9.

Ouput

A list of generalized string that can be separated by anything. String are of the form :

aaa

aaaX

aaaX/Y

With aaa any set of non capital alphabetic letter that were in the input list. X and Y stay the same and symbolise the digit. The goal of the challenge is to reduce the input list of string into their generic representation.

Examples

Two strings can be reduced :

```<code>Input : regex1 regex2 split1/0
Output : regexX splitX/Y
</code>```

Full example :

```<code>Input : toto toto titi titi1 titi2 titi5 tutu tutu0 tutu1 tutu1/2 tutu0/1
Output : toto titi titiX tutu tutuX tutuX/Y
</code>```

Another example :

```<code>Input: ["foo0","bar0","baz0/0","eth0/0","eth0/1","eth1/0","eth1/1","vlan8","modem0"]

Output: ["fooX","barX","bazX/Y","ethX/Y","vlanX","modemX"]
</code>```

Scoring

This is code-golf; shortest code in bytes wins.

Body:
Python, 69 bytes

import re
lambda s:set(re.sub("\d","X",s).replace("/X","/Y").split())


问:
Is it truthy or falsy?
There are so many different ways to express whether something is true or not! The goal of this challenge is to produce a standardized output of truthy or falsy for various input truthy and falsy values.

For the purposes of this challenge, the following inputs are considered truthy:

A string representing a signed integer with a non-zero value (contains only the digits [0-9], with an optional - at the beginning). Note that the string -0 will never be given as input. A non-zero integer will never be preceded by a 0 (i.e. 01 will never be given as input, similarly -01 will never be gien as input).

The case-insensitive strings equivalent to one of defined, found, nonnil, non-nil, on, success, t, true, y, and yes

For the purposes of this challenge, the following inputs are considered falsy:

The string 0. Repeated zeros (00, 00...) will never be given as input.

An empty string

The case-insensitive strings equivalent to one of f, failure, false, n, nan, nil, no, notfound, not-found, null, nullptr, off, and undefined

Input

The input is a string representing a truthy/falsy value. The string may come from any source desired (stdio, function parameter, etc.). There is no leading/trailing whitespace.

The input is guaranteed to match one of the allowed truthy/falsy values above (i.e. you do not need to provide any error handling).

Output

Your program/function must output a truthy/falsy value which represents the "truthy-ness" or "falsy-ness" of the input.
You are only allowed to specify exactly 1 truthy and 1 falsy value which your output must convert the input to (these are your "standardized" truthy/falsy value). The output may be written to any sink desired (stdio, return value, output parameter, etc.).

Please specify what truthy and falsy value you chose in your answer.

Ex.: If you choose the string true as a truthy value, you cannot also have the integer 1 for truthy.

Test Cases

Test cases are formatted as the first line is the input, and the second line is the output.

```<code>-1
true

1
true

1234
true

-4321
true

defined
true

deFined
true

Found
true

nonnil
true

non-nil
true

ON
true

SuCCess
true

T
true

true
true

y
true

YeS
true

0
false

'' (empty string)
false

faLSE
false

f
false

Failure
false

n
false

NaN
false

nil
false

no
false

notfound
false

not-Found
false

NULL
false

nullptr
false

OFF
false

unDefined
false
</code>```

Scoring

This is code-golf; shortest code in bytes wins. Standard loopholes apply. You may use any built-ins desired.

答:
Python, 83 bytes

```<code>lambda x:x.lower()[:3]in['fou','non','on']or x[:1].lower()in'dsty-123456789'and''<x
</code>```

https://repl.it/ClgO/1

Title: Is it truthy or falsy?

Body:
Python, 83 bytes

lambda x:x.lower()[:3]in['fou','non','on']or x[:1].lower()in'dsty-123456789'and''<x

https://repl.it/ClgO/1


问:
Print an alphabet wave
You are to print this exact text:

```<code>ABABABABABABABABABABABABAB
BCBCBCBCBCBCBCBCBCBCBCBCBC
CDCDCDCDCDCDCDCDCDCDCDCDCD
DEDEDEDEDEDEDEDEDEDEDEDEDE
EFEFEFEFEFEFEFEFEFEFEFEFEF
FGFGFGFGFGFGFGFGFGFGFGFGFG
GHGHGHGHGHGHGHGHGHGHGHGHGH
HIHIHIHIHIHIHIHIHIHIHIHIHI
IJIJIJIJIJIJIJIJIJIJIJIJIJ
JKJKJKJKJKJKJKJKJKJKJKJKJK
KLKLKLKLKLKLKLKLKLKLKLKLKL
LMLMLMLMLMLMLMLMLMLMLMLMLM
MNMNMNMNMNMNMNMNMNMNMNMNMN
NONONONONONONONONONONONONO
OPOPOPOPOPOPOPOPOPOPOPOPOP
PQPQPQPQPQPQPQPQPQPQPQPQPQ
QRQRQRQRQRQRQRQRQRQRQRQRQR
RSRSRSRSRSRSRSRSRSRSRSRSRS
STSTSTSTSTSTSTSTSTSTSTSTST
TUTUTUTUTUTUTUTUTUTUTUTUTU
UVUVUVUVUVUVUVUVUVUVUVUVUV
VWVWVWVWVWVWVWVWVWVWVWVWVW
WXWXWXWXWXWXWXWXWXWXWXWXWX
XYXYXYXYXYXYXYXYXYXYXYXYXY
YZYZYZYZYZYZYZYZYZYZYZYZYZ
ZAZAZAZAZAZAZAZAZAZAZAZAZA
</code>```

Specs

You can print all lowercase instead of all uppercase. However, case must be consistent throughout the output.

You may print one extra trailing linefeed.

Scoring

Since this is an alphabet wave that fluctuates to a small extent, your code should also be small in terms of byte-count. In fact, the smallest code in terms of byte-count wins.

答:
ListSharp, 236 bytes

```<code>ROWS x=ROWSPLIT "A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,T,S,U,V,W,X,Y,Z,A" BY [","]
[FOREACH NUMB IN 1 TO 26 AS i]
{
STRG t =""
[FOREACH NUMB IN 1 TO 13 AS j]
{
STRG e=GETLINE x [i]
STRG r=GETLINE x [i+1]
STRG t=t+e+r
}
ROWS s=s+t
}
SHOW=s
</code>```

Feel free to comment if you want anything to be explained to you

Execution screenshot:

Title: Print an alphabet wave

Body:
ListSharp, 236 bytes

ROWS x=ROWSPLIT "A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,T,S,U,V,W,X,Y,Z,A" BY [","]
[FOREACH NUMB IN 1 TO 26 AS i]
{
STRG t =""
[FOREACH NUMB IN 1 TO 13 AS j]
{
STRG e=GETLINE x [i]
STRG r=GETLINE x [i+1]
STRG t=t+e+r
}
ROWS s=s+t
}
SHOW=s

Feel free to comment if you want anything to be explained to you

Execution screenshot:


答:
Perl, <S>29</S> 27 bytes

Includes +1 for -p

Give input list as seperate lines on STDIN:

```<code>perl reduce.pl
regex1
regex2
split1/0
^D
</code>```

reduce.pl:

```<code>#!/usr/bin/perl -p
s/\d/X/&&s//Y/;$_ x=!$$_++
</code>```

Title: Reduce and generalize a list of string

Body:
Perl, <S>29</S> 27 bytes

Includes +1 for -p

Give input list as seperate lines on STDIN:

perl reduce.pl
regex1
regex2
split1/0
^D

reduce.pl:

#!/usr/bin/perl -p
s/\d/X/&&s//Y/;$_ x=!$$_++


问:
Implement Takewhile

Introduction and Credit

Today without a fancy prelude: Please implement takewhile.

A variation of this (on a non-trivial data structure) was an assignment at my university functional programming course. This assignment is now closed and has been discussed in class and I have my professor's permission to post it here (I asked explicitly).

Specification

Input

The input will be a list (or your language's equivalent concept) of positive integers.

Output

The output should be a list (or your language's equivalent concept) of positive integers.

What to do?

Your task is to implement takewhile (language built-ins are allowed) with the predicate that the number under consideration is even (to focus on takewhile).

So you iterate over the list from start to end and while the condition (is even) holds, you copy to the output-list and as soon as you hit an element that doesn't make the condition true, you abort the operation and output (a step-by-step example is below). This higher-order functionality is also called takeWhile (takewhile).

Potential corner cases

The order of the output list compared to the input list may not be changed, e.g. [14,42,2] may not become [42,14].

The empty list is a valid in- and output.

Who wins?

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

Standard rules apply of course.

Test Vectors

```<code>[14, 42, 2324, 97090, 4080622, 171480372] -> [14, 42, 2324, 97090, 4080622, 171480372]
[42, 14, 42, 2324] -> [42, 14, 42, 2324]
[7,14,42] -> []
[] -> []
[171480372, 13, 14, 42] -> [171480372]
[42, 14, 42, 43, 41, 4080622, 171480372] -> [42, 14, 42]
</code>```

Step-by-Step Example

```<code>Example Input: [42, 14, 42, 43, 41, 4080622, 171480372]

Consider first element: 42
42 is even (21*2)
Put 42 into output list, output list is now [42]

Consider second element: 14
14 is even (7*2)
Put 14 into output list, output list is now [42,14]

Consider third element: 42
42 is even (21*2)
Put 42 into output list, output list is now [42,14,42]

Consider fourth element: 43
43 is not even (2*21+1)
Drop 43 and return the current output list

return [42,14,42]
</code>```

答:
Javascript (using external library - Enumerable) (42 bytes)

```<code>n=>_.From(n).TakeWhile(y=>y%2<1).ToArray()
</code>```

Code explanation: Library built in implementation...

Title: Implement Takewhile

Body:
Javascript (using external library - Enumerable) (42 bytes)

n=>_.From(n).TakeWhile(y=>y%2<1).ToArray()

Code explanation: Library built in implementation...


答:
Perl 6, 50 bytes

```<code>say .join x 13 for flat('A'..'Z','A').rotor(2=>-1)
</code>```

Title: Print an alphabet wave

Body:
You are to print this exact text:

```<code>ABABABABABABABABABABABABAB
BCBCBCBCBCBCBCBCBCBCBCBCBC
CDCDCDCDCDCDCDCDCDCDCDCDCD
DEDEDEDEDEDEDEDEDEDEDEDEDE
EFEFEFEFEFEFEFEFEFEFEFEFEF
FGFGFGFGFGFGFGFGFGFGFGFGFG
GHGHGHGHGHGHGHGHGHGHGHGHGH
HIHIHIHIHIHIHIHIHIHIHIHIHI
IJIJIJIJIJIJIJIJIJIJIJIJIJ
JKJKJKJKJKJKJKJKJKJKJKJKJK
KLKLKLKLKLKLKLKLKLKLKLKLKL
LMLMLMLMLMLMLMLMLMLMLMLMLM
MNMNMNMNMNMNMNMNMNMNMNMNMN
NONONONONONONONONONONONONO
OPOPOPOPOPOPOPOPOPOPOPOPOP
PQPQPQPQPQPQPQPQPQPQPQPQPQ
QRQRQRQRQRQRQRQRQRQRQRQRQR
RSRSRSRSRSRSRSRSRSRSRSRSRS
STSTSTSTSTSTSTSTSTSTSTSTST
TUTUTUTUTUTUTUTUTUTUTUTUTU
UVUVUVUVUVUVUVUVUVUVUVUVUV
VWVWVWVWVWVWVWVWVWVWVWVWVW
WXWXWXWXWXWXWXWXWXWXWXWXWX
XYXYXYXYXYXYXYXYXYXYXYXYXY
YZYZYZYZYZYZYZYZYZYZYZYZYZ
ZAZAZAZAZAZAZAZAZAZAZAZAZA
</code>```

Specs

You can print all lowercase instead of all uppercase. However, case must be consistent throughout the output.

You may print one extra trailing linefeed.

Scoring

Since this is an alphabet wave that fluctuates to a small extent, your code should also be small in terms of byte-count. In fact, the smallest code in terms of byte-count wins.

Body:
Perl 6, 50 bytes

say .join x 13 for flat('A'..'Z','A').rotor(2=>-1)


问:
Smile! Just smile
It's well known that Brainf*ck is very bad at Kolmogorov-complexity problems, for example, it requires around 100 characters just to print "Hello world".

However, there might be texts where Brainf*ck is just very good at.

Your task is now to write a program that takes no input, and it displays the following:

```<code>☺
</code>```

That is, a smiley face (ASCII 1, if you browser does not render it).

Brainf*ck can do it in 2 characters.

```<code>+.
</code>```

Try to find a language that beats it!

We assume your console can actually display that character (or your font has it, etc.).

Shortest code wins. If there are more of the same length, the first wins, but I'll upvote the others as well.

EDIT: I'm very sorry, I did not think the first post arrives this soon. A quick edit: the language has to be Turing-complete!

答:
Doesn't beat 2 chars, but:

PHP 11 chars.

```<code><?=chr(1)?>
</code>```

For everyone saying you can simply place the smiley in php and it will output ☺:

Running it with php.exe in the command line gives Γÿǁ and placing it in the browser gives â˜º

It does not work.

Title: Smile! Just smile

Body:
Doesn't beat 2 chars, but:

PHP 11 chars.

<?=chr(1)?>

For everyone saying you can simply place the smiley in php and it will output ☺:

Running it with php.exe in the command line gives Γÿǁ and placing it in the browser gives â˜º

It does not work.


问:
Automate the OEIS
We see a lot of challenges here asking for a function to create a sequence from the OEIS.  While these challenges are fun, as a programmer I see an opportunity for automation.

Your challenge is to make a program that takes the index of a sequence (e.g. A172141) and some integer n (e.g. 7), and pulls the appropriate value from the appropriate webpage.

I/O

As mentioned, your program should take a sequence index and some value n as input and output the nth term in that sequence. You accept any index in the sequence's B-files. If the index is greater than the largest index listed in the B-files you may throw an exception or output whatever you choose (these are not in the test cases).  Standard methods of input and output are permitted.

Restrictions on web use

You should not access any websites other than https://oeis.org and http://oeis.org.  This includes url shorteners, your own personal website, and this question itself.  If you would like to access some other website and you believe that it is not unfair to allow you to do so, you can leave a comment and I will arbitrate.

Scoring

This is a code golf challenge so the program with the least bytes used in its source code wins.  Standard loopholes are disallowed.

Test Cases

Assuming that your machine has proper internet connection and the OEIS servers are up and running the following inputs and outputs should correspond.

```<code>A172141, 7   -> 980
A173429, 4   -> 276
A190394, 6   -> 16
A002911, 11  -> 960
A052170, 3   -> 24
A060296, 8   -> 3
A178732, 5   -> 27
A000001, 1   -> 1
A000796, 314 -> 3
A001622, 162 -> 8
A002206, -1  -> 1
</code>```

Tip

When accessing the B-files http://oeis.org/b.txt will redirect to the proper B-file.

答:
Python 3, <s>153</s> <s>146</s> 135 bytes

7 bytes thanks to FryAmTheEggman.

6 bytes thanks to Eamon Olive.

5 bytes thanks to Rod.

from urllib.request import*
def f(a,n):
 for l in urlopen("http://oeis.org/b%s.txt"%a[1:]):
  p,q=l.split()
  if n==p.decode():return q
```

<p>Call it like this:</p>

<pre class="lang-python prettyprint-override"><code>print(f("A000796","314"))
</code>```

Run on a machine where the default is utf-8.

Title: Automate the OEIS

Body:
Python 3, <s>153</s> <s>146</s> 135 bytes

7 bytes thanks to FryAmTheEggman.

6 bytes thanks to Eamon Olive.

5 bytes thanks to Rod.

from urllib.request import*
def f(a,n):
 for l in urlopen("http://oeis.org/b%s.txt"%a[1:]):
  p,q=l.split()
  if n==p.decode():return q

Call it like this:

print(f("A000796","314"))

Run on a machine where the default is utf-8.


答:
PHP, 102 bytes

```<code><?php $a='ABCDEFGHIJKLMNOPQRSTUVWXYZA';$i=-1;while($i++<25){echo str_repeat(substr($a,$i,2),13)."\n";}
</code>```

Title: Print an alphabet wave

Body:
PHP, 102 bytes

<?php $a='ABCDEFGHIJKLMNOPQRSTUVWXYZA';$i=-1;while($i++<25){echo str_repeat(substr($a,$i,2),13)."\n";}


答:
Perl, 59 bytes

($_,$v)=@ARGV;/./;say`curl oeis.org/$_/b$'.txt`=~/$v (.*)/m
```

<p>Needs <code>-M5.010</code> or <code>-E</code> to run. For instance : </p>

```$ cat oeis.pl
($_,$v)=@ARGV;/./;say`curl oeis.org/$_/b$'.txt`=~/$v (.*)/m
$ perl -M5.010 oeis.pl A178932 5 2>&-
27
```

Saved 8 bytes thanks to @Dennis answer, by removing http://, as he did.

Title: Automate the OEIS

Body:
We see a lot of challenges here asking for a function to create a sequence from the OEIS.  While these challenges are fun, as a programmer I see an opportunity for automation.

Your challenge is to make a program that takes the index of a sequence (e.g. A172141) and some integer n (e.g. 7), and pulls the appropriate value from the appropriate webpage.

I/O

As mentioned, your program should take a sequence index and some value n as input and output the nth term in that sequence. You accept any index in the sequence's B-files. If the index is greater than the largest index listed in the B-files you may throw an exception or output whatever you choose (these are not in the test cases).  Standard methods of input and output are permitted.

Restrictions on web use

You should not access any websites other than https://oeis.org and http://oeis.org.  This includes url shorteners, your own personal website, and this question itself.  If you would like to access some other website and you believe that it is not unfair to allow you to do so, you can leave a comment and I will arbitrate.

Scoring

This is a code golf challenge so the program with the least bytes used in its source code wins.  Standard loopholes are disallowed.

Test Cases

Assuming that your machine has proper internet connection and the OEIS servers are up and running the following inputs and outputs should correspond.

```<code>A172141, 7   -> 980
A173429, 4   -> 276
A190394, 6   -> 16
A002911, 11  -> 960
A052170, 3   -> 24
A060296, 8   -> 3
A178732, 5   -> 27
A000001, 1   -> 1
A000796, 314 -> 3
A001622, 162 -> 8
A002206, -1  -> 1
</code>```

Tip

When accessing the B-files http://oeis.org/b.txt will redirect to the proper B-file.

Body:
Perl, 59 bytes

($_,$v)=@ARGV;/./;say`curl oeis.org/$_/b$'.txt`=~/$v (.*)/m

Needs -M5.010 or -E to run. For instance :

$ cat oeis.pl
($_,$v)=@ARGV;/./;say`curl oeis.org/$_/b$'.txt`=~/$v (.*)/m
$ perl -M5.010 oeis.pl A178932 5 2>&-
27

Saved 8 bytes thanks to @Dennis answer, by removing http://, as he did.


答:
EXCEL: 53 bytes

```<code>=REPT(CHAR(ROW(A1)+64)&CHAR(MOD(ROW(A1),26)+65),13)
</code>```

Place in A1 and drag to desired length of wave (in this case, 26, one cell for each letter).

Title: Print an alphabet wave

Body:
EXCEL: 53 bytes

=REPT(CHAR(ROW(A1)+64)&CHAR(MOD(ROW(A1),26)+65),13)

Place in A1 and drag to desired length of wave (in this case, 26, one cell for each letter).


Title: Print an alphabet wave

Body:
Ruby, 41 bytes

26.times{|i|puts [*?A..?Z,?A][i,2]*''*13}


Title: Reduce and generalize a list of string

Body:
Brachylog, <s>61</s> <s>59</s> <s>44</s> 42 bytes

2 bytes thanks to Fatalize.

<s>:{:ef:{~s"0123456789","X".;?.}ac.}a:{rbh"/",?rbr:"Y"c.;?.}ad.</s>
<s>:{:ef:{~s"0123456789","X".;?.}ac.L(rbh"/",Lrbr:"Y"c.;.)}ad.</s>
<s>:{s"/",?rbbbr:"X/Y"c.;.?t~s@A;?rbr:"X"c.}ad.</s>
:{s"/",?rbbbr:"X/Y"c.|.t~s@A|rbr:"X"c.}ad.

Try it online!


答:
Bash + coreutils + w3m, <s>51</s> <s>45</s> 42 bytes

w3m oeis.org/b${1:1}.txt|sed "s/^$2 //p;d"
```

<p><em>Thanks to @EamonOlive for golfing off 3 bytes!</em></p>

<h3>Example run</h3>

<pre class="lang-bash prettyprint-override"><code>$ bash oeis.sh A172141 7
980
</code>```

How it works

w3m is a text-based web browser, which displays both HTML and plain text in readable format. Unlike curl, it follows redirects by default (this is required, since oeis.org/bxxxxxx.txt redirects to oeis.org/Axxxxxx/bxxxxxx.txt), doesn't produce any stray output to STDERR, and has a three-byte name.

The command

w3m oeis.org/b${1:1}.txt
```

<p>the desired URL, where <code>${1:1}</code> is the first command-line argument without its first character.</p>

<p>The output is piped to the command</p>

<pre class="lang-bash prettyprint-override"><code>sed "s/^$2 //p;d"
</code>```

which extracts the desired output. s/^$2 //p attempts to replace ^$2  (start of line, followed by the second command-line argument, followed by a space) with the empty string. If the substitution is successful, p prints its result. Afterwards, d unconditionally deletes the pattern to prevent sed from printing the entire input.

Title: Automate the OEIS

Body:
Bash + coreutils + w3m, <s>51</s> <s>45</s> 42 bytes

w3m oeis.org/b${1:1}.txt|sed "s/^$2 //p;d"

Thanks to @EamonOlive for golfing off 3 bytes!

Example run

$ bash oeis.sh A172141 7
980

How it works

w3m is a text-based web browser, which displays both HTML and plain text in readable format. Unlike curl, it follows redirects by default (this is required, since oeis.org/bxxxxxx.txt redirects to oeis.org/Axxxxxx/bxxxxxx.txt), doesn't produce any stray output to STDERR, and has a three-byte name.

The command

w3m oeis.org/b${1:1}.txt

the desired URL, where ${1:1} is the first command-line argument without its first character.

The output is piped to the command

sed "s/^$2 //p;d"

which extracts the desired output. s/^$2 //p attempts to replace ^$2  (start of line, followed by the second command-line argument, followed by a space) with the empty string. If the substitution is successful, p prints its result. Afterwards, d unconditionally deletes the pattern to prevent sed from printing the entire input.


答:
PHP, 50 bytes

```<code><?=preg_match('%^([-1-9dsty]|fo|n?on)%i',$argv[1])
</code>```

prints 1 for truthy, nothing for falsy

tried to come up with a different solution, but the shortest regex for falsy is 3 bytes longer than that for truthy: %^(0|fa|f?$|n(?!on)|of|u)%i

Title: Is it truthy or falsy?

Body:
There are so many different ways to express whether something is true or not! The goal of this challenge is to produce a standardized output of truthy or falsy for various input truthy and falsy values.

For the purposes of this challenge, the following inputs are considered truthy:

A string representing a signed integer with a non-zero value (contains only the digits [0-9], with an optional - at the beginning). Note that the string -0 will never be given as input. A non-zero integer will never be preceded by a 0 (i.e. 01 will never be given as input, similarly -01 will never be gien as input).

The case-insensitive strings equivalent to one of defined, found, nonnil, non-nil, on, success, t, true, y, and yes

For the purposes of this challenge, the following inputs are considered falsy:

The string 0. Repeated zeros (00, 00...) will never be given as input.

An empty string

The case-insensitive strings equivalent to one of f, failure, false, n, nan, nil, no, notfound, not-found, null, nullptr, off, and undefined

Input

The input is a string representing a truthy/falsy value. The string may come from any source desired (stdio, function parameter, etc.). There is no leading/trailing whitespace.

The input is guaranteed to match one of the allowed truthy/falsy values above (i.e. you do not need to provide any error handling).

Output

Your program/function must output a truthy/falsy value which represents the "truthy-ness" or "falsy-ness" of the input.
You are only allowed to specify exactly 1 truthy and 1 falsy value which your output must convert the input to (these are your "standardized" truthy/falsy value). The output may be written to any sink desired (stdio, return value, output parameter, etc.).

Please specify what truthy and falsy value you chose in your answer.

Ex.: If you choose the string true as a truthy value, you cannot also have the integer 1 for truthy.

Test Cases

Test cases are formatted as the first line is the input, and the second line is the output.

```<code>-1
true

1
true

1234
true

-4321
true

defined
true

deFined
true

Found
true

nonnil
true

non-nil
true

ON
true

SuCCess
true

T
true

true
true

y
true

YeS
true

0
false

'' (empty string)
false

faLSE
false

f
false

Failure
false

n
false

NaN
false

nil
false

no
false

notfound
false

not-Found
false

NULL
false

nullptr
false

OFF
false

unDefined
false
</code>```

Scoring

This is code-golf; shortest code in bytes wins. Standard loopholes apply. You may use any built-ins desired.

Body:
PHP, 50 bytes

<?=preg_match('%^([-1-9dsty]|fo|n?on)%i',$argv[1])

prints 1 for truthy, nothing for falsy

tried to come up with a different solution, but the shortest regex for falsy is 3 bytes longer than that for truthy: %^(0|fa|f?$|n(?!on)|of|u)%i


答:
Dyalog APL, 21 bytes

∪'/\d' '\d'⎕R'/Y' 'X'
```

⎕R regex replaces the left-side strings with the right-side ones

∪ returns the unique elements

TryAPL online!

Title: Reduce and generalize a list of string

Body:
The goal of this challenge is to reduce a list of string to a shorter more general list of string.

Input

The Input is provided with space between the string (a b c) or in list form (["a","b", "c"]). It's a list list of string that can be of the following form :

aaa

aaaX

aaaX/Y

With aaa any set of non capital alphabetic letter, and X or Y any digit between 0 and 9.

Ouput

A list of generalized string that can be separated by anything. String are of the form :

aaa

aaaX

aaaX/Y

With aaa any set of non capital alphabetic letter that were in the input list. X and Y stay the same and symbolise the digit. The goal of the challenge is to reduce the input list of string into their generic representation.

Examples

Two strings can be reduced :

```<code>Input : regex1 regex2 split1/0
Output : regexX splitX/Y
</code>```

Full example :

```<code>Input : toto toto titi titi1 titi2 titi5 tutu tutu0 tutu1 tutu1/2 tutu0/1
Output : toto titi titiX tutu tutuX tutuX/Y
</code>```

Another example :

```<code>Input: ["foo0","bar0","baz0/0","eth0/0","eth0/1","eth1/0","eth1/1","vlan8","modem0"]

Output: ["fooX","barX","bazX/Y","ethX/Y","vlanX","modemX"]
</code>```

Scoring

This is code-golf; shortest code in bytes wins.

Body:
Dyalog APL, 21 bytes

∪'/\d' '\d'⎕R'/Y' 'X'

⎕R regex replaces the left-side strings with the right-side ones

∪ returns the unique elements

TryAPL online!


答:
Python 2, <s>125</s> <s>118</s> 113 bytes

<s>7</s> 12 bytes saved thanks to Lynn

```<code>import re,urllib2 as u;lambda x,y:re.findall("(?<=%d ).*"%y,u.urlopen("http://oeis.org/b%s.txt"%x[1:]).read())[0]
</code>```

Well heres my go at my own problem. It is likely suboptimal but I think I did a pretty decent job. It creates an anonymous function that takes a string and integer as arguments and returns a string as the result or throws an error if the index is out of range.

This can be made into a 124 bytes full program.

```<code>import re,urllib2 as u;print re.findall("(?<=%d ).*"%input(),u.urlopen("http://oeis.org/b%s.txt"%raw_input()[1:]).read())[0]
</code>```

This prompts the user for the input.  First asking for the index and then the A-number of the sequence.

Title: Automate the OEIS

Body:
Python 2, <s>125</s> <s>118</s> 113 bytes

<s>7</s> 12 bytes saved thanks to Lynn

import re,urllib2 as u;lambda x,y:re.findall("(?<=%d ).*"%y,u.urlopen("http://oeis.org/b%s.txt"%x[1:]).read())[0]

Well heres my go at my own problem. It is likely suboptimal but I think I did a pretty decent job. It creates an anonymous function that takes a string and integer as arguments and returns a string as the result or throws an error if the index is out of range.

This can be made into a 124 bytes full program.

import re,urllib2 as u;print re.findall("(?<=%d ).*"%input(),u.urlopen("http://oeis.org/b%s.txt"%raw_input()[1:]).read())[0]

This prompts the user for the input.  First asking for the index and then the A-number of the sequence.


答:
C, 18 chars

Far from beating Brainf**k, but as good as C can get (I guess).

Only works on little-endian platforms, must run without parameters.

```<code>main(c){puts(&c);}
</code>```

Title: Smile! Just smile

Body:
It's well known that Brainf*ck is very bad at Kolmogorov-complexity problems, for example, it requires around 100 characters just to print "Hello world".

However, there might be texts where Brainf*ck is just very good at.

Your task is now to write a program that takes no input, and it displays the following:

```<code>☺
</code>```

That is, a smiley face (ASCII 1, if you browser does not render it).

Brainf*ck can do it in 2 characters.

```<code>+.
</code>```

Try to find a language that beats it!

We assume your console can actually display that character (or your font has it, etc.).

Shortest code wins. If there are more of the same length, the first wins, but I'll upvote the others as well.

EDIT: I'm very sorry, I did not think the first post arrives this soon. A quick edit: the language has to be Turing-complete!

Body:
C, 18 chars

Far from beating Brainf**k, but as good as C can get (I guess).

Only works on little-endian platforms, must run without parameters.

main(c){puts(&c);}


问:
Fraction to exact decimal
Write a program or function that given two integers a, b outputs a string containing a decimal number representing the fraction a/b exactly.

If a/b is integer, simply output the value, without a decimal dot or leading zeroes:

```<code>123562375921304812375087183597 / 2777 -> 44494913907563850333124661
81 / 3 -> 27
-6 / 2 -> -3
</code>```

If a/b is not integer but has a finite representation in base 10, output the value without leading or trailing zeroes (except a single zero before the dot):

```<code>1 / 2 -> 0.5
3289323463 / -250000000 -> -13.157293852
</code>```

Finally, if and only if (so no 0.999...) a/b is not integer and does not have a finite representation, output the finite part followed by the repeating part in parenthesis. The repeating part must be as small as possible, and start as early as possible.

```<code>-1 / 3 -> -0.(3)
235 / 14 -> 16.7(857142)
123 / 321 -> 0.(38317757009345794392523364485981308411214953271028037)
355 / 113 -> 3.(1415929203539823008849557522123893805309734513274336283185840707964601769911504424778761061946902654867256637168)
</code>```

Your program must work for all above examples in under 10 seconds on a modern desktop PC. Smallest program in bytes wins.

答:
Mathematica 198 bytes

```<code>i=Integer;t=ToString;a_~h~b_:=f[a/b];f@q_i:= t@q;
f@q_:=""<>{t@IntegerPart[q],".",RealDigits[FractionalPart[q]][[1]]//.{{x___,{k__i}}:> {x,"("<>(t/@{k})<>")"},{x__i,j___String}:>""<> {""<>t/@{x},j}}}
</code>```

UnGolfed

```<code>(* hand over quotient of a, b to function f *)
h[a_, b_] := f[a/b];

(* if the quotient is an integer, return it as a string *)
f[q_Integer] := ToString@q;

(* otherwise, return the integer part, followed by a decimal point ...*)
f[q_] := "" <> {ToString@IntegerPart[q], ".",

   (* replacing the repeating part (if it exists) between parentheses *)
   RealDigits[FractionalPart[q]][[1]] //. {{x___, {i__Integer}} :> {x, "(" <>(ToString /@ {i}) <> ")"},

   (* and the non-repeating part (if it exists) without parentheses *)
   {x__Integer, i___String} :> "" <> {"" <> ToString /@ {x}, i}}}
</code>```

Tests

```<code>h @@@ {{81, 3}, {-81, 3}, {1, 4}, {-13, 3}, {19, 7}, {3289323463, 25000}, {235, 14}, {1325, 14}}
</code>```

{"27", "-27", "0.25", "-4.(3)", "2.(714285)", "131572.93852",
"16.7(857142)", "94.6(428571)"}

Title: Fraction to exact decimal

Body:
Mathematica 198 bytes

i=Integer;t=ToString;a_~h~b_:=f[a/b];f@q_i:= t@q;
f@q_:=""<>{t@IntegerPart[q],".",RealDigits[FractionalPart[q]][[1]]//.{{x___,{k__i}}:> {x,"("<>(t/@{k})<>")"},{x__i,j___String}:>""<> {""<>t/@{x},j}}}

UnGolfed

(* hand over quotient of a, b to function f *)
h[a_, b_] := f[a/b];

(* if the quotient is an integer, return it as a string *)
f[q_Integer] := ToString@q;

(* otherwise, return the integer part, followed by a decimal point ...*)
f[q_] := "" <> {ToString@IntegerPart[q], ".",

   (* replacing the repeating part (if it exists) between parentheses *)
   RealDigits[FractionalPart[q]][[1]] //. {{x___, {i__Integer}} :> {x, "(" <>(ToString /@ {i}) <> ")"},

   (* and the non-repeating part (if it exists) without parentheses *)
   {x__Integer, i___String} :> "" <> {"" <> ToString /@ {x}, i}}}

Tests

h @@@ {{81, 3}, {-81, 3}, {1, 4}, {-13, 3}, {19, 7}, {3289323463, 25000}, {235, 14}, {1325, 14}}

{"27", "-27", "0.25", "-4.(3)", "2.(714285)", "131572.93852",
"16.7(857142)", "94.6(428571)"}


问:
Print a 10 by 10 grid of asterisks

Background

This is a standard textbook example to demonstrate for loops.

This is one of the first programs I learnt when I started learning programming ~10 years ago.

Task

You are to print this exact text:

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

Specs

You may have extra trailing newlines.

You may have extra trailing spaces (U+0020) at the end of each line, including the extra trailing newlines.

Scoring

This is code-golf. Shortest answer in bytes wins.

答:
Xtend, 33 bytes

```<code>[for(_:0..9)print('**********
')]
</code>```

... a Java dialect; [] is a lambda definition

Title: Print a 10 by 10 grid of asterisks

Body:
Xtend, 33 bytes

[for(_:0..9)print('**********
')]

... a Java dialect; [] is a lambda definition


答:
CJam, 36 bytes

```<code>"oeis.org/b"r1>+".txt"+gN%Sf%z~\ra#=
</code>```

Example run

```<code>$ cjam oeis.cjam <<< 'A172141 7'
980
</code>```

Title: Automate the OEIS

Body:
CJam, 36 bytes

"oeis.org/b"r1>+".txt"+gN%Sf%z~\ra#=

Example run

$ cjam oeis.cjam <<< 'A172141 7'
980


答:
R, <s>94</s> 89 bytes

```<code>t=read.table(paste0("http://oeis.org/b",substring(scan(,""),2),".txt"));t[t$V1==scan(),2]
</code>```

Using sprintf instead of paste0 results in the same bytecount:

```<code>t=read.table(sprintf("http://oeis.org/b%s.txt",substring(scan(,""),2)));t[t$V1==scan(),2]
</code>```

Five bytes saved thanks to plannapus.

Title: Automate the OEIS

Body:
R, <s>94</s> 89 bytes

t=read.table(paste0("http://oeis.org/b",substring(scan(,""),2),".txt"));t[t$V1==scan(),2]

Using sprintf instead of paste0 results in the same bytecount:

t=read.table(sprintf("http://oeis.org/b%s.txt",substring(scan(,""),2)));t[t$V1==scan(),2]

Five bytes saved thanks to plannapus.


答:
Javascript, <s>92</s> 78 bytes

```<code>a=a=>[...new Set(a.replace(/\d/g,"X").replace(/\/./g,"/Y").split` `)].join` `;
</code>```

Title: Reduce and generalize a list of string

Body:
Javascript, <s>92</s> 78 bytes

a=a=>[...new Set(a.replace(/\d/g,"X").replace(/\/./g,"/Y").split` `)].join` `;


答:
PHP 5.6, <s>93</s> 92 bytes

function f($i,$l){echo explode(' ',file('http://oeis.org/b'.substr($i,1).'.txt')[--$l])[1];}
```

This one is pretty straight forward. Pull the page with file(), get the line at $line - 1 (0-index), explode on the space and print out the second array element from that.

Title: Automate the OEIS

Body:
We see a lot of challenges here asking for a function to create a sequence from the OEIS.  While these challenges are fun, as a programmer I see an opportunity for automation.

Your challenge is to make a program that takes the index of a sequence (e.g. A172141) and some integer n (e.g. 7), and pulls the appropriate value from the appropriate webpage.

I/O

As mentioned, your program should take a sequence index and some value n as input and output the nth term in that sequence. You accept any index in the sequence's B-files. If the index is greater than the largest index listed in the B-files you may throw an exception or output whatever you choose (these are not in the test cases).  Standard methods of input and output are permitted.

Restrictions on web use

You should not access any websites other than https://oeis.org and http://oeis.org.  This includes url shorteners, your own personal website, and this question itself.  If you would like to access some other website and you believe that it is not unfair to allow you to do so, you can leave a comment and I will arbitrate.

Scoring

This is a code golf challenge so the program with the least bytes used in its source code wins.  Standard loopholes are disallowed.

Test Cases

Assuming that your machine has proper internet connection and the OEIS servers are up and running the following inputs and outputs should correspond.

```<code>A172141, 7   -> 980
A173429, 4   -> 276
A190394, 6   -> 16
A002911, 11  -> 960
A052170, 3   -> 24
A060296, 8   -> 3
A178732, 5   -> 27
A000001, 1   -> 1
A000796, 314 -> 3
A001622, 162 -> 8
A002206, -1  -> 1
</code>```

Tip

When accessing the B-files http://oeis.org/b.txt will redirect to the proper B-file.

Body:
PHP 5.6, <s>93</s> 92 bytes

function f($i,$l){echo explode(' ',file('http://oeis.org/b'.substr($i,1).'.txt')[--$l])[1];}

This one is pretty straight forward. Pull the page with file(), get the line at $line - 1 (0-index), explode on the space and print out the second array element from that.


答:
PHP, 104 bytes

```<code><?=join(' ',array_unique(explode(' ',preg_replace('%\d%','X',preg_replace('%\d/\d%', 'X/Y',$argv[1])))))
</code>```

expects input as single argument

I could replace the join(' ',array_unique(explode(' ',...))) with preg_replace('%(\b\w+\b)(?=.*\b\1\b)%','',...), but it´s 6 bytes shorter via the array.

127 bytes for list of arguments:

```<code><?foreach($argv as$i=>$s)if($i)$r[]=preg_replace('%\d%','X',preg_replace('%\d/\d%', 'X/Y',$s));echo join(' ',array_unique($r));
</code>```

120 bytes for a function on an array:

```<code>function r($a){foreach($a as$s)$r[]=preg_replace('%\d%','X',preg_replace('%\d/\d%', 'X/Y',$s));return array_unique($r);}
</code>```

Title: Reduce and generalize a list of string

Body:
PHP, 104 bytes

<?=join(' ',array_unique(explode(' ',preg_replace('%\d%','X',preg_replace('%\d/\d%', 'X/Y',$argv[1])))))

expects input as single argument

I could replace the join(' ',array_unique(explode(' ',...))) with preg_replace('%(\b\w+\b)(?=.*\b\1\b)%','',...), but it´s 6 bytes shorter via the array.

127 bytes for list of arguments:

<?foreach($argv as$i=>$s)if($i)$r[]=preg_replace('%\d%','X',preg_replace('%\d/\d%', 'X/Y',$s));echo join(' ',array_unique($r));

120 bytes for a function on an array:

function r($a){foreach($a as$s)$r[]=preg_replace('%\d%','X',preg_replace('%\d/\d%', 'X/Y',$s));return array_unique($r);}


答:
Improving on @gabe3886's answer (new account and not able to comment)

PHP 94 92 Bytes

```<code><?php for($i=0;$i<26;)echo str_repeat(substr('ABCDEFGHIJKLMNOPQRSTUVWXYZA',$i++,2),13)."\n";
</code>```

However if you suppress notices, it's 92 90 bytes

```<code><?php for(;@$i<26;)echo str_repeat(substr('ABCDEFGHIJKLMNOPQRSTUVWXYZA',@$i++,2),13)."\n";
</code>```

Title: Print an alphabet wave

Body:
You are to print this exact text:

```<code>ABABABABABABABABABABABABAB
BCBCBCBCBCBCBCBCBCBCBCBCBC
CDCDCDCDCDCDCDCDCDCDCDCDCD
DEDEDEDEDEDEDEDEDEDEDEDEDE
EFEFEFEFEFEFEFEFEFEFEFEFEF
FGFGFGFGFGFGFGFGFGFGFGFGFG
GHGHGHGHGHGHGHGHGHGHGHGHGH
HIHIHIHIHIHIHIHIHIHIHIHIHI
IJIJIJIJIJIJIJIJIJIJIJIJIJ
JKJKJKJKJKJKJKJKJKJKJKJKJK
KLKLKLKLKLKLKLKLKLKLKLKLKL
LMLMLMLMLMLMLMLMLMLMLMLMLM
MNMNMNMNMNMNMNMNMNMNMNMNMN
NONONONONONONONONONONONONO
OPOPOPOPOPOPOPOPOPOPOPOPOP
PQPQPQPQPQPQPQPQPQPQPQPQPQ
QRQRQRQRQRQRQRQRQRQRQRQRQR
RSRSRSRSRSRSRSRSRSRSRSRSRS
STSTSTSTSTSTSTSTSTSTSTSTST
TUTUTUTUTUTUTUTUTUTUTUTUTU
UVUVUVUVUVUVUVUVUVUVUVUVUV
VWVWVWVWVWVWVWVWVWVWVWVWVW
WXWXWXWXWXWXWXWXWXWXWXWXWX
XYXYXYXYXYXYXYXYXYXYXYXYXY
YZYZYZYZYZYZYZYZYZYZYZYZYZ
ZAZAZAZAZAZAZAZAZAZAZAZAZA
</code>```

Specs

You can print all lowercase instead of all uppercase. However, case must be consistent throughout the output.

You may print one extra trailing linefeed.

Scoring

Since this is an alphabet wave that fluctuates to a small extent, your code should also be small in terms of byte-count. In fact, the smallest code in terms of byte-count wins.

Body:
Improving on @gabe3886's answer (new account and not able to comment)

PHP 94 92 Bytes

<?php for($i=0;$i<26;)echo str_repeat(substr('ABCDEFGHIJKLMNOPQRSTUVWXYZA',$i++,2),13)."\n";

However if you suppress notices, it's 92 90 bytes

<?php for(;@$i<26;)echo str_repeat(substr('ABCDEFGHIJKLMNOPQRSTUVWXYZA',@$i++,2),13)."\n";


答:
Q/k (9 chars)

Can't do it in 2 unfortunately.

```<code>-1"\001";
</code>```

I seem to recall a bug in an older version of the interpreter which produced the other smile symbol in less characters. I'll look it up.

Edit: found the quirk. It only appears to work on windows versions of the interpreter:

```<code>q)1(1b);
☺
</code>```

Title: Smile! Just smile

Body:
Q/k (9 chars)

Can't do it in 2 unfortunately.

-1"\001";

I seem to recall a bug in an older version of the interpreter which produced the other smile symbol in less characters. I'll look it up.

Edit: found the quirk. It only appears to work on windows versions of the interpreter:

q)1(1b);
☺


问:
Dyalog's International Problem Solving Competition (Phase I) – Code Golf Edition
Every year, Dyalog Ltd. holds a student competition. The challenge there is to write good APL code. However, this is a multiple-holes (common theme is manipulation of data of any type and structure, especially special handling of empty data) code-golf version of the Phase I problems – open to any language. Enjoy!

Objective

Write ten complete programs (or functions, etc.) to solve the below problems using any one language. The point is that you must select a language that is good at various tasks, as opposed to the common golfing strategy of choosing the right tool for the (single) task. You may not use one solution as subroutine in another solution, and your score is the total byte count of all ten programs together.

Passing all the test cases is sufficient to be a valid submission.

Closing Date

18 August 2016.

Related: possibility of real world prizes

If you chose to use Dyalog APL (free download), you may also want to participate in the original competition, but note that the objective there is to submit quality code – not necessarily short code. If you are a student, you can win USD 100 for Phase I. Phase II (not included here) can win you up to USD 2000 and a free trip to Scotland.

The problems

Problem 1 – Statistics - Mean

Write a program that takes a numeric array and gives the mean (average) of the array.

Test cases:

[1,2,3,4,5,6] → 3.5

[] → 0

17 → 17

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

Problem 2 – Statistics - Median

Write a program that takes numeric data and gives the median of the data. The median is the number separating the higher half of the data from the lower half. The median can be found by arranging all the observations from lowest value to highest value and picking the middle one. If there is an even number of observations, then there is no single middle value; the median is then defined to be the mean of the two middle values.

Test cases:

[1,2,3,4,5,6,7,8,9] → 5

[[1,8,2],[7,3,6,4,5]] → 4.5

[] → 0

7 → 7

[1,1,1,9,1] → 1

[1,3,9,1] → 2

Problem 3 – Statistics - Mode

Write a program that takes a numeric list and gives the mode, most common value, of the list. If more than one number occurs the greatest number of times, return all such numbers.

Test cases:

[2,2,1,4,3,2,5,1,2] → 2 or [2]

[] → []

[1,2,3,4,1,2] → [1,2]

Problem 4 – Just Meshing Around

Write a program that takes strings or two numeric lists and gives the inputs shuffled into a string/list formed by alternately taking successive elements from each input. (This is known as a Faro shuffle.) The inputs do not have to be the same length. Begin with the first input.

Test cases:

'MENS' 'EKES' → 'MEEKNESS'

'Dyalog' 'APL' → 'DAyPaLlog'

'APL' 'Dyalog' → 'ADPyLalog'

[1,3,5,7] [2,4,6,8] → [1,2,3,4,5,6,7,8]

'' 'Hello' → 'Hello'

'Hello' ''→ 'Hello'

'' '' → ''

Problem 5 – You're Unique, Just Like Everyone Else

Write a program that takes a list or string and gives elements or characters that occur only once in the input.

Test cases:

[1,2,3,4,5] → [1,2,3,4,5]

[1,2,3,4,5,4,3,2,1] →[5]

'hello world' → 'he wrd'

'aabbcc' → ''

'' → ''

Problem 6 – Shorter Ones to the Front

Write a program that takes a list and sorts it by the length of each element. Note: an element of the list can be single number, in which case it must be counted as length 1.

Test cases:

['one','two','three','four','five','six'] → ['one','two','six','four','five','three']

[[2,4,3],[4,5],1,[7,3]] → [1,[4,5],[7,3],[2,4,3]] (sorting is not necessary)

[] → []

[[],[2,2],1] → [[],1,[2,2]]

Problem 7 – 3's and 5's

Write a program that takes a numeric list and returns all elements that are divisible by 3 or 5.

Test cases:

[1,2,3,4,5,6,7,8,9,10] → [3,5,6,9,10]

[] → []

[-1,-2,-3,-4,-5,-6,-7,-8,-9,-10] → [-10,-9,-6,-5,-3] (sorting is not necessary)

Problem 8 – Separating Out the Negative

Write a program that takes a numeric list and gives a two element list whose first element contains the values less than 0 (zero) in the input and the second element contains all values greater than or equal to 0 (zero).

Test cases:

[0,1,-2,3,-4,-5,6,7,8,-9,10] → [[-2,-4,-5,-9],[0,1,3,6,7,8,10]]

[1,2,3,4,5] → [[],[1,2,3,4,5]

[-1,-2,-3,-4,-5] → [[-1,-2,-3,-4,-5],[]]

[] → [[],[]]

Problem 9 – Delimited Text

Write a program that takes two strings where the first string is delimiters in the second string. The program should give the delimited text as a list of strings.

Test cases:

',' 'comma,delimited,values' → ['comma','delimited','values']

' ' 'break up words' → ['break','up','words']

',' ',' → ['','']

',' 'hello world' → ['hello world']

',' '' → ['']

',;' 'multi,delimited;values' → ['multi','delimited','values']

Order Total

Write a program which takes list of prices and a list which indicates the count ordered of each corresponding item and gives the total cost for the order.

Test cases:
[2.99,4.99,1.99] [5,0,2] → 18.93

[2.99,4.99,1.99] [0,0,0] → 0

[123.00] [0] → 0

[2.00 0.00] [3,4] → 6

[] [] → 0

I have explicit permission to post this challenge here from the original author of the competition. Feel free to verify by following the provided link and contacting the author. I gave the original competition author the link to this page within the minute I posted it, so they can check if I submit someone's answer as my own.

答:
Pyth, <s>88</s> <s>86</s> 84 bytes

Problem 1: Mean (6 bytes)

```<code>.O.n]Q
</code>```

Test suite.

Problem 2: Median (<s>23</s> 21 bytes)

```
<s>.O,hJ.x.<S*2K.n]QlK]0eJ</s>
.O<.x.<S*2K.n]QtlK]02
```

Test suite.

Problem 3: Mode (7 bytes)

```<code>{.x.M/Q
</code>```

Test suite.

Problem 4: Interleave (3 bytes)

```<code>.iF
</code>```

Test suite.

Problem 5: Unique (7 bytes)

```<code>fq1/QTQ
</code>```

Test suite.

Problem 6: Sort (6 bytes)

```<code>ol.n]N
</code>```

Test suite.

Problem 7: Divisibility (10 bytes)

```<code>f!*%T3%T5Q
</code>```

Test suite.

Problem 8: Separate (10 bytes)

```<code>,Jf<T0Q-QJ
</code>```

Test suite.

Problem 9: Split (12 bytes)

```
<s>AQu.ncRHGG]H</s>
u.ncRHGQ]E
```

Test suite.

Problem 10: Dot-product (4 bytes)

```<code>s*VF
</code>```

Test suite.

Body:
Pyth, <s>88</s> <s>86</s> 84 bytes

Problem 1: Mean (6 bytes)

.O.n]Q

Test suite.

Problem 2: Median (<s>23</s> 21 bytes)

<s>.O,hJ.x.<S*2K.n]QlK]0eJ</s>
.O<.x.<S*2K.n]QtlK]02

Test suite.

Problem 3: Mode (7 bytes)

{.x.M/Q

Test suite.

Problem 4: Interleave (3 bytes)

.iF

Test suite.

Problem 5: Unique (7 bytes)

fq1/QTQ

Test suite.

Problem 6: Sort (6 bytes)

ol.n]N

Test suite.

Problem 7: Divisibility (10 bytes)

f!*%T3%T5Q

Test suite.

Problem 8: Separate (10 bytes)

,Jf<T0Q-QJ

Test suite.

Problem 9: Split (12 bytes)

<s>AQu.ncRHGG]H</s>
u.ncRHGQ]E

Test suite.

Problem 10: Dot-product (4 bytes)

s*VF

Test suite.


问:
Input ∩ Source Code

Intro

The challenge is to create a program/function that prints the intersection of its own source code and a given string input. This is code golf and to be more precise:

Let I be the input set

{"a","b","c"}

Let S be the source code set

{"b","f"}

Then the intersection is what they share

I ∩ S = {"b"}

Input

Input is flexible. It should be able to handle the character encoding used for the source code.

Output

Output is flexible. It should be the set of characters that the input and source code share. Also, sets are unordered collections of distinct objects. In summary:

Output is flexible:

Could be any data structure (string or otherwise)

Could unordered

Could have a trailing \n

Should be distinct

Restriction

Similar to quine challenges, the program/function may not read its own source code and 0-byte solutions are not allowed.

Examples

#1

```<code>functor x(I){ return I ∩ self; }

Inputs                                Outputs
------                                -------
enter preformatted text here      ->  {"e","n","t","r","f","o","x"}

["Albrt"," Einstin"]              ->  {"l","r","t","n","s"}
</code>```

#2

```<code>(_)->_&"(_)->&\"\\"

Inputs                                Outputs
------                                -------
"Security at the expense of       ->  "
usability comes at the expense
of security."

(0____0)                          ->  (_)
</code>```

#3

```<code>ಠa益длф

Inputs                                Outputs
------                                -------
Far out in the uncharted backwaters ->"a"
of the unfashionable end of the
Western Spiral arm of the Galaxy lies
a small unregarded yellow sun.
Orbiting this at a distance of roughly
ninety-eight million miles is an
utterly insignificant little blue-green
planet whose ape-descended life forms
are so amazingly primitive that they
still think digital watches are a pretty
neat idea.

(ノಠ益ಠ)ノ彡┻━┻                      ->"ಠ益"
</code>```

Test Cases

```<code>Albert Einstein

\__( O__O)_/

!@#$%^&*()_+{}|:"<>?

1234567890-=[]\;',./

(ノಠ益ಠ)ノ彡┻━┻

“¤>%,oỊȤʠ“ØụĊ5D³ṃṠɼQ»j;Ç;“;}¶”

┬──┬ ノ( ゜-゜ノ)

Far out in the uncharted backwaters of the unfashionable end of the Western Spiral arm of the Galaxy lies a small unregarded yellow sun. Orbiting this at a distance of roughly ninety-eight million miles is an utterly insignificant little blue-green planet whose ape-descended life forms are so amazingly primitive that they still think digital watches are a pretty neat idea.
</code>```

Update

[16-08-10]: sets are unordered collections of distinct objects

[16-08-10]: trailing newline is acceptable

答:
MATL, 8 bytes

```<code>'X&'''X&
</code>```

Try it online!

Input is a string enclosed in single quotes. If the string contains a single-quote symbol, it should be duplicated to escape it.

Explanation

```<code>'X&'''   % Push string with the three characters used by the program. The single-quote
         % symbol needs to be escaped by duplicating it
X&       % Take input implicitly. Set intersection. Display implicitly
</code>```

Title: Input ∩ Source Code

Body:
MATL, 8 bytes

'X&'''X&

Try it online!

Input is a string enclosed in single quotes. If the string contains a single-quote symbol, it should be duplicated to escape it.

Explanation

'X&'''   % Push string with the three characters used by the program. The single-quote
         % symbol needs to be escaped by duplicating it
X&       % Take input implicitly. Set intersection. Display implicitly


答:
05AB1E, 11 bytes

Code:

```<code>"'ÃJÙ"'"JÃÙ
</code>```

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

Title: Input ∩ Source Code

Body:
Intro

The challenge is to create a program/function that prints the intersection of its own source code and a given string input. This is code golf and to be more precise:

Let I be the input set

{"a","b","c"}

Let S be the source code set

{"b","f"}

Then the intersection is what they share

I ∩ S = {"b"}

Input

Input is flexible. It should be able to handle the character encoding used for the source code.

Output

Output is flexible. It should be the set of characters that the input and source code share. Also, sets are unordered collections of distinct objects. In summary:

Output is flexible:

Could be any data structure (string or otherwise)

Could unordered

Could have a trailing \n

Should be distinct

Restriction

Similar to quine challenges, the program/function may not read its own source code and 0-byte solutions are not allowed.

Examples

#1

```<code>functor x(I){ return I ∩ self; }

Inputs                                Outputs
------                                -------
enter preformatted text here      ->  {"e","n","t","r","f","o","x"}

["Albrt"," Einstin"]              ->  {"l","r","t","n","s"}
</code>```

#2

```<code>(_)->_&"(_)->&\"\\"

Inputs                                Outputs
------                                -------
"Security at the expense of       ->  "
usability comes at the expense
of security."

(0____0)                          ->  (_)
</code>```

#3

```<code>ಠa益длф

Inputs                                Outputs
------                                -------
Far out in the uncharted backwaters ->"a"
of the unfashionable end of the
Western Spiral arm of the Galaxy lies
a small unregarded yellow sun.
Orbiting this at a distance of roughly
ninety-eight million miles is an
utterly insignificant little blue-green
planet whose ape-descended life forms
are so amazingly primitive that they
still think digital watches are a pretty
neat idea.

(ノಠ益ಠ)ノ彡┻━┻                      ->"ಠ益"
</code>```

Test Cases

```<code>Albert Einstein

\__( O__O)_/

!@#$%^&*()_+{}|:"<>?

1234567890-=[]\;',./

(ノಠ益ಠ)ノ彡┻━┻

“¤>%,oỊȤʠ“ØụĊ5D³ṃṠɼQ»j;Ç;“;}¶”

┬──┬ ノ( ゜-゜ノ)

Far out in the uncharted backwaters of the unfashionable end of the Western Spiral arm of the Galaxy lies a small unregarded yellow sun. Orbiting this at a distance of roughly ninety-eight million miles is an utterly insignificant little blue-green planet whose ape-descended life forms are so amazingly primitive that they still think digital watches are a pretty neat idea.
</code>```

Update

[16-08-10]: sets are unordered collections of distinct objects

[16-08-10]: trailing newline is acceptable

Body:
05AB1E, 11 bytes

Code:

"'ÃJÙ"'"JÃÙ

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


答:
Dyalog APL, 8 bytes

'∩''⊢'∩⊢
```

∩ is returns those characters from the left argument that are present in the right argument (if the left argument has no duplicates – as in this case – then the result also has no duplicates

⊢ is the argument

Then the string just has those two plus the quote character (doubled, as it is in a string).

TryAPL online!

Title: Input ∩ Source Code

Body:
Dyalog APL, 8 bytes

'∩''⊢'∩⊢

∩ is returns those characters from the left argument that are present in the right argument (if the left argument has no duplicates – as in this case – then the result also has no duplicates

⊢ is the argument

Then the string just has those two plus the quote character (doubled, as it is in a string).

TryAPL online!


答:
C (86 bytes):

for(int c=-11,n=-26;++n<1;){while(c++){printf("%c%c",90+n,n?91+n:65);}c=-11;puts("");}
```

My first attempt on a Code Golf challenge.

Some answers are really impressive!

Title: Print an alphabet wave

Body:
C (86 bytes):

for(int c=-11,n=-26;++n<1;){while(c++){printf("%c%c",90+n,n?91+n:65);}c=-11;puts("");}

My first attempt on a Code Golf challenge.

Some answers are really impressive!


答:
Pyth, <s>9</s> 8 bytes

1 byte thanks to Sp3000

```<code>@Q"\Q@\"
</code>```

Try it online!

```<code>@Q"\Q@\"
@Q"\Q@\""   implicit string ending

@Q           intersect the input with
  "\Q@\""   the string containing '\', 'Q', '@', '"'.
</code>```

Title: Input ∩ Source Code

Body:
Pyth, <s>9</s> 8 bytes

1 byte thanks to Sp3000

@Q"\Q@\"

Try it online!

@Q"\Q@\"
@Q"\Q@\""   implicit string ending

@Q           intersect the input with
  "\Q@\""   the string containing '\', 'Q', '@', '"'.


答:
Jelly, <s>10</s> 6 bytes

```<code>“Ṿf”Ṿf
</code>```

Try it online!

How it works

```<code>“Ṿf”Ṿf  Main link. Argument: s (string)

“Ṿf”    Set the return value to 'Ṿf'.
    Ṿ   Uneval; yield '“Ṿf”'.
     f  Filter; remove the characters from '“Ṿf”' that do not appear in s.
</code>```

Title: Input ∩ Source Code

Body:
Jelly, <s>10</s> 6 bytes

“Ṿf”Ṿf

Try it online!

How it works

“Ṿf”Ṿf  Main link. Argument: s (string)

“Ṿf”    Set the return value to 'Ṿf'.
    Ṿ   Uneval; yield '“Ṿf”'.
     f  Filter; remove the characters from '“Ṿf”' that do not appear in s.


答:
Node.js + request, 109 bytes

```<code>x=>n=>require('request')(`http://oeis.org/b${x.slice(1)}.txt`,(a,b)=>console.log(b.body.match(n+` (.+)`)[1]))
</code>```

Takes the sequence ID and a number.

Title: Automate the OEIS

Body:
Node.js + request, 109 bytes

x=>n=>require('request')(`http://oeis.org/b${x.slice(1)}.txt`,(a,b)=>console.log(b.body.match(n+` (.+)`)[1]))

Takes the sequence ID and a number.


答:
PHP, 65 bytes

Well, this is pretty straight forward:

```<code>for(;$i<26;)echo str_repeat(chr(65+$i).chr(65+(++$i%26)),13)."
";
</code>```

Title: Print an alphabet wave

Body:
PHP, 65 bytes

Well, this is pretty straight forward:

for(;$i<26;)echo str_repeat(chr(65+$i).chr(65+(++$i%26)),13)."
";


问:
Shortest code that raises a SIGSEGV
Write the shortest code that raises a  Segmentation Fault (SIGSEGV) in any programming language.</p>

答:
Cython, 14

This often comes in handy for debugging purposes.

```<code>a=(<int*>0)[0]
</code>```

Title: Shortest code that raises a SIGSEGV

Body:
Cython, 14

This often comes in handy for debugging purposes.

a=(<int*>0)[0]


答:
Python 3, 44 bytes

Thanks Karl for saving me one byte :-)
Thanks Dada for saving me two bytes!

I think this works, but it's my first quine challenge so I'm not 100% sure. :\

```<code>print(set("printseu()&'"+'+"')&set(input()))
</code>```

Lambda version with 43 bytes:
lambda a:set(" lambdaset()&'"+':+"')&set(a)

Title: Input ∩ Source Code

Body:
Python 3, 44 bytes

Thanks Karl for saving me one byte :-)
Thanks Dada for saving me two bytes!

I think this works, but it's my first quine challenge so I'm not 100% sure. :\

print(set("printseu()&'"+'+"')&set(input()))

Lambda version with 43 bytes:
lambda a:set(" lambdaset()&'"+':+"')&set(a)


答:
Perl 6, 56, 55 bytes

"French" / Unicode version (55 bytes)

say perl q.say perlq∩$*IN\\\.comb:..comb∩$*IN.comb:
```

<p><strong>"<em>Texas</em>" / ASCII versions</strong> (56 bytes)</p>

<pre class="lang-perl6 prettyprint-override"><code>say (q.sayq(&) $*IN\\\.combperl..comb (&)$*IN.comb).perl
</code>```

say perl q.sayq(&) $*IN\\\.comb:perl..comb (&)$*IN.comb:
```

<h1>Non-golfed:</h1>

<pre class="lang-perl6 prettyprint-override"><code>my \Source = 'my \\Source = \'say ( $*IN.comb.Set ∩ Source.comb.Set ).perl\'';
say ( $*IN.comb.Set ∩ Source.comb.Set ).perl
</code>```

Examples:

$ echo -n 'say perl q.say perlq∩$*IN\\\.comb:..comb∩$*IN.comb:' > test-unicode.p6

$ echo -n 'say (q.sayq(&) $*IN\\\.combperl..comb (&)$*IN.comb).perl' > test-ascii.p6

$ perl6 test-ascii.p6 <<< 'abcdefghijklmnopqrstuvwxyz'
set("p","a","l","r","c","q","b","s","e","m","y","o")

$ perl6 test-unicode.p6 < test-unicode.p6
set("\\","I","p"," ","a","c","l","r","q","b","∩","*","s","m","e",".","y",":","o","N","\$")

$ perl6 test-ascii.p6 < test-ascii.p6
set("p","\\","I"," ","a","l","r","c","q","b",")","*","s","e","m","\&",".","(","y","o","N","\$")

$ perl6 test-ascii.p6 < test-unicode.p6
set("p","\\","I"," ","a","l","r","c","q","b","*","s","e","m",".","y","o","N","\$")

$ perl6 test-unicode.p6 <<< 'Albert Einstein'
set(" ","l","r","b","s","e")

$ perl6 test-unicode.p6 <<< '\__( O__O)_/'
set("\\"," ")

$ perl6 test-ascii.p6 <<< '!@#$%^&*()_+{}|:"<>?'
set(")","*","\&","(","\$")

$ perl6 test-unicode.p6 <<< "1234567890-=[]\\;',./"
set("\\",".")

$ perl6 test-unicode.p6 <<< '(ノಠ益ಠ)ノ彡┻━┻'
set()

“¤>%,oỊȤʠ“ØụĊ5D³ṃṠɼQ»j;Ç;“;}¶”
set("o")

$ perl6 test-unicode.p6 <<< '┬──┬ ノ( ゜-゜ノ)'
set(" ")

$ perl6 test-ascii.p6 <<< 'Far out in the uncharted backwaters of the unfashionable end of the Western Spiral arm of the Galaxy lies a small unregarded yellow sun. Orbiting this at a distance of roughly ninety-eight million miles is an utterly insignificant little blue-green planet whose ape-descended life forms are so amazingly primitive that they still think digital watches are a pretty neat idea.'
set("p"," ","a","l","r","c","b","s","e","m",".","y","o")
```

Title: Input ∩ Source Code

Body:
Perl 6, 56, 55 bytes

"French" / Unicode version (55 bytes)

say perl q.say perlq∩$*IN\\\.comb:..comb∩$*IN.comb:

"Texas" / ASCII versions (56 bytes)

say (q.sayq(&) $*IN\\\.combperl..comb (&)$*IN.comb).perl

say perl q.sayq(&) $*IN\\\.comb:perl..comb (&)$*IN.comb:

Non-golfed:

my \Source = 'my \\Source = \'say ( $*IN.comb.Set ∩ Source.comb.Set ).perl\'';
say ( $*IN.comb.Set ∩ Source.comb.Set ).perl

Examples:

$ echo -n 'say perl q.say perlq∩$*IN\\\.comb:..comb∩$*IN.comb:' > test-unicode.p6

$ echo -n 'say (q.sayq(&) $*IN\\\.combperl..comb (&)$*IN.comb).perl' > test-ascii.p6

$ perl6 test-ascii.p6 <<< 'abcdefghijklmnopqrstuvwxyz'
set("p","a","l","r","c","q","b","s","e","m","y","o")

$ perl6 test-unicode.p6 < test-unicode.p6
set("\\","I","p"," ","a","c","l","r","q","b","∩","*","s","m","e",".","y",":","o","N","\$")

$ perl6 test-ascii.p6 < test-ascii.p6
set("p","\\","I"," ","a","l","r","c","q","b",")","*","s","e","m","\&",".","(","y","o","N","\$")

$ perl6 test-ascii.p6 < test-unicode.p6
set("p","\\","I"," ","a","l","r","c","q","b","*","s","e","m",".","y","o","N","\$")

$ perl6 test-unicode.p6 <<< 'Albert Einstein'
set(" ","l","r","b","s","e")

$ perl6 test-unicode.p6 <<< '\__( O__O)_/'
set("\\"," ")

$ perl6 test-ascii.p6 <<< '!@#$%^&*()_+{}|:"<>?'
set(")","*","\&","(","\$")

$ perl6 test-unicode.p6 <<< "1234567890-=[]\\;',./"
set("\\",".")

$ perl6 test-unicode.p6 <<< '(ノಠ益ಠ)ノ彡┻━┻'
set()

“¤>%,oỊȤʠ“ØụĊ5D³ṃṠɼQ»j;Ç;“;}¶”
set("o")

$ perl6 test-unicode.p6 <<< '┬──┬ ノ( ゜-゜ノ)'
set(" ")

$ perl6 test-ascii.p6 <<< 'Far out in the uncharted backwaters of the unfashionable end of the Western Spiral arm of the Galaxy lies a small unregarded yellow sun. Orbiting this at a distance of roughly ninety-eight million miles is an utterly insignificant little blue-green planet whose ape-descended life forms are so amazingly primitive that they still think digital watches are a pretty neat idea.'
set("p"," ","a","l","r","c","b","s","e","m",".","y","o")


答:
Logo, 93 bytes

Here's a non-graphical Logo solution.  Try it online with Calormen.com's interpreter.

```<code>to m:c type char 65+modulo:c 26end
to b:a repeat 13[m:a-1 m:a] pr" end
repeat 26[b repcount]
</code>```

Title: Print an alphabet wave

Body:
Logo, 93 bytes

Here's a non-graphical Logo solution.  Try it online with Calormen.com's interpreter.

to m:c type char 65+modulo:c 26end
to b:a repeat 13[m:a-1 m:a] pr" end
repeat 26[b repcount]


答:
Python 2, <s>56</s> <s>46</s> 39 Bytes

-1 Byte thanks to @Jeremy

```<code>lambda a:set(':&()smelt\ bad\'')&set(a)
</code>```

anonymous lambda function, takes a string, returns a set

old version:

```<code>lambda x,w=set('newmatrixbuspdl_:-)(=,\ \''):w-(w-set(x))
</code>```

Title: Input ∩ Source Code

Body:
Python 2, <s>56</s> <s>46</s> 39 Bytes

-1 Byte thanks to @Jeremy

lambda a:set(':&()smelt\ bad\'')&set(a)

anonymous lambda function, takes a string, returns a set

old version:

lambda x,w=set('newmatrixbuspdl_:-)(=,\ \''):w-(w-set(x))


答:
GolfScript, 6 bytes

```<code>"`&"`&
</code>```

Try it online!

How it works

```<code>        # (implicit) Push the input on the stack.
"`&"    # Push the string '`&' on the stack.
   `    # Inspect; turn the string into '"`&"'.
     &  # Perform set intersection.
</code>```

Title: Input ∩ Source Code

Body:
GolfScript, 6 bytes

"`&"`&

Try it online!

How it works

        # (implicit) Push the input on the stack.
"`&"    # Push the string '`&' on the stack.
   `    # Inspect; turn the string into '"`&"'.
     &  # Perform set intersection.


答:
Python, 48 bytes

First thing I though of. It can probably be golfed more.

Input comes from sdtin. Output goes to stdout as a set object

```<code>print set(raw_input())&set("raw_pint se(u)\&\"")
</code>```

Title: Input ∩ Source Code

Body:
Python, 48 bytes

First thing I though of. It can probably be golfed more.

Input comes from sdtin. Output goes to stdout as a set object

print set(raw_input())&set("raw_pint se(u)\&\"")


答:
PowerShell v4+, <s>122</s> 104 bytes

```<code>([char[]]($args[0]+'acegfhmnoprstu012|][()"?+_,.$-{0}{1}{2}'-f("'","}","{"))|group|?{$_.count-gt1}).name
</code>```

Ugh. Quines or quine-like code in PowerShell sucks, because the string replacement formatting is so clunky.

The string ace...{2} in the middle is every character that's present in the rest of the code. The {0}{1}{2} is used in conjunction with the -format operator to pull the '{} characters into the string.

That's combined as a char-array with the input $args, then fed into the pipeline. The first stop is Group-Object which (essentially) creates a hashtable of the input objects and how many times they occur in the input. That's piped to |?{...} the Where-Object to only select those items that have a .count greater than 1. We encapsulate that in parens, and pluck out the .Name portion of the hashtable (which is where the v4+ requirement comes into play, otherwise we'd need an additional |Select Name stage to the pipeline).

Those elements are left on the pipeline (as an array), and printing is implicit.

Title: Input ∩ Source Code

Body:
PowerShell v4+, <s>122</s> 104 bytes

([char[]]($args[0]+'acegfhmnoprstu012|][()"?+_,.$-{0}{1}{2}'-f("'","}","{"))|group|?{$_.count-gt1}).name

Ugh. Quines or quine-like code in PowerShell sucks, because the string replacement formatting is so clunky.

The string ace...{2} in the middle is every character that's present in the rest of the code. The {0}{1}{2} is used in conjunction with the -format operator to pull the '{} characters into the string.

That's combined as a char-array with the input $args, then fed into the pipeline. The first stop is Group-Object which (essentially) creates a hashtable of the input objects and how many times they occur in the input. That's piped to |?{...} the Where-Object to only select those items that have a .count greater than 1. We encapsulate that in parens, and pluck out the .Name portion of the hashtable (which is where the v4+ requirement comes into play, otherwise we'd need an additional |Select Name stage to the pipeline).

Those elements are left on the pipeline (as an array), and printing is implicit.


答:
Python, <s>83</s> 75 bytes

```<code>import re
def f(s):return re.search(r'^([-1-9dsty]|fo|n?on)',s.lower()).pos
</code>```

Returns 0 on success, AttributeError on failure.

Now using edc85's regex to save 8 bytes.

Title: Is it truthy or falsy?

Body:
There are so many different ways to express whether something is true or not! The goal of this challenge is to produce a standardized output of truthy or falsy for various input truthy and falsy values.

For the purposes of this challenge, the following inputs are considered truthy:

A string representing a signed integer with a non-zero value (contains only the digits [0-9], with an optional - at the beginning). Note that the string -0 will never be given as input. A non-zero integer will never be preceded by a 0 (i.e. 01 will never be given as input, similarly -01 will never be gien as input).

The case-insensitive strings equivalent to one of defined, found, nonnil, non-nil, on, success, t, true, y, and yes

For the purposes of this challenge, the following inputs are considered falsy:

The string 0. Repeated zeros (00, 00...) will never be given as input.

An empty string

The case-insensitive strings equivalent to one of f, failure, false, n, nan, nil, no, notfound, not-found, null, nullptr, off, and undefined

Input

The input is a string representing a truthy/falsy value. The string may come from any source desired (stdio, function parameter, etc.). There is no leading/trailing whitespace.

The input is guaranteed to match one of the allowed truthy/falsy values above (i.e. you do not need to provide any error handling).

Output

Your program/function must output a truthy/falsy value which represents the "truthy-ness" or "falsy-ness" of the input.
You are only allowed to specify exactly 1 truthy and 1 falsy value which your output must convert the input to (these are your "standardized" truthy/falsy value). The output may be written to any sink desired (stdio, return value, output parameter, etc.).

Please specify what truthy and falsy value you chose in your answer.

Ex.: If you choose the string true as a truthy value, you cannot also have the integer 1 for truthy.

Test Cases

Test cases are formatted as the first line is the input, and the second line is the output.

```<code>-1
true

1
true

1234
true

-4321
true

defined
true

deFined
true

Found
true

nonnil
true

non-nil
true

ON
true

SuCCess
true

T
true

true
true

y
true

YeS
true

0
false

'' (empty string)
false

faLSE
false

f
false

Failure
false

n
false

NaN
false

nil
false

no
false

notfound
false

not-Found
false

NULL
false

nullptr
false

OFF
false

unDefined
false
</code>```

Scoring

This is code-golf; shortest code in bytes wins. Standard loopholes apply. You may use any built-ins desired.

Body:
Python, <s>83</s> 75 bytes

import re
def f(s):return re.search(r'^([-1-9dsty]|fo|n?on)',s.lower()).pos

Returns 0 on success, AttributeError on failure.

Now using edc85's regex to save 8 bytes.


答:
C, 142 bytes

```<code>main(i){char*p,a[]="remain([*]){fought?>:01;,\\\"=capsv+-l}";for(;(i=getchar())>=0;p?putchar(i),memmove(p,p+1,a+strlen(a)-p):0)p=strchr(a,i);}
</code>```

Try it on ideone.

Title: Input ∩ Source Code

Body:
Intro

The challenge is to create a program/function that prints the intersection of its own source code and a given string input. This is code golf and to be more precise:

Let I be the input set

{"a","b","c"}

Let S be the source code set

{"b","f"}

Then the intersection is what they share

I ∩ S = {"b"}

Input

Input is flexible. It should be able to handle the character encoding used for the source code.

Output

Output is flexible. It should be the set of characters that the input and source code share. Also, sets are unordered collections of distinct objects. In summary:

Output is flexible:

Could be any data structure (string or otherwise)

Could unordered

Could have a trailing \n

Should be distinct

Restriction

Similar to quine challenges, the program/function may not read its own source code and 0-byte solutions are not allowed.

Examples

#1

```<code>functor x(I){ return I ∩ self; }

Inputs                                Outputs
------                                -------
enter preformatted text here      ->  {"e","n","t","r","f","o","x"}

["Albrt"," Einstin"]              ->  {"l","r","t","n","s"}
</code>```

#2

```<code>(_)->_&"(_)->&\"\\"

Inputs                                Outputs
------                                -------
"Security at the expense of       ->  "
usability comes at the expense
of security."

(0____0)                          ->  (_)
</code>```

#3

```<code>ಠa益длф

Inputs                                Outputs
------                                -------
Far out in the uncharted backwaters ->"a"
of the unfashionable end of the
Western Spiral arm of the Galaxy lies
a small unregarded yellow sun.
Orbiting this at a distance of roughly
ninety-eight million miles is an
utterly insignificant little blue-green
planet whose ape-descended life forms
are so amazingly primitive that they
still think digital watches are a pretty
neat idea.

(ノಠ益ಠ)ノ彡┻━┻                      ->"ಠ益"
</code>```

Test Cases

```<code>Albert Einstein

\__( O__O)_/

!@#$%^&*()_+{}|:"<>?

1234567890-=[]\;',./

(ノಠ益ಠ)ノ彡┻━┻

“¤>%,oỊȤʠ“ØụĊ5D³ṃṠɼQ»j;Ç;“;}¶”

┬──┬ ノ( ゜-゜ノ)

Far out in the uncharted backwaters of the unfashionable end of the Western Spiral arm of the Galaxy lies a small unregarded yellow sun. Orbiting this at a distance of roughly ninety-eight million miles is an utterly insignificant little blue-green planet whose ape-descended life forms are so amazingly primitive that they still think digital watches are a pretty neat idea.
</code>```

Update

[16-08-10]: sets are unordered collections of distinct objects

[16-08-10]: trailing newline is acceptable

Body:
C, 142 bytes

main(i){char*p,a[]="remain([*]){fought?>:01;,\\\"=capsv+-l}";for(;(i=getchar())>=0;p?putchar(i),memmove(p,p+1,a+strlen(a)-p):0)p=strchr(a,i);}

Try it on ideone.


答:
Perl 6 (7 chars)

```<code>say '☺'
</code>```

I'm bending the rules a little by assuming that a \n is welcome to avoid shell prompt mess.

Title: Smile! Just smile

Body:
It's well known that Brainf*ck is very bad at Kolmogorov-complexity problems, for example, it requires around 100 characters just to print "Hello world".

However, there might be texts where Brainf*ck is just very good at.

Your task is now to write a program that takes no input, and it displays the following:

```<code>☺
</code>```

That is, a smiley face (ASCII 1, if you browser does not render it).

Brainf*ck can do it in 2 characters.

```<code>+.
</code>```

Try to find a language that beats it!

We assume your console can actually display that character (or your font has it, etc.).

Shortest code wins. If there are more of the same length, the first wins, but I'll upvote the others as well.

EDIT: I'm very sorry, I did not think the first post arrives this soon. A quick edit: the language has to be Turing-complete!

Body:
Perl 6 (7 chars)

say '☺'

I'm bending the rules a little by assuming that a \n is welcome to avoid shell prompt mess.


问:
Tips for Golfing in Go
What general tips do you have for golfing in Go? I'm new to Code Golfing and looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to Go.

Please keep to one tip per answer.

答:
Declaring Multiple Variables:

```<code>i,s:=0,""

var(i int;s string)
</code>```

Int From String Conversion: (limited but sometimes helpful)

```<code>n:=byte("9"[0])-48 // actual type is uint8

n,_:=strconv.Atoi("9")
</code>```

And Vice Versa

```<code>s:=string(9+48)

s:=strconv.Itoa(9)
</code>```

Title: Tips for Golfing in Go

Body:
Declaring Multiple Variables:

i,s:=0,""

var(i int;s string)

Int From String Conversion: (limited but sometimes helpful)

n:=byte("9"[0])-48 // actual type is uint8

n,_:=strconv.Atoi("9")

And Vice Versa

s:=string(9+48)

s:=strconv.Itoa(9)


答:
Bash, <s>45 50 41 39 37 34</s> 29 bytes

-9 bytes thanks to Geoff Reedy

-4 bytes thanks to Dennis

-5 bytes thanks to Nahuel Fouilleul

grep -o '[] [|\'\'grepouniq-]
```

Try it online!

Title: Input ∩ Source Code

Body:
Bash, <s>45 50 41 39 37 34</s> 29 bytes

-9 bytes thanks to Geoff Reedy

-4 bytes thanks to Dennis

-5 bytes thanks to Nahuel Fouilleul

grep -o '[] [|\'\'grepouniq-]

Try it online!


问:
I've been alphabet hunting for a while
Y'know, we've had a lot of "alphabet" challenges recently. (one two three four five.) While I love a good challenge, and those challenges were very fun, I think it's time for a change of pace. We need to exclude such challenges in the future. It's time for automation!

You're going to find some alphabets for me, and for automation (and for glory!) Alphabets are tricky and like to disguise themselves.[citation-needed] You'll need to account for the following factors:

Alphabets can be uppercase or lowercase (but not both). So, you need to look for ABCDEFGHIJKLMNOPQRSTUVWXYZ and abcdefghijklmnopqrstuvwxyz, but not AbCdeFGhIJkLmNOpQRsTuvwxyZ. That is, only look for alphabets that are composed of entirely one case.

Alphabets can shift around. they may not always start with A, but instead may start with G or U. So you'll have to look for things like OPQRSTUVWXYZABCDEFGHIJKLMN.

Alphabets may not always read forwards. They can also read backwards, up, and down. E.g., ZYXWVUTSRQPONMLKJIHGFEDCBAis also a valid alphabet.

Here's an example of a string that has an alphabet:

```<code>JIHGFEDCBAZYXWVUTSRQPONMLK
</code>```

This is a backwards-oriented, shifted alphabet:

```<code>JIHGFEDCBAZYXWVUTSRQPONMLK
<--------|<---------------
</code>```

This also contains an alphabet:

```<code>F
G
H
I
J
K
L
M
N
O
P
Q
R
S
T
U
V
W
X
Y
Z
A
B
C
D
E
</code>```

it's a down-oriented alphabet:

```<code>F |
G |
H |
I |
J |
K |
L |
M |
N |
O |
P |
Q |
R |
S |
T |
U |
V |
W |
X |
Y |
Z V
A===
B |
C |
D |
E V
</code>```

Your challenge is to write a program, function, etc. that, given a string, outputs/returns a truthy value if the string contains at least one alphabet, or a falsey value otherwise. This is a code-golf, so the shortest program in bytes wins.

Test cases

Truthy

```<code>ABCDEFGHIJKLMNOPQRSTUVWXYZ

abcdefghijklmnopqrstuvwxyz

ABCDEFGHIJKLMNOPQRSTUVWXYabcdefghijklmnopqrstuvwxyz

ZABCDEFGHIJKLMNOPQRSTUVWXYghijklmnopqrstuvwxyzabcdef

ZBCDEFGHIJghijklmnopqrstuvwxyzabcdef

AAAAAAAA
BBBBBBBB
CCCCCCCC
DDDDDDDD
EEEEEEEE
FFFFFFFF
GGGGGGGG
HHHHHHHH
IIIIIIII
JJJJJJJJ
KKKKKKKK
LLLLLLLL
MMMMMMMM
NNNNNNNN
OOOOOOOO
PPPPPPPP
QQQQQQQQ
RRRRRRRR
SSSSSSSS
TTTTTTTT
UUUUUUUU
VVVVVVVV
WWWWWWWW
XXXXXXXX
YYYYYYYY
ZZZZZZZZ

 J54
 Igeh
 H
 G
 Fzx6
 E
 Dv
 Cvzxc
 Bs
 Adf
 Z
@Yascvf
 Xsf
 W
 Vfas
 Uw
 Te
~S
 R
 Qasdfasdf
 P
 O
 N
 M
 LMNOPQR
 K
</code>```

Falsey

```<code>Hello, World!

KLMNOPQRSTUVWXYZABCDEF

K        ZYXW
 L         V
  M       U
   N     T
    O   S
     P R
      Q

A
 BCDEFGHIJKLMNOPQRSTUVWXYZ

ABCDEFGHIJKLmnopqrstuvwxyz
</code>```

答:
05AB1E, 43 bytes

```<code>AÂ‚Duìvy26FÀD}})U|Dø€J)˜vXDgs`rFysk>ˆ}}¯O__
</code>```

Explanation in short

Get different variations of alphabet (caps, no-caps, reversed, normal) and store in X.

```<code>AÂ‚Duìvy26FÀD}})U
</code>```

Get each row and column of input as a list of strings.

```<code>                 |Dø€J)˜
</code>```

Check each such string if it contains a variation of the alphabet.

```<code>                        vXDgs`rFysk>ˆ}}
</code>```

Sum and double negate, giving 1 for true and 0 for false.

```<code>                                       ¯O__
</code>```

Try it online

Title: I've been alphabet hunting for a while

Body:
05AB1E, 43 bytes

AÂ‚Duìvy26FÀD}})U|Dø€J)˜vXDgs`rFysk>ˆ}}¯O__

Explanation in short

Get different variations of alphabet (caps, no-caps, reversed, normal) and store in X.

AÂ‚Duìvy26FÀD}})U

Get each row and column of input as a list of strings.

                 |Dø€J)˜

Check each such string if it contains a variation of the alphabet.

                        vXDgs`rFysk>ˆ}}

Sum and double negate, giving 1 for true and 0 for false.

                                       ¯O__

<a href="http://05ab1e.tryitonline.net/#code=QcOC4oCaRHXDrHZ5MjZGw4BEfX0pVXxEw7jigqxKKcucdlhEZ3NgckZ5c2s-y4Z9fcKvT19f&input=IEo1NCAgICAgIAogSWdlaCAgICAgCiBIICAgICAgICAKIEcgICAgICAgIAogRnp4NiAgICAgCiBFICAgICAgICAKIER2ICAgICAgIAogQ3Z6eGMgICAgCiBCcyAgICAgICAKIEFkZiAgICAgIAogWiAgICAgICAgCkBZYXNjdmYgICAKIFhzZiAgICAgIAogVyAgICAgICAgCiBWZmFzICAgICAKIFV3ICAgICAgIAogVGUgICAgICAgCn5TICAgICAgICAKIFIgICAgICAgIAogUWFzZGZhc2RmCiBQICAgICAgICAKIE8gICAgICAgIAogTiAgICAgICAgCiBNICAgICAgICAKIExNTk9QUVIgIAogSyAgICAgICAg" rel="nofollow noreferrer">Try it online


答:
q (38 bytes)

Reads from stdin

```<code>"readint0\\\" "inter read0 0
</code>```

edit: was missing backslash

Title: Input ∩ Source Code

Body:
q (38 bytes)

Reads from stdin

"readint0\\\" "inter read0 0

edit: was missing backslash


答:
R, 129 bytes

```<code>f=function(s){b=strsplit("f=unctio(s){arpl;,[1]b\\\"qemh0T}",c())[[1]];cat(b[unique(pmatch(strsplit(s,c())[[1]],b,0,T))],sep="")}
</code>```

If I ungolf it, it needs to have weird things changed like a newline in the string for b. Anyhow, its super simple -- builds a vector with all characters in the function in it. Then it pulls the input into a vector, and checks membership.

Title: Input ∩ Source Code

Body:
R, 129 bytes

f=function(s){b=strsplit("f=unctio(s){arpl;,[1]b\\\"qemh0T}",c())[[1]];cat(b[unique(pmatch(strsplit(s,c())[[1]],b,0,T))],sep="")}

If I ungolf it, it needs to have weird things changed like a newline in the string for b. Anyhow, its super simple -- builds a vector with all characters in the function in it. Then it pulls the input into a vector, and checks membership.


答:
CJam, 8 bytes

```<code>"`q&"`q&
</code>```

Try it here.

Explanation:

```<code>"`q&"    e# Push that string to the stack
     `   e# Stringify, pops the string and pushes "\"`r&\"" to the stack
      q  e# Pushes the input to the stack
       & e# Union, pops two elements and pushes a list of every element that is contained in both.
</code>```

Title: Input ∩ Source Code

Body:
CJam, 8 bytes

"`q&"`q&

Try it here.

Explanation:

"`q&"    e# Push that string to the stack
     `   e# Stringify, pops the string and pushes "\"`r&\"" to the stack
      q  e# Pushes the input to the stack
       & e# Union, pops two elements and pushes a list of every element that is contained in both.


答:
JavaScript, Z (90) bytes

```<code>for(i=65,b=66;i<91;++i,b=b<90?++b:65)console.log(Array(14).join(String.fromCharCode(i,b)))
</code>```

To learn:

```<code>var start = 65,
    end = 90;

for (var i = start, b = i+1; i <= end; ++i) {
    var chars = String.fromCharCode(i, b);
    /* repeat chars 14 times */
    console.log(Array(14).join(chars));
}
</code>```

Title: Print an alphabet wave

Body:
You are to print this exact text:

```<code>ABABABABABABABABABABABABAB
BCBCBCBCBCBCBCBCBCBCBCBCBC
CDCDCDCDCDCDCDCDCDCDCDCDCD
DEDEDEDEDEDEDEDEDEDEDEDEDE
EFEFEFEFEFEFEFEFEFEFEFEFEF
FGFGFGFGFGFGFGFGFGFGFGFGFG
GHGHGHGHGHGHGHGHGHGHGHGHGH
HIHIHIHIHIHIHIHIHIHIHIHIHI
IJIJIJIJIJIJIJIJIJIJIJIJIJ
JKJKJKJKJKJKJKJKJKJKJKJKJK
KLKLKLKLKLKLKLKLKLKLKLKLKL
LMLMLMLMLMLMLMLMLMLMLMLMLM
MNMNMNMNMNMNMNMNMNMNMNMNMN
NONONONONONONONONONONONONO
OPOPOPOPOPOPOPOPOPOPOPOPOP
PQPQPQPQPQPQPQPQPQPQPQPQPQ
QRQRQRQRQRQRQRQRQRQRQRQRQR
RSRSRSRSRSRSRSRSRSRSRSRSRS
STSTSTSTSTSTSTSTSTSTSTSTST
TUTUTUTUTUTUTUTUTUTUTUTUTU
UVUVUVUVUVUVUVUVUVUVUVUVUV
VWVWVWVWVWVWVWVWVWVWVWVWVW
WXWXWXWXWXWXWXWXWXWXWXWXWX
XYXYXYXYXYXYXYXYXYXYXYXYXY
YZYZYZYZYZYZYZYZYZYZYZYZYZ
ZAZAZAZAZAZAZAZAZAZAZAZAZA
</code>```

Specs

You can print all lowercase instead of all uppercase. However, case must be consistent throughout the output.

You may print one extra trailing linefeed.

Scoring

Since this is an alphabet wave that fluctuates to a small extent, your code should also be small in terms of byte-count. In fact, the smallest code in terms of byte-count wins.

Body:
JavaScript, Z (90) bytes

for(i=65,b=66;i<91;++i,b=b<90?++b:65)console.log(Array(14).join(String.fromCharCode(i,b)))

To learn:

var start = 65,
    end = 90;

for (var i = start, b = i+1; i <= end; ++i) {
    var chars = String.fromCharCode(i, b);
    /* repeat chars 14 times */
    console.log(Array(14).join(chars));
}


答:
JavaScript (ES6), <s>59</s> 57 bytes

f=
t=>[..."\"().=>O[\\]defilnrtx~"].filter(e=>~t.indexOf(e))
;```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input placeholder=Input oninput=o.value=f(this.value).join``><input placeholder=Output id=o></code>```

Returns an array of characters present in both the original string/character array and the source code. Edit: Saved 2 bytes thanks to @user81655.

Title: Input ∩ Source Code

Body:
JavaScript (ES6), <s>59</s> 57 bytes

f=
t=>[..."\"().=>O[\\]defilnrtx~"].filter(e=>~t.indexOf(e))
;

<input placeholder=Input oninput=o.value=f(this.value).join``><input placeholder=Output id=o>

Returns an array of characters present in both the original string/character array and the source code. Edit: Saved 2 bytes thanks to @user81655.


答:
Ruby, 34 + n flag = 35 bytes

Doesn't exactly work with multi-lined input, since -n causes the program to process STDIN line-by-line. There aren't newlines in this code, but trying to input something like that will output multiple arrays instead of one. If that is not good according to spec, please inform me and I will fix.

```<code>p $_.chars&"\\\"p $_.chars&".chars
</code>```

Title: Input ∩ Source Code

Body:
Ruby, 34 + n flag = 35 bytes

Doesn't exactly work with multi-lined input, since -n causes the program to process STDIN line-by-line. There aren't newlines in this code, but trying to input something like that will output multiple arrays instead of one. If that is not good according to spec, please inform me and I will fix.

p $_.chars&"\\\"p $_.chars&".chars


答:
Golfscript, 3 characters

```<code>"☺"
</code>```

Not a golfscript expert, but I don't believe there is a way to convert an integer into the corresponding ASCII character using only 1 character, so it seems like this is the shortest it can get

Title: Smile! Just smile

Body:
Golfscript, 3 characters

"☺"

Not a golfscript expert, but I don't believe there is a way to convert an integer into the corresponding ASCII character using only 1 character, so it seems like this is the shortest it can get


问:
King of the Torus!

King of the Torus!

Your job is to conquer the torus, but wait, there are multiple other players banded together in teams facing you! You will need to use your wit's to conquer the torus.

There are three teams: red, blue and green. Teams are self-assigned arbitrarily. If the teams are even you may join the team of your choice, otherwise you must join the smallest team(s). The map is a torus presented as a square of length 640  by 640.  Lets take a look at a sample map

```<code>OOOOOOOOOOOOOOOOOOOOOOOOOOO
RRRRRRRRRRRRRRRRRRRRRRRRRRR
OOOOOOOOOOOOOOOOOOOOOOOOOOO
GGGGGOOOOOOOOBBBBBBBBBBBBBB
GGGGGGGGGGGGGGGGGGGGGOOOOOG
OOOOOOOOOOOOOOOOOOOOOOOOOGG
RRRRRRRRRRRRRRRRRRRRRRRRRRR
OOOOOOOOOOOOOOOOOOOOOOOOOOO
</code>```

as you can see, the red team has built a wall to safely conquer the territory between the two walls. Blue, and green will have to fight it out. This scaled down version of the map is representative of the larger one.

Red would likely win this battle as they would finish the game (once the board is filled or a large number of turns have passed) with the most territory

Now each bot has a location (known only to you). You can only move to an adjacent square if it is owned by your team. At the start of your game, you start on a single square of your teams color. Your goal is to expand this splotch by conquering other land. At any turn you can choose to move to any adjacent color of your own territory or you may alternatively choose to attack an adjacent territory. If the attacked square is unowned it will be captured.

Java API

You will override the Bot class to return a single number (0-3) for attempted moves and 4-7 for an attempted attack. Your bot's should only take 10 milliseconds to move, but the rule will not be formally enforced unless it becomes a problem. Problematic, malicous, or otherwise obnoxious bots are clearly not in the spirit of this competition and will be disqualified with an immediate low quality flag.
Otherwise bots acting in good faith, but otherwise buggy will be given time as needed for bug repairs.
Method summary

```<code>public abstract class Bot{
public final int team;// 0 = red 1 = green 2 = blue
public Bot(int inTeam){team=inTeam}//be sure to call super(inTeam);
public int move(){};//you will override this
}

Methods available

Color Bot.getColor(int x,int y){}//returns a Color object with rgb values where the r g or b value of the team owning it will be 100.
getX(); returns the X position of your bot
getY(); returns the y position of your bot
Bot.getMap();//returns the array representing the map. I.e Bot.getMap[i][j] returns a color with r g b values representing each teams stake in that spot.
//only one r g b value will be greater than 0 as only one team can hold a spot
Do not abuse the map access. Giving direct access (as opposed to a copy) is to speed up access to the map. Abusing it will result in disqualification!
</code>```

A wrapper program may be made available as long as it still allows the program to run smoothly.

How to play:

Step one: Post your bot here as an answer and ensure it follows the specs.

Step Two Head over to this gitHub repository fork it and add your bot's file in as well as add these two lines after '//init bots' Bot.run. Be sure to choose the team with the least members if applicable.

```<code>  bots.add(new UniqueBotNameHere(team=choiceOfTeam,x=getRandom(0,map.length),y=getRandom(0,map[0].length)));
    map[x][y].colors[team]=255;
</code>```

Step Three: Make a pull request. I will accept your pull request and your bot will automagically be added to the tournament.

Step Four: Download the source files and copy them into the proper package. Run the build and enjoy watching the bots

Good luck and don't let your team down! Team's will be made even by my sample bots. I may also move around teams to ensure equal members.

Interesting trivia

Modifying the Half Hearted flood filling sample bot, gives an interesting map generator.

答:
SpiralBot

This bot will go until he hits something that is not neutral, then will turn left, making a spiral in the free space.

```<code>public class SpiralBot extends Bot{
    int d;

        public SpiralBot (int team, int inX, int inY) {
            super(team, inX, inY);
        d = 0;
        }

    int dx(int move){
        return (int) Math.cos(move * Math.PI / 2);
    }
    int dy(int move){
        return (int) Math.sin(move * Math.PI / 2);
    }

        @Override
        public int move() {
        int x = getX();
        int y = getY();
        Color[]c = new Color[4];
        for(int i = 0;i<4;i++)
            c[i] = Bot.getColor(x+dx(i), y+dy(i));
        if(c[d].equals(Color.black))
            return d;
        if(c[(d+1)%4].equals(Color.black))
            return d = (d+1)%4;
        if(c[(d+3)%4].equals(Color.black))
            return d = (d+3)%4;
        return d + 2;
    }

}
</code>```

I have no account on GitHub, so if someone could push this for me that would be good. Thank you.

Title: King of the Torus!

Body:
SpiralBot

This bot will go until he hits something that is not neutral, then will turn left, making a spiral in the free space.

public class SpiralBot extends Bot{
    int d;

        public SpiralBot (int team, int inX, int inY) {
            super(team, inX, inY);
        d = 0;
        }

    int dx(int move){
        return (int) Math.cos(move * Math.PI / 2);
    }
    int dy(int move){
        return (int) Math.sin(move * Math.PI / 2);
    }

        @Override
        public int move() {
        int x = getX();
        int y = getY();
        Color[]c = new Color[4];
        for(int i = 0;i<4;i++)
            c[i] = Bot.getColor(x+dx(i), y+dy(i));
        if(c[d].equals(Color.black))
            return d;
        if(c[(d+1)%4].equals(Color.black))
            return d = (d+1)%4;
        if(c[(d+3)%4].equals(Color.black))
            return d = (d+3)%4;
        return d + 2;
    }

}

I have no account on GitHub, so if someone could push this for me that would be good. Thank you.


答:
VIM, 42

```<code>:h<_↵↵↵YZZP:s/./&\r/g↵^25↑y↑pG2↑aa↓^ggy13P
</code>```

where:

↵ is return,

^ is ctrl + v

↑ is the up arrow

↓ is escape

I'm sure this can be golfed more. I'm new to VIM so any suggestions are appreciated.

Title: Print an alphabet wave

Body:
VIM, 42

:h<_↵↵↵YZZP:s/./&\r/g↵^25↑y↑pG2↑aa↓^ggy13P

where:

↵ is return,

^ is ctrl + v

↑ is the up arrow

↓ is escape

I'm sure this can be golfed more. I'm new to VIM so any suggestions are appreciated.


答:
Nim, <s>123</s> <s>115</s> 113 bytes

import httpclient,nre,future
(a,n)=>get getContent("http://oeis.org/b"&a[1..^0]&".txt").find re "(?<="&n&r" )\d+"
```

<p>This is a lambda expression; to use it, it must be passed as an argument to a testing procedure. A complete program that can be used for testing is given here:</p>

<pre class="lang-nim prettyprint-override"><code>import httpclient,nre,future
proc test(x: (string, string) -> RegexMatch) = echo x("A172141", "7") # Your input here
test((a,n)=>get getContent("http://oeis.org/b"&a[1..^0]&".txt").find re "(?<="&n&r" )\d+")
</code>```

Expects input as two strings. Example usage:

$ nim c oeis.nim
$ ./oeis
980
```

We use httpclient's getContent proc to get the OEIS b-file, then use a regex to find the line with the index. find returns an Option[RegexMatch], so we use get to retrieve the value from the Option. echo automatically stringifies, so we leave stringification out.

Title: Automate the OEIS

Body:
We see a lot of challenges here asking for a function to create a sequence from the OEIS.  While these challenges are fun, as a programmer I see an opportunity for automation.

Your challenge is to make a program that takes the index of a sequence (e.g. A172141) and some integer n (e.g. 7), and pulls the appropriate value from the appropriate webpage.

I/O

As mentioned, your program should take a sequence index and some value n as input and output the nth term in that sequence. You accept any index in the sequence's B-files. If the index is greater than the largest index listed in the B-files you may throw an exception or output whatever you choose (these are not in the test cases).  Standard methods of input and output are permitted.

Restrictions on web use

You should not access any websites other than https://oeis.org and http://oeis.org.  This includes url shorteners, your own personal website, and this question itself.  If you would like to access some other website and you believe that it is not unfair to allow you to do so, you can leave a comment and I will arbitrate.

Scoring

This is a code golf challenge so the program with the least bytes used in its source code wins.  Standard loopholes are disallowed.

Test Cases

Assuming that your machine has proper internet connection and the OEIS servers are up and running the following inputs and outputs should correspond.

```<code>A172141, 7   -> 980
A173429, 4   -> 276
A190394, 6   -> 16
A002911, 11  -> 960
A052170, 3   -> 24
A060296, 8   -> 3
A178732, 5   -> 27
A000001, 1   -> 1
A000796, 314 -> 3
A001622, 162 -> 8
A002206, -1  -> 1
</code>```

Tip

When accessing the B-files http://oeis.org/b.txt will redirect to the proper B-file.

Body:
Nim, <s>123</s> <s>115</s> 113 bytes

import httpclient,nre,future
(a,n)=>get getContent("http://oeis.org/b"&a[1..^0]&".txt").find re "(?<="&n&r" )\d+"

This is a lambda expression; to use it, it must be passed as an argument to a testing procedure. A complete program that can be used for testing is given here:

import httpclient,nre,future
proc test(x: (string, string) -> RegexMatch) = echo x("A172141", "7") # Your input here
test((a,n)=>get getContent("http://oeis.org/b"&a[1..^0]&".txt").find re "(?<="&n&r" )\d+")

Expects input as two strings. Example usage:

$ nim c oeis.nim
$ ./oeis
980

We use httpclient's getContent proc to get the OEIS b-file, then use a regex to find the line with the index. find returns an Option[RegexMatch], so we use get to retrieve the value from the Option. echo automatically stringifies, so we leave stringification out.