答:
PHP, 41 bytes, cracked

Yeah, finally another Cops and Robbers challenge. Hope I didn't make it to easy.

Output

```<code>a(5)   = 0
a(15)  = 1
a(35)  = 0
a(36)  = 1
a(45)  = 1
</code>```

Source

```<code>____________________$argv[1]____________;
####################        ############
</code>```

Notes

It's a full program, not a function.

Reads the input from command line (obviously).

Does not contain any PHP opening tag.

Cracked

I obviously made it to easy and provided not enough examples. The sequence I had in mind was A010054:

a(n) = 1 if n is a triangular number else 0.

Here's my original source code:

 echo(int)($r=sqrt(8*$argv[1]+1))==$r?1:0;

It tests whether the input is a triangular number and outputs 1 or 0 accordingly.

Body:
PHP, 41 bytes, cracked

Yeah, finally another Cops and Robbers challenge. Hope I didn't make it to easy.

Output

a(5)   = 0
a(15)  = 1
a(35)  = 0
a(36)  = 1
a(45)  = 1

Source

____________________$argv[1]____________;
####################        ############

Notes

It's a full program, not a function.

Reads the input from command line (obviously).

Does not contain any PHP opening tag.

Cracked

I obviously made it to easy and provided not enough examples. The sequence I had in mind was A010054:

a(n) = 1 if n is a triangular number else 0.

Here's my original source code:

 echo(int)($r=sqrt(8*$argv[1]+1))==$r?1:0;

It tests whether the input is a triangular number and outputs 1 or 0 accordingly.


问:
Find the program that prints this integer sequence (Cops' thread)
This is the cops' thread. The robbers' thread goes here.

The last cops-and-robbers thread was already 4 months ago.

The cop's task

The cop's task is to write a program/function that takes a positive (or non-negative) integer and outputs/returns another integer.

The cop must state it if the program is intolerant towards zero.

The cop will provide at least 2 sample inputs/outputs.

For example, if I have decided to write the Fibonacci sequence, I would write this in my answer:

```
a(0) returns 0
a(3) returns 2
```

The number of examples is up to the cop's discretion.

However, the sequence must actually exist in the On-Line Encyclopedia of Integer Sequences®, so no pseudo-random number generator for you. :(

The cop can hide as many characters as is so wished.

For example, if my program is:

```<code>function a(n)
    if n>2 then
        return n
    else
        return a(n-1) + a(n-2)
    end
end
</code>```

Then I would hide these characters as I want:

```<code>function a(n)
    if ### then
        ########
    else
        ######################
    end
end
</code>```

The robber's task

is obviously to find the original source code.

However, any proposed source code that produces the same set of output also counts as valid, as long as it is also found in OEIS.

Tips for the cops

<s>The search function in the OEIS only works for consecutive terms, so if you want to hide your sequence, then just leave a hole anywhere.</s>

Apparently there is no way to hide the sequence. Put this in mind when you choose the sequence.

Your score is the number of bytes in your code.

The winner will be the submission with the lowest score that hasn't been cracked in 7 days.

Only submissions that are posted in 2016 April are eligible for the win. Submissions that are posted later than this are welcome, but cannot win.

In order to claim the win you need to reveal the full code and the OEIS sequence (after 7 days).

Your post should be formatted like this (NN is the number of characters):

Lua, 98 bytes

Output:

```<code>a(0) returns 0
a(3) returns 2
</code>```

Code (# marks unrevealed characters):

```<code>function a(n)
    if ### then
        ########
    else
        ######################
    end
end
</code>```

If the code is cracked, insert [Cracked](link to cracker) in the header.
If the submission is safe, insert "Safe" in the header and reveal the full code in your answer. Only answers that have revealed the full code will be eligible for the win.

答:
Pyke, 15 bytes, SAFE

Output

```<code>a(2) = 21
a(15) = 17
</code>```

Revealed code:

```<code>#R#D######+##)#
</code>```

Solution:

 OEIS A038822

wR}DSR_Q*L+#P)l

 I used a couple of red herrings here by using wR} to generate the number 100 and revealing the character R which is normally used to rotate the stack. I also used #P)l instead of the more simple mPs to count the number of primes in the sequence.

ContentLicense: CC BY-SA 3.0

Body:
Pyke, 15 bytes, SAFE

Output

a(2) = 21
a(15) = 17

Revealed code:

#R#D######+##)#

Solution:

 OEIS A038822

wR}DSR_Q*L+#P)l

 I used a couple of red herrings here by using wR} to generate the number 100 and revealing the character R which is normally used to rotate the stack. I also used #P)l instead of the more simple mPs to count the number of primes in the sequence.


问:
Switching Gravity

Challenge

You are given an ASCII-art representation of characters on a plane as input by any reasonable method. This will only contain:

[a-z] representing moveable characters. Every letter will appear on the board at most once.

# representing immovable walls

. representing empty space

For example:

```<code>abcdef.gh#..
.......ij.#.
#..#.......#
...#.#...###
.#.......#q#
.........###
</code>```

You are also given a string representing the changes in gravity. This will only contain:

> representing a change to rightward gravity

< representing a change to leftward gravity

^ representing a change to upward gravity

v representing a change to downward gravity

For example:

```<code>v>^
</code>```

Your program must simulate the each change in gravity sequentially until all characters stop moving (they hit a wall, or another character). Characters that "fall off the edge of the map" are permanently removed, and characters can "stack" on top of each other.

In this example, at the start there is downward gravity (v), so c, e, g, h, i, and j fall off the bottom of the map. All other characters slide downwards until hitting a wall, leaving the map like this:

```<code>.........#..
a..d......#.
#..#.f.....#
.b.#.#...###
.#.......#q#
.........###
</code>```

Then, we move on to rightward gravity (>), which leaves us with this:
Note how the a stacks next to the d.

```<code>.........#..
........ad#.
#..#......f#
..b#.#...###
.#.......#q#
.........###
</code>```

Finally, we simulate upward gravity (^), during which the a and the b fall off the map.

```<code>.........#..
.........d#.
#..#......f#
...#.#...###
.#.......#q#
.........###
</code>```

Your task is to output the remaining characters after the gravitational shifts. They can be given in any order. For this example, you could output any permutation of dfq.

Testcases

For the following map:

```<code>abcde
.....
##.##
</code>```

```<code>v   =  abde
v>  =  <nothing>
</code>```

For the following map:

```<code>######
#....#
abcdef
#.gh..
######
</code>```

```<code>>   = <nothing>
<   = gh
^>  = bcde
v<  = bghef
</code>```

答:
JavaScript (ES6), <s>251</s> 233 bytes

```<code>(m,d,r=`replace`)=>[...d].map(c=>[...`<^>v`].map(d=>m=[...(m=(c==d?m[r](/[.\w]+/g,s=>s[r](/\./g,``)+s[r](/\w/g,``))[r](/^\w+/gm,s=>s[r](/./g,`.`)):m).split`
`)[0]].map((_,i)=>m.map(s=>s[i]).join``).reverse().join`
`))&&m[r](/\W/g,``)
</code>```

Edit: Saved 18 bytes thanks to @WashingtonGuedes.

Works by rotating the input grid four times for each directional character, but on the direction where the directional character matches the loop character we do the left gravity thing. Pseudocode:

```<code>function slideleft(map) {
    map = map.replace(/[.\w+]/g, match=>movedotstoend(match));
    map = map.replace(/^\w+/gm, match=>changetodots(match));
}
function rotate(map) {
    return joinrows(reverse([for each (column of rows(map)[0])
            joinrow([for each (row of rows(map)) row[column]])
           ]));
}
function gravity(map, directions) {
    for each (direction of directions) {
        for each (angle of '<^>v') {
            if (direction == angle) map = slideleft(map);
            map = rotate(map);
        }
    }
    return letters(map);
}
</code>```

Title: Switching Gravity

Body:
JavaScript (ES6), <s>251</s> 233 bytes

(m,d,r=`replace`)=>[...d].map(c=>[...`<^>v`].map(d=>m=[...(m=(c==d?m[r](/[.\w]+/g,s=>s[r](/\./g,``)+s[r](/\w/g,``))[r](/^\w+/gm,s=>s[r](/./g,`.`)):m).split`
`)[0]].map((_,i)=>m.map(s=>s[i]).join``).reverse().join`
`))&&m[r](/\W/g,``)

Edit: Saved 18 bytes thanks to @WashingtonGuedes.

Works by rotating the input grid four times for each directional character, but on the direction where the directional character matches the loop character we do the left gravity thing. Pseudocode:

function slideleft(map) {
    map = map.replace(/[.\w+]/g, match=>movedotstoend(match));
    map = map.replace(/^\w+/gm, match=>changetodots(match));
}
function rotate(map) {
    return joinrows(reverse([for each (column of rows(map)[0])
            joinrow([for each (row of rows(map)) row[column]])
           ]));
}
function gravity(map, directions) {
    for each (direction of directions) {
        for each (angle of '<^>v') {
            if (direction == angle) map = slideleft(map);
            map = rotate(map);
        }
    }
    return letters(map);
}


Title: Find the program that prints this integer sequence (Cops' thread)

Body:
This is the cops' thread. The robbers' thread goes here.

The last cops-and-robbers thread was already 4 months ago.

The cop's task

The cop's task is to write a program/function that takes a positive (or non-negative) integer and outputs/returns another integer.

The cop must state it if the program is intolerant towards zero.

The cop will provide at least 2 sample inputs/outputs.

For example, if I have decided to write the Fibonacci sequence, I would write this in my answer:

```
a(0) returns 0
a(3) returns 2
```

The number of examples is up to the cop's discretion.

However, the sequence must actually exist in the On-Line Encyclopedia of Integer Sequences®, so no pseudo-random number generator for you. :(

The cop can hide as many characters as is so wished.

For example, if my program is:

```<code>function a(n)
    if n>2 then
        return n
    else
        return a(n-1) + a(n-2)
    end
end
</code>```

Then I would hide these characters as I want:

```<code>function a(n)
    if ### then
        ########
    else
        ######################
    end
end
</code>```

The robber's task

is obviously to find the original source code.

However, any proposed source code that produces the same set of output also counts as valid, as long as it is also found in OEIS.

Tips for the cops

<s>The search function in the OEIS only works for consecutive terms, so if you want to hide your sequence, then just leave a hole anywhere.</s>

Apparently there is no way to hide the sequence. Put this in mind when you choose the sequence.

Your score is the number of bytes in your code.

The winner will be the submission with the lowest score that hasn't been cracked in 7 days.

Only submissions that are posted in 2016 April are eligible for the win. Submissions that are posted later than this are welcome, but cannot win.

In order to claim the win you need to reveal the full code and the OEIS sequence (after 7 days).

Your post should be formatted like this (NN is the number of characters):

Lua, 98 bytes

Output:

```<code>a(0) returns 0
a(3) returns 2
</code>```

Code (# marks unrevealed characters):

```<code>function a(n)
    if ### then
        ########
    else
        ######################
    end
end
</code>```

If the code is cracked, insert [Cracked](link to cracker) in the header.
If the submission is safe, insert "Safe" in the header and reveal the full code in your answer. Only answers that have revealed the full code will be eligible for the win.

Body:
Python 2, 87 bytes, cracked

n=input()
#####################################################################
print _

Output:

a(5) = 2
a(10) = 2
a(15) = 1
a(20) = 1
a(25) = 1

I really should have checked for other sequences before I posted, here's another  one that works (A014709):

n=input()
g=lambda n:~n%2*(n/2%2+1)or g(n/2);_=g(n)############################
print _


答:
Pyth, 18 bytes

# marks unrevealed characters.

```<code>L?Jtb##5#m##S#2 #y
</code>```

Outputs (starts from 1):

```<code>1 -> 2
2 -> 3
3 -> 5
4 -> 7
</code>```

Online interpreter

Body:
Pyth, 18 bytes

# marks unrevealed characters.

L?Jtb##5#m##S#2 #y

Outputs (starts from 1):

1 -> 2
2 -> 3
3 -> 5
4 -> 7

Online interpreter


问:
Find the program that prints this integer sequence (Robbers' thread)
This is the robbers' thread. The cops' thread goes here.

In the cops thread, the task was to write a program/function that takes a positive (or non-negative) integer and outputs/returns another number (not necessarily integer). The robbers task is to unscramble the code the cops used to produce this output.

The cracked code doesn't have to be identical, as long as it has the same length and any revealed characters are in the correct positions. The language must also be the same (version numbers can be different). The output must of course be identical.

No-ops can be used in robber's solution.

The winner of the robbers thread will be the user who has cracked the
most submissions by May 7th 2016. If there's a tie, the user who has cracked submissions with the longest combined code will win.

The submission should be formatted like this:

Language, nn characters (including link to answer), Cop's username

Code:

```<code>function a(n)
    if n<2 then
        return n
    else
        return a(n-1) + a(n-2)
    end
end
</code>```

Output

```<code>a(0) returns 0
a(3) returns 2
</code>```

Optional explanation and comments.

答:
Python 2, 87 bytes, Sp3000, A083054

n=input()
_=int(3**.5*n)-3*int(n/3**.5)########################################
print _
```

Not that hard, actually. Just searched for sequences that met the constraints until I found one that could be generated in the given space.

Body:
Python 2, 87 bytes, Sp3000, A083054

n=input()
_=int(3**.5*n)-3*int(n/3**.5)########################################
print _

Not that hard, actually. Just searched for sequences that met the constraints until I found one that could be generated in the given space.


答:
MATL, 5 bytes, cracked

Hidden characters are indicated by %.

```<code>%5%*%
</code>```

Output:

```<code>a(1) = 3
a(2) = 6
a(4) = 12
</code>```

Input 0 is valid.

Original code:

```<code>35B*s
</code>```

that is,

```<code>35    % push number 35
B     % convert to binary: array [1 0 0 0 1 1]
*     % multiply element-wise by implicit input n: gives [n 0 0 0 n n]
s     % sum of array: gives 3*n
</code>```

Body:
MATL, 5 bytes, cracked

Hidden characters are indicated by %.

%5%*%

Output:

a(1) = 3
a(2) = 6
a(4) = 12

Input 0 is valid.

Original code:

35B*s

that is,

35    % push number 35
B     % convert to binary: array [1 0 0 0 1 1]
*     % multiply element-wise by implicit input n: gives [n 0 0 0 n n]
s     % sum of array: gives 3*n


问:
"Stair-ify" a string
You must write a program or function that creates a "stair-ified" string. Here is how you "stair-ify" a string:

For each character in the string:

If the character is an upper or lowercase vowel, not including 'y', output it then move the rest of the string up a column.

If the character is a space or a tab, output it then move the rest of the string down a colum.

If the character is neither, output it normally.

IO can be in any reasonable format. The input will not contain any newlines. If you want, you can remove any trailing whitespace.

If you choose to return the string, rather than printing it, please also include a short program that will print your string so that it can be visualized. This is not mandatory, nor will it go towards your byte-count. This is just a convenience for users who don't understand golf or esolangs (like me) to be able to verify output or tinker with the code.

Sample IO:

Output for "bcdef ghijkl":

```<code>    f    jkl
bcde  ghi
</code>```

Output for "Programming Puzzles And Code-Golf":

```<code>                               lf
                            -Go
                  s  nd   de
         ng   zzle  A   Co
      mmi   Pu
   gra
Pro
</code>```

Output for "Abcdefghijklmnopqrstuvwxyz":

```<code>                     vwxyz
               pqrstu
         jklmno
     fghi
 bcde
A
</code>```

As usual, this is code-golf, so shortest answer in bytes wins.

答:
C, 180 bytes

```<code>char s[99];i,j,p[99],m,M;main(c){for(gets(s);c=s[i];j+=strchr("aeiou",c|32)!=0,j-=c<33,m>j?m=j:M<j?M=j:0)p[i++]=j;for(;m<=M;putchar(10),M--)for(i=0;c=s[i];)putchar(M^p[i++]?32:c);}
</code>```

Ungolfed:

```<code>char s[99];i,j,p[99],m,M;
main(c){for(gets(s);c=s[i];
j+=strchr("aeiou",c|32)!=0,j-=c<33,m>j?m=j:M<j?M=j:0)
  //move current height up or down, adjust minimum and maximum height
p[i++]=j;  //record height of character
for(;m<=M;putchar(10),M--)  //from maximum to minimum height
for(i=0;c=s[i];)putchar(M^p[i++]?32:c);}  //print only characters on this height
</code>```

Title: "Stair-ify" a string

Body:
C, 180 bytes

char s[99];i,j,p[99],m,M;main(c){for(gets(s);c=s[i];j+=strchr("aeiou",c|32)!=0,j-=c<33,m>j?m=j:M<j?M=j:0)p[i++]=j;for(;m<=M;putchar(10),M--)for(i=0;c=s[i];)putchar(M^p[i++]?32:c);}

Ungolfed:

char s[99];i,j,p[99],m,M;
main(c){for(gets(s);c=s[i];
j+=strchr("aeiou",c|32)!=0,j-=c<33,m>j?m=j:M<j?M=j:0)
  //move current height up or down, adjust minimum and maximum height
p[i++]=j;  //record height of character
for(;m<=M;putchar(10),M--)  //from maximum to minimum height
for(i=0;c=s[i];)putchar(M^p[i++]?32:c);}  //print only characters on this height


答:
05AB1E, 5 bytes, cracked

I hope that this submission isn't as easy as my other ones :p. Outputs:

```<code>a(0) = 0
a(1) = 1
a(2) = 6
a(3) = 24
a(4) = 80
a(5) = 240
</code>```

Obfuscated code:

```<code>####O
</code>```

Contains some non-ASCII characters though, uses CP-1252 encoding.

Try it online! might come in handy :p.

Body:
05AB1E, 5 bytes, cracked

I hope that this submission isn't as easy as my other ones :p. Outputs:

a(0) = 0
a(1) = 1
a(2) = 6
a(3) = 24
a(4) = 80
a(5) = 240

Obfuscated code:

####O

Contains some non-ASCII characters though, uses CP-1252 encoding.

Try it online! might come in handy :p.


答:
Jolf, 11 bytes, QPaysTaxes, A000005

```<code>aσ0xxdxxxxx
</code>```

Simple enough: alert the σ0 (number of divisors of) x, then put useless stuff at the end.

Try it online! The test suite button's a bit broke, but still shows proper results.

(You could've golfed it down to two bytes! Just σ0 would've done nicely.)

Title: Find the program that prints this integer sequence (Robbers' thread)

Body:
This is the robbers' thread. The cops' thread goes here.

In the cops thread, the task was to write a program/function that takes a positive (or non-negative) integer and outputs/returns another number (not necessarily integer). The robbers task is to unscramble the code the cops used to produce this output.

The cracked code doesn't have to be identical, as long as it has the same length and any revealed characters are in the correct positions. The language must also be the same (version numbers can be different). The output must of course be identical.

No-ops can be used in robber's solution.

The winner of the robbers thread will be the user who has cracked the
most submissions by May 7th 2016. If there's a tie, the user who has cracked submissions with the longest combined code will win.

The submission should be formatted like this:

Language, nn characters (including link to answer), Cop's username

Code:

```<code>function a(n)
    if n<2 then
        return n
    else
        return a(n-1) + a(n-2)
    end
end
</code>```

Output

```<code>a(0) returns 0
a(3) returns 2
</code>```

Optional explanation and comments.

Body:
Jolf, 11 bytes, QPaysTaxes, A000005

aσ0xxdxxxxx

Simple enough: alert the σ0 (number of divisors of) x, then put useless stuff at the end.

Try it online! The test suite button's a bit broke, but still shows proper results.

(You could've golfed it down to two bytes! Just σ0 would've done nicely.)


答:
JavaScript ES6, 119 bytes, Cracked.

Output:

```<code>a(0) = 0
a(5) = 10000
</code>```

Code:

```<code>x=>##=#=>[[[##x####r(###f#n###;#####n####h.##w###<1##].c####t.##pl##[####nc#######y([###(###(#]###)######`#######h####`
</code>```

Returns an anonymous function.

Original sequence: A016744.

Original code:

```<code>x=>{f=n=>[[[1,x] for(x of n)]];return Math.pow(x<<1,[].concat.apply([].concat.apply([],f(f(f([]))))).join``.length)}//`
</code>```

I need to show more characters of obsfucated code next time :P

Body:
JavaScript ES6, 119 bytes, Cracked.

Output:

a(0) = 0
a(5) = 10000

Code:

x=>##=#=>[[[##x####r(###f#n###;#####n####h.##w###<1##].c####t.##pl##[####nc#######y([###(###(#]###)######`#######h####`

Returns an anonymous function.

Original sequence: A016744.

Original code:

x=>{f=n=>[[[1,x] for(x of n)]];return Math.pow(x<<1,[].concat.apply([].concat.apply([],f(f(f([]))))).join``.length)}//`

I need to show more characters of obsfucated code next time :P


答:
05AB1E, 5 bytes, Adnan, A001788

```<code>Læ€OO
</code>```

Try it online! This uses an alternative definition given on the page. Explanation:

```<code>Læ€OO
L     range;      [1..n]
 æ    powerset;   [[], [1], ..., [1..n]]
  €O  mapped sum; [0, 1, ..., T(n)]
    O sum;        [a(n)]
</code>```

Body:
05AB1E, 5 bytes, Adnan, A001788

Læ€OO

Try it online! This uses an alternative definition given on the page. Explanation:

Læ€OO
L     range;      [1..n]
 æ    powerset;   [[], [1], ..., [1..n]]
  €O  mapped sum; [0, 1, ..., T(n)]
    O sum;        [a(n)]


问:
Count the divisors of a number

Introduction

This is a very simple challenge: simply count the divisors of a number. We've had a similar but more complicated challenge before, but I'm intending this one to be entry-level.

The Challenge

Create a program or function that, given one strictly positive integer N, outputs or returns how many divisors it has, including 1 and N.

Input: One integer > 0. You may assume that the number can be represented in your language's native numeric type.

Output: The number of positive integer divisors it has, including 1 and the number itself.

Submissions will be scored in bytes. You may find this website handy, though you may use any reasonable method for generating your byte count.

This is code-golf, so the lowest score wins!

Edit: It looks like FryAmTheEggman's 5-byte Pyth answer is the winner! Feel free to submit new answers, though; if you can get something shorter, I'll change the accepted answer.

Test Cases

```<code>ndiv(1) -> 1
ndiv(2) -> 2
ndiv(12) -> 6
ndiv(30) -> 8
ndiv(60) -> 12
ndiv(97) -> 2
ndiv(100) -> 9
</code>```

Leaderboards

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

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

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

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

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

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

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

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

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

var QUESTION_ID=64944,OVERRIDE_USER=45162;function answersUrl(e){return"http://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"http://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="
"+e.body.replace(OVERRIDE_REG,"")+"
")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?([\d.]+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}</code>```

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

```

答:
JavaScript (ES6), 29 bytes

f=(n,i=n)=>i&&f(n,i-1)+!(n%i)
```

Recursive solution.

Title: Count the divisors of a number

Body:
JavaScript (ES6), 29 bytes

f=(n,i=n)=>i&&f(n,i-1)+!(n%i)

Recursive solution.


答:
MATL, <s>38</s> 37 bytes

```<code>Oj33<G13Y2m-IL)hYstX<-"@Z"GX@)h]Xh!c!
</code>```

Try it online!

Explanation

For each char, the code computes its vertical position, measured from above (0 is highest). It then builds the output string transposed: each char is on a line with as many leading spaces as its vertical position indicates. Then all lines are contatenated into a 2D char array, which is finally transposed and displayed.

```<code>O       % push a 0
j       % input a string
33<     % array of the same length as the input that contains true for spaces or tabs
G       % push input again
11Y2    % string 'aeiouAEIOU'
m       % array of the same length as the input that contains true for vowels
-       % subtract
IL)     % remove last element
h       % prepend the 0 that is at the bottom of the stack
Ys      % cumulative sum. This gives the vertical position of each char
tX<     % duplicate. Compute minimum
-       % subtract. This sets minimum vertical position to 0
"       % for each vertical position
  @     %   push vertical position of current character
  Z"    %   string with that many spaces
  G     %   push input again
  X@)   %   get the character corresponding to the current iteration index
  h     %   concatenate horizontally
]       % end for each
Xh      % concatenate all lines into a row cell array
!       % transpose into a column cell array
c       % convert into 2D array, padding with spaces if needed
!       % transpose. Implicitly display
</code>```

Title: "Stair-ify" a string

Body:
You must write a program or function that creates a "stair-ified" string. Here is how you "stair-ify" a string:

For each character in the string:

If the character is an upper or lowercase vowel, not including 'y', output it then move the rest of the string up a column.

If the character is a space or a tab, output it then move the rest of the string down a colum.

If the character is neither, output it normally.

IO can be in any reasonable format. The input will not contain any newlines. If you want, you can remove any trailing whitespace.

If you choose to return the string, rather than printing it, please also include a short program that will print your string so that it can be visualized. This is not mandatory, nor will it go towards your byte-count. This is just a convenience for users who don't understand golf or esolangs (like me) to be able to verify output or tinker with the code.

Sample IO:

Output for "bcdef ghijkl":

```<code>    f    jkl
bcde  ghi
</code>```

Output for "Programming Puzzles And Code-Golf":

```<code>                               lf
                            -Go
                  s  nd   de
         ng   zzle  A   Co
      mmi   Pu
   gra
Pro
</code>```

Output for "Abcdefghijklmnopqrstuvwxyz":

```<code>                     vwxyz
               pqrstu
         jklmno
     fghi
 bcde
A
</code>```

As usual, this is code-golf, so shortest answer in bytes wins.

Body:
MATL, <s>38</s> 37 bytes

Oj33<G13Y2m-IL)hYstX<-"@Z"GX@)h]Xh!c!

Try it online!

Explanation

For each char, the code computes its vertical position, measured from above (0 is highest). It then builds the output string transposed: each char is on a line with as many leading spaces as its vertical position indicates. Then all lines are contatenated into a 2D char array, which is finally transposed and displayed.

O       % push a 0
j       % input a string
33<     % array of the same length as the input that contains true for spaces or tabs
G       % push input again
11Y2    % string 'aeiouAEIOU'
m       % array of the same length as the input that contains true for vowels
-       % subtract
IL)     % remove last element
h       % prepend the 0 that is at the bottom of the stack
Ys      % cumulative sum. This gives the vertical position of each char
tX<     % duplicate. Compute minimum
-       % subtract. This sets minimum vertical position to 0
"       % for each vertical position
  @     %   push vertical position of current character
  Z"    %   string with that many spaces
  G     %   push input again
  X@)   %   get the character corresponding to the current iteration index
  h     %   concatenate horizontally
]       % end for each
Xh      % concatenate all lines into a row cell array
!       % transpose into a column cell array
c       % convert into 2D array, padding with spaces if needed
!       % transpose. Implicitly display


答:
PHP, 41 bytes, insertusernamehere, A079978

echo/* does n%3=0 */$argv[1]%3<1?1:0    ;
```

Returns 1 if its argument is a multiple of 3, and 0 otherwise. Not much beyond that.

Body:
PHP, 41 bytes, insertusernamehere, A079978

echo/* does n%3=0 */$argv[1]%3<1?1:0    ;

Returns 1 if its argument is a multiple of 3, and 0 otherwise. Not much beyond that.


问:
A simple TCP server
Write a program or function that listens for incoming TCP traffic on port N. It offers a simple service: it calculates sum of IP address fields of incoming connection and returns.

Program or function reads integer N from arguments or stdin. It listens to incoming TCP connections on port N. When someone connects to that port, the program calculates sum of its IP address fields and sends it back to the client with trailing newline and closes connection.

Port number N is a valid port, and 210 < N < 215

Trailing newline can be either \nor \r\n

You can use either IPv4 or IPv6. Since IPv6 addresses are written in hexadecimal form, you must also provide result in same format, for example 2001:0db8:0000:0042:0000:8a2e:0370:7334 => 12ecd.

This is code-golf. Standard rules and loopholes apply.

Example

You run your server with ./server 1234. The server is now running and waiting for connections on port 1234. Then a client from 127.0.0.1 connects to your server. Your server performs a simple calculation: 127+0+0+1 => 128 and sends the result to the client (with trailing newline): 128\n. Then server closes connection and waits for next client.

Leaderboard

var QUESTION_ID=76379,OVERRIDE_USER=20569;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="
"+e.body.replace(OVERRIDE_REG,"")+"
")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}</code>```

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

```

答:
Racket, 265 bytes

```<code>#lang racket(define l(tcp-listen(string->number(read-line))))(let e()(define-values(i o)(tcp-accept l))(thread(λ()(define-values(a b)(tcp-addresses o))(write(~a(foldl + 0(map string->number(string-split a".")))o))(newline o)(close-output-port o)))(e)))
</code>```

Ungolfed:

```<code>#lang racket
(define listener (tcp-listen (string->number (read-line))))
(define (mk-server)
  (let echo-server ()
    (define-values (in out) (tcp-accept listener))
    (thread
     (λ()
       (define-values (a b) (tcp-addresses out))
       (write (number->string (foldl + 0(map string->number(string-split a "."))) out))
       (write "\n" out)
       (close-output-port out)))
    (echo-server)))
</code>```

Title: A simple TCP server

Body:
Racket, 265 bytes

#lang racket(define l(tcp-listen(string->number(read-line))))(let e()(define-values(i o)(tcp-accept l))(thread(λ()(define-values(a b)(tcp-addresses o))(write(~a(foldl + 0(map string->number(string-split a".")))o))(newline o)(close-output-port o)))(e)))

Ungolfed:

#lang racket
(define listener (tcp-listen (string->number (read-line))))
(define (mk-server)
  (let echo-server ()
    (define-values (in out) (tcp-accept listener))
    (thread
     (λ()
       (define-values (a b) (tcp-addresses out))
       (write (number->string (foldl + 0(map string->number(string-split a "."))) out))
       (write "\n" out)
       (close-output-port out)))
    (echo-server)))


答:
JavaScript (ES6), 199

Same algortihm of @Neil's answer. The grid is rotated four times for each directional character, when in the right position the gravity shift to left is applied to each row.

x=>y=>(x=>{for(d of y){R='';for(e of'^>v<')x=[...x[0]].map((c,i)=>e!=d?x.map(r=>r[i]).join``:x.map(r=>(c=r[i])<'.'?(q+=p+c,p=''):c>'.'&&q?(q+=c,R+=c):p+='.',q=p='')&&q+p).reverse();}})(x.split`
`)||R
```

<p><div class="snippet" data-lang="js" data-hide="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>F=x=>y=>(x=>{for(d of y){R='';for(e of'^>v<')x=[...x[0]].map((c,i)=>e!=d?x.map(r=>r[i]).join``:x.map(r=>(c=r[i])<'.'?(q+=p+c,p=''):c>'.'&&q?(q+=c,R+=c):p+='.',q=p='')&&q+p).reverse();}})(x.split`
`)||R

// Less golfed

U=(x,y)=>
{
  x = x.split`\n`;
  for(d of y)
  {
    R = '';
    for(e of '^>v<')
      x = [...x[0]].map(
        (c,i) => e != d
        ? x.map( r => r[i] ).join`` // basic rotation
        : x.map( // rotation with gravity shift
          r=> (c=r[i])<'.' ? (q+=p+c,p='') : c>'.'&&q?(q+=c,R+=c) : p+='.', q=p=''
        ) && q+p
      ).reverse();
  }
  return R
}

console.log=x=>O.textContent+=x+'\n'

;[
  ['abcdef.gh#..\n.......ij.#.\n#..#.......#\n...#.#...###\n.#.......#q#\n.........###',
   [['v>^','dfq']]
  ],
  ['abcde\n.....\n##.##',[['v','abde'],['v>','']]],
  ['######\n#....#\nabcdef\n#.gh..\n######',[['>',''],['<','gh'],['^>','bcde'],['v<','befgh']]]
].forEach(t => {
  var i=t[0]
  console.log(i)
  t[1].forEach(([d,k])=>{
    var r=F(i)(d),ok=[...r].sort().join``==k
    console.log((ok?'OK ':'KO ')+d+' : '+r+(ok?'':' (expected '+k+')'))
  })
  console.log('')
})</code>```

```</code>```

Title: Switching Gravity

Body:
Challenge

You are given an ASCII-art representation of characters on a plane as input by any reasonable method. This will only contain:

[a-z] representing moveable characters. Every letter will appear on the board at most once.

# representing immovable walls

. representing empty space

For example:

```<code>abcdef.gh#..
.......ij.#.
#..#.......#
...#.#...###
.#.......#q#
.........###
</code>```

You are also given a string representing the changes in gravity. This will only contain:

> representing a change to rightward gravity

< representing a change to leftward gravity

^ representing a change to upward gravity

v representing a change to downward gravity

For example:

```<code>v>^
</code>```

Your program must simulate the each change in gravity sequentially until all characters stop moving (they hit a wall, or another character). Characters that "fall off the edge of the map" are permanently removed, and characters can "stack" on top of each other.

In this example, at the start there is downward gravity (v), so c, e, g, h, i, and j fall off the bottom of the map. All other characters slide downwards until hitting a wall, leaving the map like this:

```<code>.........#..
a..d......#.
#..#.f.....#
.b.#.#...###
.#.......#q#
.........###
</code>```

Then, we move on to rightward gravity (>), which leaves us with this:
Note how the a stacks next to the d.

```<code>.........#..
........ad#.
#..#......f#
..b#.#...###
.#.......#q#
.........###
</code>```

Finally, we simulate upward gravity (^), during which the a and the b fall off the map.

```<code>.........#..
.........d#.
#..#......f#
...#.#...###
.#.......#q#
.........###
</code>```

Your task is to output the remaining characters after the gravitational shifts. They can be given in any order. For this example, you could output any permutation of dfq.

Testcases

For the following map:

```<code>abcde
.....
##.##
</code>```

```<code>v   =  abde
v>  =  <nothing>
</code>```

For the following map:

```<code>######
#....#
abcdef
#.gh..
######
</code>```

```<code>>   = <nothing>
<   = gh
^>  = bcde
v<  = bghef
</code>```

Body:
JavaScript (ES6), 199

Same algortihm of @Neil's answer. The grid is rotated four times for each directional character, when in the right position the gravity shift to left is applied to each row.

x=>y=>(x=>{for(d of y){R='';for(e of'^>v<')x=[...x[0]].map((c,i)=>e!=d?x.map(r=>r[i]).join``:x.map(r=>(c=r[i])<'.'?(q+=p+c,p=''):c>'.'&&q?(q+=c,R+=c):p+='.',q=p='')&&q+p).reverse();}})(x.split`
`)||R

F=x=>y=>(x=>{for(d of y){R='';for(e of'^>v<')x=[...x[0]].map((c,i)=>e!=d?x.map(r=>r[i]).join``:x.map(r=>(c=r[i])<'.'?(q+=p+c,p=''):c>'.'&&q?(q+=c,R+=c):p+='.',q=p='')&&q+p).reverse();}})(x.split`
`)||R

// Less golfed

U=(x,y)=>
{
  x = x.split`\n`;
  for(d of y)
  {
    R = '';
    for(e of '^>v<')
      x = [...x[0]].map(
        (c,i) => e != d
        ? x.map( r => r[i] ).join`` // basic rotation
        : x.map( // rotation with gravity shift
          r=> (c=r[i])<'.' ? (q+=p+c,p='') : c>'.'&&q?(q+=c,R+=c) : p+='.', q=p=''
        ) && q+p
      ).reverse();
  }
  return R
}

console.log=x=>O.textContent+=x+'\n'

;[
  ['abcdef.gh#..\n.......ij.#.\n#..#.......#\n...#.#...###\n.#.......#q#\n.........###',
   [['v>^','dfq']]
  ],
  ['abcde\n.....\n##.##',[['v','abde'],['v>','']]],
  ['######\n#....#\nabcdef\n#.gh..\n######',[['>',''],['<','gh'],['^>','bcde'],['v<','befgh']]]
].forEach(t => {
  var i=t[0]
  console.log(i)
  t[1].forEach(([d,k])=>{
    var r=F(i)(d),ok=[...r].sort().join``==k
    console.log((ok?'OK ':'KO ')+d+' : '+r+(ok?'':' (expected '+k+')'))
  })
  console.log('')
})

<pre id=O></pre>


问:
Tips for golfing in Racket / Scheme
What general tips do you have for golfing in Racket / Scheme? I'm looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to Racket / Scheme (e.g. "remove comments" is not an answer).

I'm aware Scheme and Racket (formerly PLT Scheme) are technically different languages but are quite similar in many ways and much code (I suspect) will run mostly as intended in either. If your tip only applies to one of the aforementioned languages, note as such.

答: Use ~a to convert numbers and symbols to strings.

Title: Tips for golfing in Racket / Scheme


答:
Jolf, 13 bytes, safe!

Outputs:

```<code>a(5) = 40
a(8) = 128
</code>```

Code:

```<code>#+~##~####xx#
</code>```

Interpreter.

Revealed:

 OEIS A003600```γ+~iu~iZCzxxγ<br>γ              γ = <br>         zx    range 1..x (input)<br>       ZC      cumulutive sum<br>     ~i        identity<br>    u          sum of<br>  ~i           identity<br> +         x   plus x<br>            γ  out γ```

Body:
This is the cops' thread. The robbers' thread goes here.

The last cops-and-robbers thread was already 4 months ago.

The cop's task

The cop's task is to write a program/function that takes a positive (or non-negative) integer and outputs/returns another integer.

The cop must state it if the program is intolerant towards zero.

The cop will provide at least 2 sample inputs/outputs.

For example, if I have decided to write the Fibonacci sequence, I would write this in my answer:

```
a(0) returns 0
a(3) returns 2
```

The number of examples is up to the cop's discretion.

However, the sequence must actually exist in the On-Line Encyclopedia of Integer Sequences®, so no pseudo-random number generator for you. :(

The cop can hide as many characters as is so wished.

For example, if my program is:

```<code>function a(n)
    if n>2 then
        return n
    else
        return a(n-1) + a(n-2)
    end
end
</code>```

Then I would hide these characters as I want:

```<code>function a(n)
    if ### then
        ########
    else
        ######################
    end
end
</code>```

The robber's task

is obviously to find the original source code.

However, any proposed source code that produces the same set of output also counts as valid, as long as it is also found in OEIS.

Tips for the cops

<s>The search function in the OEIS only works for consecutive terms, so if you want to hide your sequence, then just leave a hole anywhere.</s>

Apparently there is no way to hide the sequence. Put this in mind when you choose the sequence.

Your score is the number of bytes in your code.

The winner will be the submission with the lowest score that hasn't been cracked in 7 days.

Only submissions that are posted in 2016 April are eligible for the win. Submissions that are posted later than this are welcome, but cannot win.

In order to claim the win you need to reveal the full code and the OEIS sequence (after 7 days).

Your post should be formatted like this (NN is the number of characters):

Lua, 98 bytes

Output:

```<code>a(0) returns 0
a(3) returns 2
</code>```

Code (# marks unrevealed characters):

```<code>function a(n)
    if ### then
        ########
    else
        ######################
    end
end
</code>```

If the code is cracked, insert [Cracked](link to cracker) in the header.
If the submission is safe, insert "Safe" in the header and reveal the full code in your answer. Only answers that have revealed the full code will be eligible for the win.

Body:
Jolf, 13 bytes, safe!

Outputs:

a(5) = 40
a(8) = 128

Code:

#+~##~####xx#

Interpreter.

Revealed:

 OEIS A003600
γ+~iu~iZCzxxγ
γ              γ =
         zx    range 1..x (input)
       ZC      cumulutive sum
     ~i        identity
    u          sum of
  ~i           identity
 +         x   plus x
            γ  out γ


问:
Tips for golfing in Factor
What general tips do you have for golfing in Factor? I'm looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to Factor (e.g. "remove comments" is not an answer).</p>

答:
find all the higher-order functions and use them, often

Factor is full of higher-order functions that take [ quotations ]  or other-words and work on sequences / other data.

For example, to take an IP address as a string and sum its fields, you could do:

```<code>"." split [ 10 >base ] [ + ] map-reduce 10 base>
"." split [ 10 >base ] map 0 + reduce 10 base>
"." split [ 10 >base ] map sum 10 base>
</code>```

Notice that fancy map-reduce is actually longest here because of [ quotation ] syntax, but there's already a sum word for that anyways, which is far shorter.

Here's a place map-reduce is shorter:

```<code>[ "." split [ 10 base> ] [ [ 256 * ] dip + ] map-reduce ] bi@ - abs 1 + ]
[ "." split [ 10 base> ] map 0 [ [ 256 * ] dip + ] reduce ] bi@ - abs 1 + ]
</code>```

Can't use sum there.

Title: Tips for golfing in Factor

Body:
find all the higher-order functions and use them, often

Factor is full of higher-order functions that take [ quotations ]  or other-words and work on sequences / other data.

For example, to take an IP address as a string and sum its fields, you could do:

"." split [ 10 >base ] [ + ] map-reduce 10 base>
"." split [ 10 >base ] map 0 + reduce 10 base>
"." split [ 10 >base ] map sum 10 base>

Notice that fancy map-reduce is actually longest here because of [ quotation ] syntax, but there's already a sum word for that anyways, which is far shorter.

Here's a place map-reduce is shorter:

[ "." split [ 10 base> ] [ [ 256 * ] dip + ] map-reduce ] bi@ - abs 1 + ]
[ "." split [ 10 base> ] map 0 [ [ 256 * ] dip + ] reduce ] bi@ - abs 1 + ]

Can't use sum there.


答:
The infix vocabulary is pretty cool.

It allows for infix notation math, which sounds lame since Factor's RPN, but:

```<code>IN: scratchpad USE: infix
IN: scratchpad [infix 5-40/10*2 infix] .
-3
</code>```

For longer expressions it's much shorter than RPN because of whitespace, but you'll need to overcome the [infix syntax's length.

It also allows Python-style slicing:

```<code>USING: arrays locals infix ;
[let "foobar" :> s [infix s[0:3] infix] ] .
"foo"
</code>```

Additionally, you can step through sequences with seq[from:to:step]
  notation.

```<code>USING: arrays locals infix ;
[let "reverse" :> s [infix s[::-1] infix] ] .
"esrever"

USING: arrays locals infix ;
[let "0123456789" :> s [infix s[::2] infix] ] .
"02468"
</code>```

Title: Tips for golfing in Factor

Body: What general tips do you have for golfing in Factor? I'm looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to Factor (e.g. "remove comments" is not an answer).</p>

Body:
The infix vocabulary is pretty cool.

It allows for infix notation math, which sounds lame since Factor's RPN, but:

IN: scratchpad USE: infix
IN: scratchpad [infix 5-40/10*2 infix] .
-3

For longer expressions it's much shorter than RPN because of whitespace, but you'll need to overcome the [infix syntax's length.

It also allows Python-style slicing:

USING: arrays locals infix ;
[let "foobar" :> s [infix s[0:3] infix] ] .
"foo"

Additionally, you can step through sequences with seq[from:to:step]
  notation.

USING: arrays locals infix ;
[let "reverse" :> s [infix s[::-1] infix] ] .
"esrever"

USING: arrays locals infix ;
[let "0123456789" :> s [infix s[::2] infix] ] .
"02468"


问:
Running length of the movie in a human readable format
Whenever I search for the running length of a movie in IMDb, it is displayed in minutes. Immediately I would try to convert it into hour(s) and minute(s). It would be better if we could automate this.

Input:

```<code>150 min
</code>```

Output:

```<code>2 hours 30 minutes
</code>```

Input:

```<code>90 min
</code>```

Output:

```<code>1 hour 30 minutes
</code>```

Input:

```<code>61 min
</code>```

Output:

```<code>1 hour 1 minute
</code>```

Input:

```<code>60 min
</code>```

Output:

```<code>1 hour 0 minute or 1 hour 0 minutes
</code>```

Following are the conditions:

Input and Output should be in this exact format.

Input minutes will between 0 and 240.

Your answer can accept command line arguments or read input from the
user or a function.

Output should not be enclosed within quotes.

Output must be printed, not returned.

Leaderboard:

    var QUESTION_ID=65106,OVERRIDE_USER=16196;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/65106/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="
"+e.body.replace(OVERRIDE_REG,"")+"
")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;```
<pre class="snippet-code-css lang-css prettyprint-override"><code>    body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}#answer-list{padding-right: 100px}</code>```

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

```

Result:

Its a tie between CJam and Pyth. Accepting CJam's answer as it was submitted before Pyth's 35 bytes code. However, please continue encouraging new submissions.

答:
Factor, <s>95</s> 88 bytes

```<code>[ readln " " split first 10 >base [ 60 / floor ] [ 60 mod ] bi "%s hrs %s mins" printf ]
</code>```

Like my Go answer, doesn't handle plurals because it doesn't have to.

Body:
Factor, <s>95</s> 88 bytes

[ readln " " split first 10 >base [ 60 / floor ] [ 60 mod ] bi "%s hrs %s mins" printf ]

Like my Go answer, doesn't handle plurals because it doesn't have to.


答:
C, 71 bytes cracked

```<code>############
#####
main(){
 scanf("%d",##);
 ###6#;
 printf("%d",##);
}
</code>```

Output:

```<code>a(1) = 0   a(2) = 0   a(5) = 1
a(6) = 1   a(7) = 1   a(9) = 2
</code>```

This works with gcc, and is a full program. It accepts 0 as input.

Body:
C, 71 bytes cracked

############
#####
main(){
 scanf("%d",##);
 ###6#;
 printf("%d",##);
}

Output:

a(1) = 0   a(2) = 0   a(5) = 1
a(6) = 1   a(7) = 1   a(9) = 2

This works with gcc, and is a full program. It accepts 0 as input.


答:
Pyke, 6 bytes, Cracked

```<code>###X#s
</code>```

Output:

```<code>a(2) = 8
a(8) = 80
a(10) = 120
</code>```

This doesn't work with N<1

Original solution:

 hSmX$s

Body:
Pyke, 6 bytes, Cracked

###X#s

Output:

a(2) = 8
a(8) = 80
a(10) = 120

This doesn't work with N<1

Original solution:

 hSmX$s


答:
When converting between numbers and strings, the

```<code>string>number
number>string
</code>```

words can be shortened to:

```<code>dec>
>dec
</code>```

respectively (thanks, chunes, again!).

There are also:

bin> and >bin for binary

oct> and >oct for octal

hex> and >hex for hexadecimal

that are all shorter than n base>, if they happen to suit your needs!

And if you need integers, use 1 /i instead of >integer:

```<code>5 3 /i
5 3 / >integer   = .
=> t
5.77 1 /i
5.77 >integer    = .
=> t
</code>```

EDIT:

If it's about printing, keep an eye on these too:

```<code>.b ! prints a number in binary
.o ! prints a number in octal
.h ! prints a number in hexadecimal
</code>```

Title: Tips for golfing in Factor

Body:
When converting between numbers and strings, the

string>number
number>string

words can be shortened to:

dec>
>dec

respectively (thanks, chunes, again!).

There are also:

bin> and >bin for binary

oct> and >oct for octal

hex> and >hex for hexadecimal

that are all shorter than n base>, if they happen to suit your needs!

And if you need integers, use 1 /i instead of >integer:

5 3 /i
5 3 / >integer   = .
=> t
5.77 1 /i
5.77 >integer    = .
=> t

EDIT:

If it's about printing, keep an eye on these too:

.b ! prints a number in binary
.o ! prints a number in octal
.h ! prints a number in hexadecimal

ContentLicense: CC BY-SA 4.0


答:
Pyke, 6 bytes, muddyfish, A005563

```<code>0QhXts
</code>```

Yay hacks! The 0Qh and s are no-ops. hXt just computes (n + 1) ^ 2 - 1.

Body:
This is the robbers' thread. The cops' thread goes here.

In the cops thread, the task was to write a program/function that takes a positive (or non-negative) integer and outputs/returns another number (not necessarily integer). The robbers task is to unscramble the code the cops used to produce this output.

The cracked code doesn't have to be identical, as long as it has the same length and any revealed characters are in the correct positions. The language must also be the same (version numbers can be different). The output must of course be identical.

No-ops can be used in robber's solution.

The winner of the robbers thread will be the user who has cracked the
most submissions by May 7th 2016. If there's a tie, the user who has cracked submissions with the longest combined code will win.

The submission should be formatted like this:

Language, nn characters (including link to answer), Cop's username

Code:

```<code>function a(n)
    if n<2 then
        return n
    else
        return a(n-1) + a(n-2)
    end
end
</code>```

Output

```<code>a(0) returns 0
a(3) returns 2
</code>```

Optional explanation and comments.

Body:
Pyke, 6 bytes, muddyfish, A005563

0QhXts

Yay hacks! The 0Qh and s are no-ops. hXt just computes (n + 1) ^ 2 - 1.


答:
MATL, 5 bytes, Luis Mendo

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

This code calculates abs((2-5)*input) which is just a(n)=3*n for positive numbers, which is http://oeis.org/A008585

Body:
MATL, 5 bytes, Luis Mendo

H5-*|

This code calculates abs((2-5)*input) which is just a(n)=3*n for positive numbers, which is http://oeis.org/A008585


问:
Mask an IP address and give its broadcast

Background

Inspired by this Unix.SE question (and of course my own answer).

When an IP address is specified for an interface, it is often given in this dotted-decimal form:

```<code>a.b.c.d e.f.g.h
</code>```

where a.b.c.d is the actual address and e.f.g.h is the netmask.

The netmask, when represented in binary, is basically a bunch of 1 bits followed by a bunch of 0 bits.  When the netmask is bitwise ANDed against the given IP address, result will be the network portion of the address, or simply the network address.  This will be programmed into the host's route table so that the host knows to send anything destined for this network out this interface.

The broadcast address for a network is derived by taking the network address (from above) and setting all the host-bits to 1.  The broadcast address is used to send to all addresses within the given network.

Challenge

Given a dotted-decimal IP address and valid netmask as input, provide the network address and broadcast address as output, also in dotted-decimal format.

Input must be address and mask as two strings in dotted-decimal format.  You may pass this as 2 separate strings, as list or array of 2 string elements or a single string with the address and mask separated by some sensible separator.

Output format is subject to the same constraints as input format.

Examples

```<code>Input                              Output

192.168.0.1 255.255.255.0          192.168.0.0 192.168.0.255
192.168.0.0 255.255.255.0          192.168.0.0 192.168.0.255
192.168.0.255 255.255.255.0        192.168.0.0 192.168.0.255
100.200.100.200 255.255.255.255    100.200.100.200 100.200.100.200
1.2.3.4 0.0.0.0                    0.0.0.0 255.255.255.255
10.25.30.40 255.252.0.0            10.24.0.0 10.27.255.255
</code>```

答:
Factor, 103 bytes

```<code>[ [ ipv4-aton ] bi@ 2dup bitand -rot dup bit-count 32 - abs on-bits pick bitor 2nip [ ipv4-ntoa ] bi@ ]
</code>```

Nice.

Ungolfed:

```<code>: mask-and-broadcast ( ip mask -- netaddr broadcast )
  [ ipv4-aton ] bi@ 2dup bitand -rot dup bit-count 32 - abs on-bits pick bitor 2nip
  [ ipv4-ntoa ] bi@ ;
</code>```

Body:
Factor, 103 bytes

[ [ ipv4-aton ] bi@ 2dup bitand -rot dup bit-count 32 - abs on-bits pick bitor 2nip [ ipv4-ntoa ] bi@ ]

Nice.

Ungolfed:

: mask-and-broadcast ( ip mask -- netaddr broadcast )
  [ ipv4-aton ] bi@ 2dup bitand -rot dup bit-count 32 - abs on-bits pick bitor 2nip
  [ ipv4-ntoa ] bi@ ;


答:
05AB1E, 5 bytes, safe

Last one for today :p. Output:

```<code>a(0) = 9
a(5) = 4
a(10) = 89
</code>```

Code:

```<code>___m_
</code>```

Obfuscated characters are indicated with _. Try it online!-link. Uses CP-1252 encoding.

Solution:

```<code>žhžm‡
</code>```

Explanation:

```<code>žh       # Short for [0-9].
  žm     # Short for [9-0].
    ‡    # Translate.
</code>```

Try it online! or Try for all test cases!.

Body:
05AB1E, 5 bytes, safe

Last one for today :p. Output:

a(0) = 9
a(5) = 4
a(10) = 89

Code:

___m_

Obfuscated characters are indicated with _. Try it online!-link. Uses CP-1252 encoding.

Solution:

žhžm‡

Explanation:

žh       # Short for [0-9].
  žm     # Short for [9-0].
    ‡    # Translate.

Try it online! or Try for all test cases!.


Body:
Jolf, 3 bytes Cracked, A001477

___

Examples:

0 -> 0

1 -> 1

4 -> 4

9 -> 9

Original Code:

 "%"


答:
Jolf, 3 bytes, Easterly Irk, A001477

```<code>axx
</code>```

Consists of a simple cat (ax) followed by a no-op. Not sure what the cop was going for here.

Body:
Jolf, 3 bytes, Easterly Irk, A001477

axx

Consists of a simple cat (ax) followed by a no-op. Not sure what the cop was going for here.


问:
Make a Strawpoll

Moderator note: https://strawpoll.me has officially shut down, and the linked API no longer appears to work or provide data. Therefore, new answers cannot actually do the task and so the challenge has been closed to prevent any new answers.

Strawpolls are great, and we use them in chat all the time for getting opinions on things. But they're kinda annoying to make since you need a webbrowser to make them, and everyone knows that I access PPCG only through SE APIs and curl. So I want you to write some code that uses Strawpoll's API to make a strawpoll with the given options.

Specs

Take as input a list in any reasonable format of options as strings, and a title which is also a string. Then use the API to make a strawpoll with that title and those options and output the url.

Multiples should not be allowed, duplicate checking should be enforced, and captchas should not be necessary.

Example

```<code>"My Awesome Poll"
["option 1", "I like pies", "I also like cakes"]
</code>```

Output: http://strawpoll.me/7275997

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

答:
Factor, <s>257</s> 262 bytes

```<code>TUPLE: p title options dupcheck ;
[ command-line rest [ first ] [ rest ] bi "normal" p boa >json "https://strawpoll.me/api/v2/polls" <post-request> "application/json" "Content-Type" set-header http-request nip json> id>> 10 base> "http://strawpoll.me/" prepend ]
</code>```

Expects a name as the first command-line arg, then options after that.

Requires com-auto-use.

Ungolfed:

```<code>TUPLE: poll
  title options dupcheck ;

: post-json ( post-data url -- response data )
  <post-request>
    "application/json" "Content-Type" set-header
  http-request ;

: strawpoll-main ( -- )
  command-line rest [ first ] [ rest ] bi "normal" poll boa
  >json "https://strawpoll.me/api/v2/polls" post-json nip
  json> id>> 10 base> "http://strawpoll.me/" prepend print ;
</code>```

Title: Make a Strawpoll

Body:
Factor, <s>257</s> 262 bytes

TUPLE: p title options dupcheck ;
[ command-line rest [ first ] [ rest ] bi "normal" p boa >json "https://strawpoll.me/api/v2/polls" <post-request> "application/json" "Content-Type" set-header http-request nip json> id>> 10 base> "http://strawpoll.me/" prepend ]

Expects a name as the first command-line arg, then options after that.

Requires com-auto-use.

Ungolfed:

TUPLE: poll
  title options dupcheck ;

: post-json ( post-data url -- response data )
  <post-request>
    "application/json" "Content-Type" set-header
  http-request ;

: strawpoll-main ( -- )
  command-line rest [ first ] [ rest ] bi "normal" poll boa
  >json "https://strawpoll.me/api/v2/polls" post-json nip
  json> id>> 10 base> "http://strawpoll.me/" prepend print ;


Body:
This is the cops' thread. The robbers' thread goes here.

The last cops-and-robbers thread was already 4 months ago.

The cop's task

The cop's task is to write a program/function that takes a positive (or non-negative) integer and outputs/returns another integer.

The cop must state it if the program is intolerant towards zero.

The cop will provide at least 2 sample inputs/outputs.

For example, if I have decided to write the Fibonacci sequence, I would write this in my answer:

```
a(0) returns 0
a(3) returns 2
```

The number of examples is up to the cop's discretion.

However, the sequence must actually exist in the On-Line Encyclopedia of Integer Sequences®, so no pseudo-random number generator for you. :(

The cop can hide as many characters as is so wished.

For example, if my program is:

```<code>function a(n)
    if n>2 then
        return n
    else
        return a(n-1) + a(n-2)
    end
end
</code>```

Then I would hide these characters as I want:

```<code>function a(n)
    if ### then
        ########
    else
        ######################
    end
end
</code>```

The robber's task

is obviously to find the original source code.

However, any proposed source code that produces the same set of output also counts as valid, as long as it is also found in OEIS.

Tips for the cops

<s>The search function in the OEIS only works for consecutive terms, so if you want to hide your sequence, then just leave a hole anywhere.</s>

Apparently there is no way to hide the sequence. Put this in mind when you choose the sequence.

Your score is the number of bytes in your code.

The winner will be the submission with the lowest score that hasn't been cracked in 7 days.

Only submissions that are posted in 2016 April are eligible for the win. Submissions that are posted later than this are welcome, but cannot win.

In order to claim the win you need to reveal the full code and the OEIS sequence (after 7 days).

Your post should be formatted like this (NN is the number of characters):

Lua, 98 bytes

Output:

```<code>a(0) returns 0
a(3) returns 2
</code>```

Code (# marks unrevealed characters):

```<code>function a(n)
    if ### then
        ########
    else
        ######################
    end
end
</code>```

If the code is cracked, insert [Cracked](link to cracker) in the header.
If the submission is safe, insert "Safe" in the header and reveal the full code in your answer. Only answers that have revealed the full code will be eligible for the win.

Body:
Jolf, 11 bytes, Cracked , A011551

c*______x__

c*mf^+91x~P

Original code:

c*^c"10"x~P

Examples:

0 -> 1

12 -> 1618033988749


答:
Java, 479 bytes, Cracked

Outputs:

```<code>a(10) = 81
a(20) = 35890
</code>```

(Inputs are provided via command line arguments)

Code (# marks hidden characters):

```<code>import java.util.*;
public class A{

    public static int#########
    public boolean###########

    static A a = new A();

    public static void main(String[] args){
        int input = Integer.parseInt(args[0]);

        LinkedList<Integer> l = new LinkedList<>();
        l.add(1);
        l.add(0);
        l.add(0);

        for(int ix = 0; ################if(##>##{
            ###########d#
            #######+##p##########+##########(#######
        }

        System.out.println(#########################
            ###(A.#############(#5#####)));
    }
}
</code>```

The program starts at index 0.

(Note that SE replaces all of the \t indents with 4 spaces, bringing the byte total to 569. Click here to see the program with \t indents instead of space indents.)

Original code:

```<code>import java.util.*;
public class A{
    public static interface B{
    public boolean C(int i);}

    static A a = new A();

    public static void main(String[] args){
        int input = Integer.parseInt(args[0]);

        LinkedList<Integer> l = new LinkedList<>();
        l.add(1);
        l.add(0);
        l.add(0);

        for(int ix = 0; ix<input; ix++)cif(i->  {
            return l.add(
            l.pop()+l.peekFirst()+l.peekLast());});{
        }

        System.out.println(l.get(1));}static boolean
            cif(A.B b5){return (b5.C((0)));
    }
}
</code>```

(Same code, but formatted normally):

```<code>import java.util.*;

public class A {
    public static interface B { //functional interface for lambda expression
        public boolean C(int i); //void would have given it away
    }

    static A a = new A(); //distraction

    public static void main(String[] args) {
        int input = Integer.parseInt(args[0]);//Input

        LinkedList<Integer> l = new LinkedList<>();
        l.add(1);//Set up list
        l.add(0);
        l.add(0);

        for (int ix = 0; ix < input; ix++)
            cif(i -> { //Fake if statement is really a lambda expression
                return l.add(l.pop() + l.peekFirst() + l.peekLast());
            });
        { //Distraction
        }

        System.out.println(l.get(1));//Output
    }

    static boolean cif(A.B b5) { //Used to pass in lambda expression.
                  //The A. and b5 were both distractions
        return (b5.C((0)));
    }
}
</code>```

Body:
Java, 479 bytes, Cracked

Outputs:

a(10) = 81
a(20) = 35890

(Inputs are provided via command line arguments)

Code (# marks hidden characters):

import java.util.*;
public class A{

    public static int#########
    public boolean###########

    static A a = new A();

    public static void main(String[] args){
        int input = Integer.parseInt(args[0]);

        LinkedList<Integer> l = new LinkedList<>();
        l.add(1);
        l.add(0);
        l.add(0);

        for(int ix = 0; ################if(##>##{
            ###########d#
            #######+##p##########+##########(#######
        }

        System.out.println(#########################
            ###(A.#############(#5#####)));
    }
}

The program starts at index 0.

(Note that SE replaces all of the \t indents with 4 spaces, bringing the byte total to 569. Click here to see the program with \t indents instead of space indents.)

Original code:

import java.util.*;
public class A{
    public static interface B{
    public boolean C(int i);}

    static A a = new A();

    public static void main(String[] args){
        int input = Integer.parseInt(args[0]);

        LinkedList<Integer> l = new LinkedList<>();
        l.add(1);
        l.add(0);
        l.add(0);

        for(int ix = 0; ix<input; ix++)cif(i->  {
            return l.add(
            l.pop()+l.peekFirst()+l.peekLast());});{
        }

        System.out.println(l.get(1));}static boolean
            cif(A.B b5){return (b5.C((0)));
    }
}

(Same code, but formatted normally):

import java.util.*;

public class A {
    public static interface B { //functional interface for lambda expression
        public boolean C(int i); //void would have given it away
    }

    static A a = new A(); //distraction

    public static void main(String[] args) {
        int input = Integer.parseInt(args[0]);//Input

        LinkedList<Integer> l = new LinkedList<>();
        l.add(1);//Set up list
        l.add(0);
        l.add(0);

        for (int ix = 0; ix < input; ix++)
            cif(i -> { //Fake if statement is really a lambda expression
                return l.add(l.pop() + l.peekFirst() + l.peekLast());
            });
        { //Distraction
        }

        System.out.println(l.get(1));//Output
    }

    static boolean cif(A.B b5) { //Used to pass in lambda expression.
                  //The A. and b5 were both distractions
        return (b5.C((0)));
    }
}


问:
418: I'm a teapot
As we all should know, there's a HTTP status code 418: I'm a teapot.

Your mission, should you choose to accept it, is to use your creativitea and write the smallest possible server that responds with the above status code to any and every HTTP request made to it.

Standard loopholes apply, including

Fetching the desired output from an external source

This includes doing an HTTP request to fetch the page with the
question and extracting a solution from that page. This was mildly
amusing back in 2011, but now is derivative and uninteresting.

Meaning you cannot simply redirect the request to another server to have it return the response.

Your server can do anything (or nothing) while no HTTP request is made to it as long as it replies with the correct response once a HTTP request is made.

答:
Factor, <s>101</s> 141 bytes

```<code>[ utf8 <threaded-server> readln 10 base> >>insecure [ "HTTP/1.1 418\r" print flush ] >>handler [ start-server ] in-thread start-server drop ]
</code>```

Return 418 to everyone who connects.

Title: 418: I'm a teapot

Body:
Factor, <s>101</s> 141 bytes

[ utf8 <threaded-server> readln 10 base> >>insecure [ "HTTP/1.1 418\r" print flush ] >>handler [ start-server ] in-thread start-server drop ]

Return 418 to everyone who connects.


问:
De-Snakify a String
A regular string looks like this:

```<code>Hello,IAmAStringSnake!
</code>```

And a string snake looks something like this:

```<code>Hel
  l      rin
  o,IAmASt g
           S
       !ekan
</code>```

Your Task

String snakes are dangerous, so you must make a program that takes a string snake as input and outputs it as a regular string.

Specifications

Input can be a multiline string or an array of strings.

Each line of the input will be padded with spaces to form a rectangular grid.

Characters in the snake can only connect to adjacent characters above, below, left or right of them (just like in the game Snake). They cannot go diagonal.

The snake characters will never be adjacent to another part of the snake, only the connected characters.

The first character of the string is the end character with the shortest Manhattan distance from the top-left corner of the input grid (i.e. the minimum number of moves it would take for a snake to go directly from the end character to the top-left corner). Both ends will never have the same distance.

The string can contain any ASCII character between code points 33 and 126 inclusive (no spaces or newlines).

The string will be between 2 and 100 characters long.

Shortest code in bytes wins.

Test Cases

(Input grid, followed by the output string)

```<code>Hel
  l      rin
  o,IAmASt g
           S
       !ekan

Hello,IAmAStringSnake!

----------

Python

Python

----------

P  ngPu  Code
r  i  z  d  G
o  m  z  n  o
gram  lesA  lf

ProgrammingPuzzlesAndCodeGolf

----------

   ~ zyx tsr XWVUTSR
   }|{ wvu q Y     Q
!          p Z `ab P
"#$ 6789:; o [ _ c O
  % 5    < n \]^ d N
('& 432  = m     e M
)     1  > lkjihgf L
*+,-./0  ?         K
         @ABCDEFGHIJ

!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~

----------

  tSyrep
  r    p
  in Sli
   g    Sile
   Snakes  n
Ser      ylt
a eh   ilS
fe w   t
   emo h
     Sre

SlipperyStringSnakesSilentlySlitherSomewhereSafe
</code>```

答:
Lua, 267 bytes

Lua 5.3 is required.

e=" "w=#arg[1]+1i=1/0q=0s=table.concat(arg,e)s=e:rep(#s)..s
m,n=i,{}for p in s:gmatch"()%g"do u=-1
for _,d in ipairs{-1,1,-w,w}do u=u+(s:find("^%S",d+p)or 0)end
n[p]=u+1m=math.min(m,p*i^(u//#s)+(p%w*w+p)*#s)end
p=m%#s repeat q,p=p,n[p]-q io.write(s:sub(q,q))until p<1
```

<p>Usage:</p>

<pre class="lang-bash prettyprint-override"><code>$ lua desnakify.lua \
>    "  tSyrep    " \
>    "  r    p    " \
>    "  in Sli    " \
>    "   g    Sile" \
>    "   Snakes  n" \
>    "Ser      ylt" \
>    "a eh   ilS  " \
>    "fe w   t    " \
>    "   emo h    " \
>    "     Sre    "
SlipperyStringSnakesSilentlySlitherSomewhereSafe
</code>```

Title: De-Snakify a String

Body:
Lua, 267 bytes

Lua 5.3 is required.

e=" "w=#arg[1]+1i=1/0q=0s=table.concat(arg,e)s=e:rep(#s)..s
m,n=i,{}for p in s:gmatch"()%g"do u=-1
for _,d in ipairs{-1,1,-w,w}do u=u+(s:find("^%S",d+p)or 0)end
n[p]=u+1m=math.min(m,p*i^(u//#s)+(p%w*w+p)*#s)end
p=m%#s repeat q,p=p,n[p]-q io.write(s:sub(q,q))until p<1

Usage:

$ lua desnakify.lua \
>    "  tSyrep    " \
>    "  r    p    " \
>    "  in Sli    " \
>    "   g    Sile" \
>    "   Snakes  n" \
>    "Ser      ylt" \
>    "a eh   ilS  " \
>    "fe w   t    " \
>    "   emo h    " \
>    "     Sre    "
SlipperyStringSnakesSilentlySlitherSomewhereSafe


答:
Octave, 34 bytes, cracked

```<code>@(m)(m###m#####m##)&isprime(#)####
</code>```

Outputs:

```<code>ans(1) = 0
ans(6) = 5
ans(7) = 10
ans(8) = 15
</code>```

The sequence starts at ans(1) in OEIS.

Body:
Octave, 34 bytes, cracked

@(m)(m###m#####m##)&isprime(#)####

Outputs:

ans(1) = 0
ans(6) = 5
ans(7) = 10
ans(8) = 15

The sequence starts at ans(1) in OEIS.


答:
Jolf, 11 bytes, RikerW, A011551

Code:

```<code>c*mf^+91x~P
</code>```

Explanation:

```<code>     +91     # add(9, 1) = 10
    ^   x    # 10 ** input
  mf         # floor function (no-op)
 *       ~P  # multiply by phi
c            # ¯\_(ツ)_/¯
</code>```

Try it here.

Body:
Jolf, 11 bytes, RikerW, A011551

Code:

c*mf^+91x~P

Explanation:

     +91     # add(9, 1) = 10
    ^   x    # 10 ** input
  mf         # floor function (no-op)
 *       ~P  # multiply by phi
c            # ¯\_(ツ)_/¯

Try it here.


答:
MATL, 9 bytes, Cracked

Code:

```<code>3#2###*##
</code>```

Output:

```<code>a(1)  = 3
a(2)  = 6
a(4)  = 12
a(12) = 37
</code>```

a(0) is valid.

Cracked

Original sequence:
A059563

Original code:

```<code>3L2^Ze*sk
3L          % Push [1 -1j] from the clipboard
  2^        % square
    Ze      % exp
      *     % times input
       s    % sum
        k   % floor
</code>```

Body:
MATL, 9 bytes, Cracked

Code:

3#2###*##

Output:

a(1)  = 3
a(2)  = 6
a(4)  = 12
a(12) = 37

a(0) is valid.

Cracked

Original sequence:
A059563

Original code:

3L2^Ze*sk
3L          % Push [1 -1j] from the clipboard
  2^        % square
    Ze      % exp
      *     % times input
       s    % sum
        k   % floor


答:
MATL, 9 bytes, beaker, A022844

Code (with a whitespace at the end):

```<code>3x2xYP*k
</code>```

Try it online!

Found the following three matches with a script I wrote:

```<code>Found match: A022844
info: "name": "Floor(n*Pi).",

Found match: A073934
info: "name": "Sum of terms in n-th row of triangle in A073932.",

Found match: A120068
info: "name": "Numbers n such that n-th prime + 1 is squarefree.",
</code>```

I tried to do the first one, which is basically done with YP*k:

```<code>3x2x       # Push 3, delete it, push 2 and delete that too
    YP     # Push pi
      *    # Multiply by implicit input
       k   # Floor function
</code>```

Body:
MATL, 9 bytes, beaker, A022844

Code (with a whitespace at the end):

3x2xYP*k

Try it online!

Found the following three matches with a script I wrote:

Found match: A022844
info: "name": "Floor(n*Pi).",

Found match: A073934
info: "name": "Sum of terms in n-th row of triangle in A073932.",

Found match: A120068
info: "name": "Numbers n such that n-th prime + 1 is squarefree.",

I tried to do the first one, which is basically done with YP*k:

3x2x       # Push 3, delete it, push 2 and delete that too
    YP     # Push pi
      *    # Multiply by implicit input
       k   # Floor function


答:
Python, 537

My initial solution:

```<code>from itertools import chain, product, ifilter
from operator import add
moves = ((1,0),(0,1),(-1,0),(0,-1))
h = dict(ifilter(lambda (p,v):not v.isspace(),chain(*map(lambda (i,r):map(lambda (j,c):((i,j),c),enumerate(r)),enumerate(s)))))
n = defaultdict(list)
for m,p in product(moves, h):
    np = tuple(map(add,m,p))
    if np in h:
        n[p].append(np)
def pr(nx):
    return(lambda l:(h[l[0]], h.pop(l[0]))[0] + pr(l[0]) if l else '')([x for x in n[nx] if x in h])
(lambda y: h[y]+ pr(y))(next(x for x in n if len(n[x])==1))
</code>```

Compacted a bit, but left it as a method:

```<code>from itertools import chain, product
from operator import add
def unsnake(s):
    (h,n) = (dict(filter(lambda (p,v):not v.isspace(),chain(*map(lambda (i,r):map(lambda (j,c):((i,j),c),enumerate(r)),enumerate(s))))),defaultdict(list))
    for m,p in product(((1,0),(0,1),(-1,0),(0,-1)), h):(lambda np: n[p].append(np) if np in h else 0)(tuple(map(add,m,p)))
    def pr(nx):return(lambda l:(h[l[0]], h.pop(l[0]))[0] + pr(l[0]) if l else '')([x for x in n[nx] if x in h])
    return(lambda y: h[y]+ pr(y))(next(x for x in n if len(n[x])==1))
</code>```

Title: De-Snakify a String

Body:
A regular string looks like this:

```<code>Hello,IAmAStringSnake!
</code>```

And a string snake looks something like this:

```<code>Hel
  l      rin
  o,IAmASt g
           S
       !ekan
</code>```

Your Task

String snakes are dangerous, so you must make a program that takes a string snake as input and outputs it as a regular string.

Specifications

Input can be a multiline string or an array of strings.

Each line of the input will be padded with spaces to form a rectangular grid.

Characters in the snake can only connect to adjacent characters above, below, left or right of them (just like in the game Snake). They cannot go diagonal.

The snake characters will never be adjacent to another part of the snake, only the connected characters.

The first character of the string is the end character with the shortest Manhattan distance from the top-left corner of the input grid (i.e. the minimum number of moves it would take for a snake to go directly from the end character to the top-left corner). Both ends will never have the same distance.

The string can contain any ASCII character between code points 33 and 126 inclusive (no spaces or newlines).

The string will be between 2 and 100 characters long.

Shortest code in bytes wins.

Test Cases

(Input grid, followed by the output string)

```<code>Hel
  l      rin
  o,IAmASt g
           S
       !ekan

Hello,IAmAStringSnake!

----------

Python

Python

----------

P  ngPu  Code
r  i  z  d  G
o  m  z  n  o
gram  lesA  lf

ProgrammingPuzzlesAndCodeGolf

----------

   ~ zyx tsr XWVUTSR
   }|{ wvu q Y     Q
!          p Z `ab P
"#$ 6789:; o [ _ c O
  % 5    < n \]^ d N
('& 432  = m     e M
)     1  > lkjihgf L
*+,-./0  ?         K
         @ABCDEFGHIJ

!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~

----------

  tSyrep
  r    p
  in Sli
   g    Sile
   Snakes  n
Ser      ylt
a eh   ilS
fe w   t
   emo h
     Sre

SlipperyStringSnakesSilentlySlitherSomewhereSafe
</code>```

Body:
Python, 537

My initial solution:

from itertools import chain, product, ifilter
from operator import add
moves = ((1,0),(0,1),(-1,0),(0,-1))
h = dict(ifilter(lambda (p,v):not v.isspace(),chain(*map(lambda (i,r):map(lambda (j,c):((i,j),c),enumerate(r)),enumerate(s)))))
n = defaultdict(list)
for m,p in product(moves, h):
    np = tuple(map(add,m,p))
    if np in h:
        n[p].append(np)
def pr(nx):
    return(lambda l:(h[l[0]], h.pop(l[0]))[0] + pr(l[0]) if l else '')([x for x in n[nx] if x in h])
(lambda y: h[y]+ pr(y))(next(x for x in n if len(n[x])==1))

Compacted a bit, but left it as a method:

from itertools import chain, product
from operator import add
def unsnake(s):
    (h,n) = (dict(filter(lambda (p,v):not v.isspace(),chain(*map(lambda (i,r):map(lambda (j,c):((i,j),c),enumerate(r)),enumerate(s))))),defaultdict(list))
    for m,p in product(((1,0),(0,1),(-1,0),(0,-1)), h):(lambda np: n[p].append(np) if np in h else 0)(tuple(map(add,m,p)))
    def pr(nx):return(lambda l:(h[l[0]], h.pop(l[0]))[0] + pr(l[0]) if l else '')([x for x in n[nx] if x in h])
    return(lambda y: h[y]+ pr(y))(next(x for x in n if len(n[x])==1))


答:
JavaScript (ES6), 133

s=>s.replace(/[^aeiou ]*(.?)/gi,(z,x,c)=>(q=o[r]||'',o[r]=q+=' '.repeat(c-q.length)+z,x<'!'?++r:r?--r:o=[,...o]),o=[],r=0)&&o.join`
`
```

<p><em>Less golfed</em></p>

<pre class="lang-js prettyprint-override"><code>s=>(
  s.replace(/[^aeiou ]*(.?)/gi,(z,x,c)=>(
    q = o[r] || '',
    o[r] = q += ' '.repeat(c - q.length) + z,
    x == ' ' ? ++r : r ? --r : o = [,...o]
  ), o = [], r = 0),
  o.join`\n`
)
</code>```

Test

f=s=>s.replace(/[^aeiou ]*(.?)/gi,(z,x,c)=>(q=o[r]||'',o[r]=q+=' '.repeat(c-q.length)+z,x<'!'?++r:r?--r:o=[,...o]),o=[],r=0)&&o.join`
`

function test() {
  i=I.value
  O.textContent=f(i)
}

test()```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#I { width:90%}</code>```

<input id=I oninput='test()' value='Programming Puzzles And Code-Golf'>

```

Title: "Stair-ify" a string

Body:
You must write a program or function that creates a "stair-ified" string. Here is how you "stair-ify" a string:

For each character in the string:

If the character is an upper or lowercase vowel, not including 'y', output it then move the rest of the string up a column.

If the character is a space or a tab, output it then move the rest of the string down a colum.

If the character is neither, output it normally.

IO can be in any reasonable format. The input will not contain any newlines. If you want, you can remove any trailing whitespace.

If you choose to return the string, rather than printing it, please also include a short program that will print your string so that it can be visualized. This is not mandatory, nor will it go towards your byte-count. This is just a convenience for users who don't understand golf or esolangs (like me) to be able to verify output or tinker with the code.

Sample IO:

Output for "bcdef ghijkl":

```<code>    f    jkl
bcde  ghi
</code>```

Output for "Programming Puzzles And Code-Golf":

```<code>                               lf
                            -Go
                  s  nd   de
         ng   zzle  A   Co
      mmi   Pu
   gra
Pro
</code>```

Output for "Abcdefghijklmnopqrstuvwxyz":

```<code>                     vwxyz
               pqrstu
         jklmno
     fghi
 bcde
A
</code>```

As usual, this is code-golf, so shortest answer in bytes wins.

Body:
JavaScript (ES6), 133

s=>s.replace(/[^aeiou ]*(.?)/gi,(z,x,c)=>(q=o[r]||'',o[r]=q+=' '.repeat(c-q.length)+z,x<'!'?++r:r?--r:o=[,...o]),o=[],r=0)&&o.join`
`

Less golfed

s=>(
  s.replace(/[^aeiou ]*(.?)/gi,(z,x,c)=>(
    q = o[r] || '',
    o[r] = q += ' '.repeat(c - q.length) + z,
    x == ' ' ? ++r : r ? --r : o = [,...o]
  ), o = [], r = 0),
  o.join`\n`
)

Test

f=s=>s.replace(/[^aeiou ]*(.?)/gi,(z,x,c)=>(q=o[r]||'',o[r]=q+=' '.repeat(c-q.length)+z,x<'!'?++r:r?--r:o=[,...o]),o=[],r=0)&&o.join`
`

function test() {
  i=I.value
  O.textContent=f(i)
}

test()

#I { width:90%}

<input id=I oninput='test()' value='Programming Puzzles And Code-Golf'>
<pre id=O>


答:
Java, 479 bytes, Daniel M., A000073

Code:

```<code>import java.util.*;
public class A{

    public static int i=0;
    public boolean b;

    static A a = new A();

    public static void main(String[] args){
        int input = Integer.parseInt(args[0]);

        LinkedList<Integer> l = new LinkedList<>();
        l.add(1);
        l.add(0);
        l.add(0);

        for(int ix = 0; ix<=input; ix++)if(ix>2){
            l.add(0,l//d
            .get(1)+l.peekFirst()+     l.get(2));
        }

        System.out.println(input<2?0:l.pop()
              +(A.i        +(/*( 5*/ 0 )));
    }
}
</code>```

If you miss non-revealed characters, they are replaced with spaces.

Body:
This is the robbers' thread. The cops' thread goes here.

In the cops thread, the task was to write a program/function that takes a positive (or non-negative) integer and outputs/returns another number (not necessarily integer). The robbers task is to unscramble the code the cops used to produce this output.

The cracked code doesn't have to be identical, as long as it has the same length and any revealed characters are in the correct positions. The language must also be the same (version numbers can be different). The output must of course be identical.

No-ops can be used in robber's solution.

The winner of the robbers thread will be the user who has cracked the
most submissions by May 7th 2016. If there's a tie, the user who has cracked submissions with the longest combined code will win.

The submission should be formatted like this:

Language, nn characters (including link to answer), Cop's username

Code:

```<code>function a(n)
    if n<2 then
        return n
    else
        return a(n-1) + a(n-2)
    end
end
</code>```

Output

```<code>a(0) returns 0
a(3) returns 2
</code>```

Optional explanation and comments.

Body:
Java, 479 bytes, Daniel M., A000073

Code:

import java.util.*;
public class A{

    public static int i=0;
    public boolean b;

    static A a = new A();

    public static void main(String[] args){
        int input = Integer.parseInt(args[0]);

        LinkedList<Integer> l = new LinkedList<>();
        l.add(1);
        l.add(0);
        l.add(0);

        for(int ix = 0; ix<=input; ix++)if(ix>2){
            l.add(0,l//d
            .get(1)+l.peekFirst()+     l.get(2));
        }

        System.out.println(input<2?0:l.pop()
              +(A.i        +(/*( 5*/ 0 )));
    }
}

If you miss non-revealed characters, they are replaced with spaces.


答:
Ruby 2.2.4 + HTTParty: 129 bytes

Anonymous function; returns a string with the strawpoll URL. Remember to install the HTTParty gem before running.

```<code>->q,a{require'httparty';s="http%s://strawpoll.me/%s"
s%[p,HTTParty.post(s%[?s,"api/v2/polls"],body:{title:q,options:a},verify:p)["id"]]}
</code>```

If the URL can be returned with https:// instead of http://, 126 bytes:

```<code>->q,a{require'httparty';s="https://strawpoll.me/%s"
s%HTTParty.post(s%"api/v2/polls",body:{title:q,options:a},verify:p)["id"]}
</code>```

Title: Make a Strawpoll

Body:
Moderator note: https://strawpoll.me has officially shut down, and the linked API no longer appears to work or provide data. Therefore, new answers cannot actually do the task and so the challenge has been closed to prevent any new answers.

Strawpolls are great, and we use them in chat all the time for getting opinions on things. But they're kinda annoying to make since you need a webbrowser to make them, and everyone knows that I access PPCG only through SE APIs and curl. So I want you to write some code that uses Strawpoll's API to make a strawpoll with the given options.

Specs

Take as input a list in any reasonable format of options as strings, and a title which is also a string. Then use the API to make a strawpoll with that title and those options and output the url.

Multiples should not be allowed, duplicate checking should be enforced, and captchas should not be necessary.

Example

```<code>"My Awesome Poll"
["option 1", "I like pies", "I also like cakes"]
</code>```

Output: http://strawpoll.me/7275997

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

Body:
Ruby 2.2.4 + HTTParty: 129 bytes

Anonymous function; returns a string with the strawpoll URL. Remember to install the HTTParty gem before running.

->q,a{require'httparty';s="http%s://strawpoll.me/%s"
s%[p,HTTParty.post(s%[?s,"api/v2/polls"],body:{title:q,options:a},verify:p)["id"]]}

If the URL can be returned with https:// instead of http://, 126 bytes:

->q,a{require'httparty';s="https://strawpoll.me/%s"
s%HTTParty.post(s%"api/v2/polls",body:{title:q,options:a},verify:p)["id"]}


答:
Jolf, 16 bytes, safe!

Outputs:

```<code>a(0) = 0
a(4) = -2
a(51) = 26
</code>```

Code:

```<code>#.‘###4#x##32#mA
</code>```

Revealed:

 ```<code>Sequence: A001057, the canonical enumeration of integers.<br>*.‘01m4zx’m32xmA<br>  ‘      ’        an array<br>   0               0: 0<br>    1              1: 1<br>     m4zx          antisum of range 1..x (1 - 2 - 3 - 4 - ... - x)<br> .        m32x    get min(2, x) of that array<br>*             mA  multiply that entry by the sign of x (implicit input); is zero when zero</code>```

Body:
This is the cops' thread. The robbers' thread goes here.

The last cops-and-robbers thread was already 4 months ago.

The cop's task

The cop's task is to write a program/function that takes a positive (or non-negative) integer and outputs/returns another integer.

The cop must state it if the program is intolerant towards zero.

The cop will provide at least 2 sample inputs/outputs.

For example, if I have decided to write the Fibonacci sequence, I would write this in my answer:

```
a(0) returns 0
a(3) returns 2
```

The number of examples is up to the cop's discretion.

However, the sequence must actually exist in the On-Line Encyclopedia of Integer Sequences®, so no pseudo-random number generator for you. :(

The cop can hide as many characters as is so wished.

For example, if my program is:

```<code>function a(n)
    if n>2 then
        return n
    else
        return a(n-1) + a(n-2)
    end
end
</code>```

Then I would hide these characters as I want:

```<code>function a(n)
    if ### then
        ########
    else
        ######################
    end
end
</code>```

The robber's task

is obviously to find the original source code.

However, any proposed source code that produces the same set of output also counts as valid, as long as it is also found in OEIS.

Tips for the cops

<s>The search function in the OEIS only works for consecutive terms, so if you want to hide your sequence, then just leave a hole anywhere.</s>

Apparently there is no way to hide the sequence. Put this in mind when you choose the sequence.

Your score is the number of bytes in your code.

The winner will be the submission with the lowest score that hasn't been cracked in 7 days.

Only submissions that are posted in 2016 April are eligible for the win. Submissions that are posted later than this are welcome, but cannot win.

In order to claim the win you need to reveal the full code and the OEIS sequence (after 7 days).

Your post should be formatted like this (NN is the number of characters):

Lua, 98 bytes

Output:

```<code>a(0) returns 0
a(3) returns 2
</code>```

Code (# marks unrevealed characters):

```<code>function a(n)
    if ### then
        ########
    else
        ######################
    end
end
</code>```

If the code is cracked, insert [Cracked](link to cracker) in the header.
If the submission is safe, insert "Safe" in the header and reveal the full code in your answer. Only answers that have revealed the full code will be eligible for the win.

Body:
Jolf, 16 bytes, safe!

Outputs:

a(0) = 0
a(4) = -2
a(51) = 26

Code:

#.‘###4#x##32#mA

Revealed:

Sequence: A001057, the canonical enumeration of integers.
*.‘01m4zx’m32xmA
  ‘      ’        an array
   0               0: 0
    1              1: 1
     m4zx          antisum of range 1..x (1 - 2 - 3 - 4 - ... - x)
 .        m32x    get min(2, x) of that array
*             mA  multiply that entry by the sign of x (implicit input); is zero when zero


问:
Find the first word starting with each letter
Given a string, find the first word starting with each letter (case insensitive).

Sample

Using Ferulas flourish in gorgeous gardens. as input:

```<code>"Ferulas flourish in gorgeous gardens."
 ^^^^^^^          ^^ ^^^^^^^^
 |                |  |
 |                |  --> is the first word starting with `g`
 |                --> is the first word starting with `i`
 --> is the first word starting with `f`
</code>```

Then, the output for this sample should be the matched words joined by one single space:

```<code>"Ferulas in gorgeous"
</code>```

Challenge

Both input and output must be a string representation, or the closest alternative in your language.

Program or function allowed.

You can consider a word being at least one of: lowercase or uppercase letters, digits, underscore.

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

Another samples:

```<code>input: "Take all first words for each letter... this is a test"
output: "Take all first words each letter is"
</code>```

```<code>input: "Look ^_^ .... There are 3 little dogs :)"
output: "Look _ There are 3 dogs"
</code>```

```<code>input: "...maybe some day 1 plus 2 plus 20 could result in 3"
output: "maybe some day 1 plus 2 could result in 3"
</code>```

答:
grep and awk, 68 56 bytes

The script:

```<code>echo `grep -o '\w*'|awk '!x[tolower(substr($0,1,1))]++'`
</code>```

Explanation:

grep -o matches the legal words, printing each on its own line.

awk takes the first letter of each line with substr, makes it lowercase, and then increments a hashtable entry with that key.  If the value was unset before the increment, the line is printed.

echo ... turns the lines back into words

I previously tried to create a solution without awk, using uniq, sort, grep and bash but fell just short.  History in the edits.

Thanks to Dennis for some improvements I missed.

Body:
grep and awk, 68 56 bytes

The script:

echo `grep -o '\w*'|awk '!x[tolower(substr($0,1,1))]++'`

Explanation:

grep -o matches the legal words, printing each on its own line.

awk takes the first letter of each line with substr, makes it lowercase, and then increments a hashtable entry with that key.  If the value was unset before the increment, the line is printed.

echo ... turns the lines back into words

I previously tried to create a solution without awk, using uniq, sort, grep and bash but fell just short.  History in the edits.

Thanks to Dennis for some improvements I missed.


问:
1/N probability
Because there are not enough simple code-golf challenges:

Create an optionally unnamed program or function that, given (by any means) an integer 1 ≤ N ≤ 10000, outputs your language's True value with a pseudo-random probability of 1/N, False otherwise.

Please note that the requirement for naming has been removed. Feel free to edit answers and scores accordingly.

Some languages use 1 (or -1) and 0 for True and False, that is fine too.

Example:

Example input tests:

```<code>4 -> True
4 -> False
4 -> False
4 -> False
4 -> False
4 -> True
4 -> False
4 -> False
</code>```

I.e. given 4; it returns True with a 25% chance and False with a 75% chance.

答:
Fuzzy Octo Guacamole, 10 bytes

```<code>^-!_[0]1.|
</code>```

Explanation:

```<code>^-!_[0]1.|

^          # Get input.
 -         # Decrement, so we can append <ToS> zeros and a 1 to the stack.
  !        # Set loop counter.
   _       # Pop, since we are done with the input.
    [      # Start loop
     0     # Push 0
      ]    # End for loop. We have pushed input-1 0s to the stack.
       1   # Push a single 1 to the stack.
        .  # Switch stacks
         | # Pick a random item from the inactive stack, which has n-1 falsy items and 1 truthy item, so the truthy probability is 1/n.
           # (implicit output)
</code>```

Title: 1/N probability

Body:
Fuzzy Octo Guacamole, 10 bytes

^-!_[0]1.|

Explanation:

^-!_[0]1.|

^          # Get input.
 -         # Decrement, so we can append <ToS> zeros and a 1 to the stack.
  !        # Set loop counter.
   _       # Pop, since we are done with the input.
    [      # Start loop
     0     # Push 0
      ]    # End for loop. We have pushed input-1 0s to the stack.
       1   # Push a single 1 to the stack.
        .  # Switch stacks
         | # Pick a random item from the inactive stack, which has n-1 falsy items and 1 truthy item, so the truthy probability is 1/n.
           # (implicit output)