答:
Perl, 92 + 4 (-sn flags) = 96 bytes

$h{$_}++}{$v=$h{$_},print$c?"$v $_":($D||$d)&&$v>1||$u&&$v<2?$_ x($d?1:$v):''for sort keys%h
```

<p>This code needs to be in a file to run. And it needs <code>-sn</code> flags, as well as <code>-M5.010</code> (free).<br>
For instance :  </p>

```$ cat input.txt
hello world
apple pie
zebra
dog
hello world
apple pie
apple pie
apple pie
$ cat prog.pl
$h{$_}++}{$v=$h{$_},print$c?"$v $_":($D||$d)&&$v>1||$u&&$v<2?$_ x($d?1:$v):''for sort keys%h
$ perl -M5.010 -sn prog.pl -c < input.txt
4 apple pie
1 dog
2 hello world
1 zebra
```

Title: UNIX Uniq Uknow?

Body:
Challenge

You must write a program which takes a string and a flag as input and performs one of the following functions.

Input

If your language does not support command line arguments, you may take the arguments as input via STDIN.

The flag will be two characters: a dash and an ASCII character such as -d or -c.

Functions

The following is the list of functions which you must implement in your program. The title of each is the flag which corresponds to the function.

Counting: -c

This counts the number of duplicate lines in the input file. For example, if the input is:

```<code>aa
aa
bb
bb
bb
xx
</code>```

The output will be:

```<code>2 aa
3 bb
1 xx
</code>```

Because there are two lines of aa, three lines of bb, and one line of xx. The output should be separated by newlines.

Duplication: -d

This shows which lines are duplicates. For example, using the above example string (aa\naa\nbb\nbb\nbb\nxx), the output would be:

```<code>aa
bb
</code>```

Because these are lines which have been duplicated. You should only output each line once.

Duplication: -D

This is almost the same as -d except it outputs each line the number of times that it occurs in the input file. For example, using the example string the output will be:

```<code>aa
aa
bb
bb
bb
</code>```

Because aa occurs twice and bb occurs three times.

Unique: -u

Similar to above except it only prints unique lines. For example, using the example file, the output will be:

```<code>xx
</code>```

Because xx is the only unique line. Also, due to xx being unique, you will only ever have to output this once.

Example

Note that although the input string will not always be sorted, the output must be sorted alphabetically. For example, for the following input:

```<code>hello world
apple pie
zebra
dog
hello world
apple pie
apple pie
apple pie
</code>```

The output for each of the flags would be:

-c

```<code>4 apple pie
1 dog
2 hello world
1 zebra
</code>```

-d

```<code>apple pie
hello world
</code>```

-D

```<code>apple pie
apple pie
apple pie
apple pie
hello world
hello world
</code>```

-u

```<code>dog
zebra
</code>```

Rules

Your programs must not use the UNIX program uniq as, frankly, that is plain cheating.

All output should be to STDOUT.

The file will only ever contain lowercase, alphabetical characters, newlines and spaces:

```<code>2 aa
3 bb
1 xx
</code>```0

The output should be sorted alphabetically.

In case there is any confusion, programs written on any operating system can enter. The challenge is not limited to UNIX.

As per PPCG standard, functions and anonymous functions are allowed, taking input via their arguments and outputting via a returned string.

Winning

As this is code-golf, the shortest code in bytes wins.

Body:
Perl, 92 + 4 (-sn flags) = 96 bytes

$h{$_}++}{$v=$h{$_},print$c?"$v $_":($D||$d)&&$v>1||$u&&$v<2?$_ x($d?1:$v):''for sort keys%h

This code needs to be in a file to run. And it needs -sn flags, as well as -M5.010 (free).

For instance :

$ cat input.txt
hello world
apple pie
zebra
dog
hello world
apple pie
apple pie
apple pie
$ cat prog.pl
$h{$_}++}{$v=$h{$_},print$c?"$v $_":($D||$d)&&$v>1||$u&&$v<2?$_ x($d?1:$v):''for sort keys%h
$ perl -M5.010 -sn prog.pl -c < input.txt
4 apple pie
1 dog
2 hello world
1 zebra


问:
Slowly turn a string into another

The Challenge

Given two strings/an array of strings, output the first string slowly shrinking and expanding back into the second string.

You can assume the strings will always start with the same character.

Example

```<code>Input:
"Test", "Testing"

Output:
Test
Tes
Te
T
Te
Tes
Test
Testi
Testin
Testing
</code>```

First you output the first word:

```<code>Test
</code>```

Then you keep removing one letter until the string is one character long:

```<code>Tes
Te
T
</code>```

Then keep adding one letter of the second word until it's done:

```<code>Te
Tes
Test
Testi
Testin
Testing
</code>```

(if both strings are one character long, then just output one of them once.)

Test Cases

```<code>"Hello!", "Hi."
Hello!
Hello
Hell
Hel
He
H
Hi
Hi.

"O", "O"

O

"z", "zz"

z
zz

".vimrc", ".minecraft"

.vimrc
.vimr
.vim
.vi
.v
.
.m
.mi
.min
.mine
.minec
.minecr
.minecra
.minecraf
.minecraft

"     ", "   "

SSSSS
SSSS
SSS
SS
S
SS
SSS

"0123456789", "02468"

0123456789
012345678
01234567
0123456
012345
01234
0123
012
01
0
02
024
0246
02468
</code>```

(note: on the space/fourth test case, replace the S with spaces)

Rules

This is code-golf, so shortest answer in bytes wins! Tiebreaker is most upvoted post. Winner will be chosen on 09/10/2016.

Standard loopholes are forbidden.

答:
(Lambdabot) Haskell - 41 bytes

```<code>f=(.drop 2.inits).(++).reverse.tail.inits
</code>```

More readable, but two bytes longer:

```<code>a!b=(reverse.tail$inits a)++drop 2(inits b)
</code>```

Output:

```<code>f "Hello" "Hi!"
["Hello","Hell","Hel","He","H","Hi","Hi!"]
</code>```

ContentLicense: CC BY-SA 3.0

Title: Slowly turn a string into another

Body:
(Lambdabot) Haskell - 41 bytes

f=(.drop 2.inits).(++).reverse.tail.inits

More readable, but two bytes longer:

a!b=(reverse.tail$inits a)++drop 2(inits b)

Output:

f "Hello" "Hi!"
["Hello","Hell","Hel","He","H","Hi","Hi!"]


问:
Convert to Bibi-binary
Bibi-binary is a numeric system invented by Boby Lapointe in order to represent numbers in letters which pronunciation seems funny.

Your task is to convert decimal numbers into Bibi-binary!

Conversion

A number is converted to base 16 (hexadecimal) and each character is replaced by its Bibi-binary name:

```<code>0 = HO
1 = HA
2 = HE
3 = HI
4 = BO
5 = BA
6 = BE
7 = BI
8 = KO
9 = KA
A = KE
B = KI
C = DO
D = DA
E = DE
F = DI
</code>```

Let N be a positive integer (between 1 -> 2^31-1).
For every character in the hexadecimal representation of N, replace the character by its according Bibi-binary pair (the table above contains all the pairs).

Example

N = 156

H = (hexadecimal representation of N) --> 9C

9 --> KA, C --> DO

Thus the output is KADO.

Input & output

You will receive an positive 32-bit integer N, which you will have to turn into Bibi-binary.

You may (return, print, etc...) in any convenient format, but the pairs have to be connected! So KA DO wouldn't be okay, but KADO would.

Both, lowercase and uppercase are allowed.

Rules

No loopholes.

This is code-golf, so the shortest code wins.

Testcases

```<code>2048 -> KOHOHO
156 -> KADO
10000 -> HEBIHAHO
12 -> DO
</code>```

答:
Dyalog APL, 19 bytes

Requires ⎕IO←0 which is default on many systems.

∊(,'HBKD'∘.,'OAEI')[16⊥⍣¯1⊢⎕]
```

∊ enlist (make completely flat)

(...

 , the raveled

 'HBKD'∘.,'OAEI' concatenation table (i.e. all combos)

)[ indexed by...

 16⊥⍣¯1 the inverse of base-16 to base 10 (i.e. base-10 to base 16) representation

 ⊢ of

 ⎕ the numeric input

]

TryAPL online!

Title: Convert to Bibi-binary

Body:
Dyalog APL, 19 bytes

Requires ⎕IO←0 which is default on many systems.

∊(,'HBKD'∘.,'OAEI')[16⊥⍣¯1⊢⎕]

∊ enlist (make completely flat)

(...

 , the raveled

 'HBKD'∘.,'OAEI' concatenation table (i.e. all combos)

)[ indexed by...

 16⊥⍣¯1 the inverse of base-16 to base 10 (i.e. base-10 to base 16) representation

 ⊢ of

 ⎕ the numeric input

]

TryAPL online!


问:
HexaGolf: Wordagons
See also: Rotatagons

Challenge

Given a string as input, output its wordagon.

Wordagons

A wordagon is a way of representing a string in a hexagon. Now, let's create a wordagon from the string hexa:

Firstly, you start with the first character in the string a place it in the centre:

```<code>h
</code>```

Then, you take the next character in the string and add a hexagonal layer:

```<code> e e
e h e
 e e
</code>```

Then, add the next layer:

```<code>  x x x
 x e e x
x e h e x
 x e e x
  x x x
</code>```

Finally, add the last layer:

```<code>   a a a a
  a x x x a
 a x e e x a
a x e h e x a
 a x e e x a
  a x x x a
   a a a a
</code>```

And you now have the wordagon for the string hexa.

Examples

Here's some I prepared earlier:

hello

```<code>    o o o o o
   o l l l l o
  o l l l l l o
 o l l e e l l o
o l l e h e l l o
 o l l e e l l o
  o l l l l l o
   o l l l l o
    o o o o o
</code>```

PPcg

```<code>   g g g g
  g c c c g
 g c P P c g
g c P P P c g
 g c P P c g
  g c c c g
   g g g g
</code>```

o *

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

(T_T)

```<code>    ) ) ) ) )
   ) T T T T )
  ) T _ _ _ T )
 ) T _ T T _ T )
) T _ T ( T _ T )
 ) T _ T T _ T )
  ) T _ _ _ T )
   ) T T T T )
    ) ) ) ) )
</code>```

Note that trailing and/or leading newlines are allowed.

Winning

The shortest code in bytes wins.

答:
Vim, 92 bytes

```<code>:se ri|s/./ &/g
ⓋCⓇ"Ⓓ␛$vpmlmrqqYpi ␛`ljxxhmlylv`rjlmr:s/\%V\(.\)./Ⓡ" /g
@qq@qVdy2G:g/^/m0
Gp
</code>```

Circled letters represent Control + letter; ␛ is escape.

Title: HexaGolf: Wordagons

Body:
Vim, 92 bytes

:se ri|s/./ &/g
ⓋCⓇ"Ⓓ␛$vpmlmrqqYpi ␛`ljxxhmlylv`rjlmr:s/\%V\(.\)./Ⓡ" /g
@qq@qVdy2G:g/^/m0
Gp

Circled letters represent Control + letter; ␛ is escape.


问:
Tips for golfing in Haskell
What general tips do you have for golfing in Haskell? I am looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to Haskell. Please post only one tip per answer.

If you are new to golfing in Haskell, please have a look at the Guide to Golfing Rules in Haskell. There is also a dedicated Haskell chat room: Of Monads and Men.

答:
Lambdabot Haskell

A language is defined by its implementation, and lambdabot (the IRC bot over at #haskell) imports a ton of common modules by default. No need to spend precious bytes re-implementing your favorite functions from Data.List or Control.Monad, just write Haskell (Lambdabot) instead of Haskell in the title and you're good to go!

Edit:

Here's a list of stuff that it imports by default, which includes, among other things, Control.Arrow, Data.Bits, Data.Ratio, System.Random and {-# LANGUAGE ParallelListComp #-} - go wild!

Title: Tips for golfing in Haskell


答:
CJam, 20 bytes

```<code>qiGb"HBKD""OAEI"m*f=
</code>```

Try it online! (As a linefeed-separated test suite.)

Explanation

```<code>qi      e# Read input and convert to integer.
Gb      e# Get hexadecimal digits.
"HBKD"  e# Push this string.
"OAEI"  e# Push this string.
m*      e# Cartesian product, yields ["HO" "HA" "HE" "HI" "BO" ... "DE" "DI"].
f=      e# For each digit, select the corresponding syllable.
</code>```

Title: Convert to Bibi-binary

Body:
Bibi-binary is a numeric system invented by Boby Lapointe in order to represent numbers in letters which pronunciation seems funny.

Your task is to convert decimal numbers into Bibi-binary!

Conversion

A number is converted to base 16 (hexadecimal) and each character is replaced by its Bibi-binary name:

```<code>0 = HO
1 = HA
2 = HE
3 = HI
4 = BO
5 = BA
6 = BE
7 = BI
8 = KO
9 = KA
A = KE
B = KI
C = DO
D = DA
E = DE
F = DI
</code>```

Let N be a positive integer (between 1 -> 2^31-1).
For every character in the hexadecimal representation of N, replace the character by its according Bibi-binary pair (the table above contains all the pairs).

Example

N = 156

H = (hexadecimal representation of N) --> 9C

9 --> KA, C --> DO

Thus the output is KADO.

Input & output

You will receive an positive 32-bit integer N, which you will have to turn into Bibi-binary.

You may (return, print, etc...) in any convenient format, but the pairs have to be connected! So KA DO wouldn't be okay, but KADO would.

Both, lowercase and uppercase are allowed.

Rules

No loopholes.

This is code-golf, so the shortest code wins.

Testcases

```<code>2048 -> KOHOHO
156 -> KADO
10000 -> HEBIHAHO
12 -> DO
</code>```

Body:
CJam, 20 bytes

qiGb"HBKD""OAEI"m*f=

Try it online! (As a linefeed-separated test suite.)

Explanation

qi      e# Read input and convert to integer.
Gb      e# Get hexadecimal digits.
"HBKD"  e# Push this string.
"OAEI"  e# Push this string.
m*      e# Cartesian product, yields ["HO" "HA" "HE" "HI" "BO" ... "DE" "DI"].
f=      e# For each digit, select the corresponding syllable.


问:
The Letter E with E
Your task is to display the below letter "E" shaped ASCII art, given five inputs.

Examples:

Input: 7,2,+,|,- (Note: You don't have to follow this exact input format, and if you don't use it, then you must explain how your own input format works)

Explanation:

7 total width, including the left and right edge characters.

2 Number of vertical characters.

+ The character that should display at the edges.

| The character that should display vertically between the edges.

- The character that should display horizontally.

Output of the above example:

```<code>+-----+
|
|
+-----+
|
|
+-----+
</code>```

Other examples:

Input: 7,2,@,|,-

Output:

```<code>@-----@
|
|
@-----@
|
|
@-----@
</code>```

Input: 7,2,+,|,#

Output:

```<code>+#####+
|
|
+#####+
|
|
+#####+
</code>```

Input: 8,3,+,|,#

Output:

```<code>+######+
|
|
|
+######+
|
|
|
+######+
</code>```

Input: 8,3,+,@,#

Output:

```<code>+######+
@
@
@
+######+
@
@
@
+######+
</code>```

Input: 9,4,^,$,!

Output:

```<code>^!!!!!!!^
$
$
$
$
^!!!!!!!^
$
$
$
$
^!!!!!!!^
</code>```

Cheating and standard loopholes are not allowed.

Your code must not print anything to STDERR.

Your code may accept any character encoding you choose as the input, but any character encoding you choose must, as a minimum, support all the 95 printable ASCII characters.

The shortest code, in bytes, that completes this challenge successfully, is the winning code.

Leaderboard

var QUESTION_ID=92138,OVERRIDE_USER=58717;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

```

答:
Dyalog APL, <s>31</s> 29 bytes

Prompts for horizontal-character, width, junction-character, height, vertical-character – in that order.

h↓⊃⍪/3/⊂↑(⍞⍴⍨h←⎕),⊂⍞{∊⍺⍵⍺}⎕⍴⍞
```
<p><code>⎕⍴⍞</code> input-horizontal-character and repeat input-width times (<strong>⍵</strong> below)</p>
<p><code>⍞{</code>...<code>}</code> input-junction-character which will be <strong>⍺</strong> in the function...</p>
<p> <code>∊⍺⍵⍺</code> flatten [[junction],[horizontals],[junction]]</p>
<p><code>⊂</code> encapsulate so it can be part of a list</p>
<p><code>(</code>...<code>),</code> prepend...</p>
<p> <code>h←⎕</code> input-height</p>
<p> <code>⍞⍴⍨</code> input-vertical-character and repeat it that many times</p>
<p><code>↑</code> make the list of strings into a character table</p>
<p><code>⊂</code> encapsulate (so it can be repeated as a whole)</p>
<p><code>3/</code> repeat it three times</p>
<pre class="lang-apl prettyprint-override"><code>╻  ╻  ╻
┗━ ┗━ ┗━
</code>```

⍪/ concatenate the three pieces vertically

╻
┣━
┣━
┗━
```
<p>(this encapsulates them too, so we need to...)</p>
<p><code>⊃</code> remove the encapsulation</p>
<p><code>h↓</code> drop the first <strong>h</strong> (rows)</p>
<pre class="lang-apl prettyprint-override"><code>┏━
┣━
┗━
</code>```

TryAPL online!

Title: The Letter E with E

Body:
Dyalog APL, <s>31</s> 29 bytes

Prompts for horizontal-character, width, junction-character, height, vertical-character – in that order.

h↓⊃⍪/3/⊂↑(⍞⍴⍨h←⎕),⊂⍞{∊⍺⍵⍺}⎕⍴⍞

⎕⍴⍞ input-horizontal-character and repeat input-width times (⍵ below)

⍞{...} input-junction-character which will be ⍺ in the function...

 ∊⍺⍵⍺ flatten [[junction],[horizontals],[junction]]

⊂ encapsulate so it can be part of a list

(...), prepend...

 h←⎕ input-height

 ⍞⍴⍨ input-vertical-character and repeat it that many times

↑ make the list of strings into a character table

⊂ encapsulate (so it can be repeated as a whole)

3/ repeat it three times

╻  ╻  ╻
┗━ ┗━ ┗━

⍪/ concatenate the three pieces vertically

╻
┣━
┣━
┗━

(this encapsulates them too, so we need to...)

⊃ remove the encapsulation

h↓ drop the first h (rows)

┏━
┣━
┗━

TryAPL online!


问:
Invalid Invali Inval
This idea is loosely based upon @TùxCräftîñg's chat message.

Take a look at the below example sequence:

INVALID0, INVALID1, INVALID2 INVALID3, INVALID4... INVALID9

After INVALID9, it goes on like this:

INVALI0, INVALI1, INVALI2, INVALI3... INVALI9

And after INVALI9, it's like this:

INVAL0,INVAL1, INVAL2, INVAL3... INVAL9

After, INVAL9, it's like this:

INVA0, INVA1, INVA2, INVA3, ... INVA9

Notice how we we kept removing a letter from the word INVALID each time.

You'll keep repeating this until you reach a single letter, that is, the letter I:

I0, I1, I2, I3, I4 ... I9

Now, your task is, to take an input of a word, and produce a sequence from it like the above example. Your code must also work with single letters, and in that case the resulting sequence will be shorter.

You may choose any input and output format that you prefer (with or without a separator, as you wish), but you must specify which one you have chosen.

The sequence needs to be in the exact specified order.

The shortest code, in bytes, that successfully completes this challenge, wins the challenge.

Full sequence in the above example:

```<code>INVALID0, INVALID1, INVALID2, INVALID3, INVALID4, INVALID5, INVALID6, INVALID7, INVALID8, INVALID9, INVALI0, INVALI1, INVALI2, INVALI3, INVALI4, INVALI5, INVALI6, INVALI7, INVALI8, INVALI9, INVAL0, INVAL1, INVAL2, INVAL3, INVAL4, INVAL5, INVAL6, INVAL7, INVAL8, INVAL9, INVA0, INVA1, INVA2, INVA3, INVA4, INVA5, INVA6, INVA7, INVA8, INVA9, INV0, INV1, INV2, INV3, INV4, INV5, INV6, INV7, INV8, INV9, IN0, IN1, IN2, IN3, IN4, IN5, IN6, IN7, IN8, IN9, I0, I1, I2, I3, I4, I5, I6, I7, I8, I9
</code>```

Other examples:

Input: MAYBE (Uppercase and lowercase don't matter)

Output:

```<code>MAYBE0, MAYBE1, MAYBE2, MAYBE3, MAYBE4, MAYBE5, MAYBE6, MAYBE7, MAYBE8, MAYBE9, MAYB0, MAYB1, MAYB2, MAYB3, MAYB4, MAYB5, MAYB6, MAYB7, MAYB8, MAYB9, MAY0, MAY1, MAY2, MAY3, MAY4, MAY5, MAY6, MAY7, MAY8, MAY9, MA0, MA1, MA2, MA3, MA4, MA5, MA6, MA7, MA8, MA9, M0, M1, M2, M3, M4, M5, M6, M7, M8, M9
</code>```

Input: AFTER

Output:

```<code>AFTER0, AFTER1, AFTER2, AFTER3, AFTER4, AFTER5, AFTER6, AFTER7, AFTER8, AFTER9, AFTE0, AFTE1, AFTE2, AFTE3, AFTE4, AFTE5, AFTE6, AFTE7, AFTE8, AFTE9, AFT0, AFT1, AFT2, AFT3, AFT4, AFT5, AFT6, AFT7, AFT8, AFT9, AF0, AF1, AF2, AF3, AF4, AF5, AF6, AF7, AF8, AF9, A0, A1, A2, A3, A4, A5, A6, A7, A8, A9
</code>```

Input: WHAT ARE YOU DOING

```<code>WHAT ARE YOU DOING0, WHAT ARE YOU DOING1, WHAT ARE YOU DOING2, WHAT ARE YOU DOING3, WHAT ARE YOU DOING4, WHAT ARE YOU DOING5, WHAT ARE YOU DOING6, WHAT ARE YOU DOING7, WHAT ARE YOU DOING8, WHAT ARE YOU DOING9, WHAT ARE YOU DOIN0, WHAT ARE YOU DOIN1, WHAT ARE YOU DOIN2, WHAT ARE YOU DOIN3, WHAT ARE YOU DOIN4, WHAT ARE YOU DOIN5, WHAT ARE YOU DOIN6, WHAT ARE YOU DOIN7, WHAT ARE YOU DOIN8, WHAT ARE YOU DOIN9, WHAT ARE YOU DOI0, WHAT ARE YOU DOI1, WHAT ARE YOU DOI2, WHAT ARE YOU DOI3, WHAT ARE YOU DOI4, WHAT ARE YOU DOI5, WHAT ARE YOU DOI6, WHAT ARE YOU DOI7, WHAT ARE YOU DOI8, WHAT ARE YOU DOI9, WHAT ARE YOU DO0, WHAT ARE YOU DO1, WHAT ARE YOU DO2, WHAT ARE YOU DO3, WHAT ARE YOU DO4, WHAT ARE YOU DO5, WHAT ARE YOU DO6, WHAT ARE YOU DO7, WHAT ARE YOU DO8, WHAT ARE YOU DO9, WHAT ARE YOU D0, WHAT ARE YOU D1, WHAT ARE YOU D2, WHAT ARE YOU D3, WHAT ARE YOU D4, WHAT ARE YOU D5, WHAT ARE YOU D6, WHAT ARE YOU D7, WHAT ARE YOU D8, WHAT ARE YOU D9, WHAT ARE YOU 0, WHAT ARE YOU 1, WHAT ARE YOU 2, WHAT ARE YOU 3, WHAT ARE YOU 4, WHAT ARE YOU 5, WHAT ARE YOU 6, WHAT ARE YOU 7, WHAT ARE YOU 8, WHAT ARE YOU 9, WHAT ARE YOU0, WHAT ARE YOU1, WHAT ARE YOU2, WHAT ARE YOU3, WHAT ARE YOU4, WHAT ARE YOU5, WHAT ARE YOU6, WHAT ARE YOU7, WHAT ARE YOU8, WHAT ARE YOU9, WHAT ARE YO0, WHAT ARE YO1, WHAT ARE YO2, WHAT ARE YO3, WHAT ARE YO4, WHAT ARE YO5, WHAT ARE YO6, WHAT ARE YO7, WHAT ARE YO8, WHAT ARE YO9, WHAT ARE Y0, WHAT ARE Y1, WHAT ARE Y2, WHAT ARE Y3, WHAT ARE Y4, WHAT ARE Y5, WHAT ARE Y6, WHAT ARE Y7, WHAT ARE Y8, WHAT ARE Y9, WHAT ARE 0, WHAT ARE 1, WHAT ARE 2, WHAT ARE 3, WHAT ARE 4, WHAT ARE 5, WHAT ARE 6, WHAT ARE 7, WHAT ARE 8, WHAT ARE 9, WHAT ARE0, WHAT ARE1, WHAT ARE2, WHAT ARE3, WHAT ARE4, WHAT ARE5, WHAT ARE6, WHAT ARE7, WHAT ARE8, WHAT ARE9, WHAT AR0, WHAT AR1, WHAT AR2, WHAT AR3, WHAT AR4, WHAT AR5, WHAT AR6, WHAT AR7, WHAT AR8, WHAT AR9, WHAT A0, WHAT A1, WHAT A2, WHAT A3, WHAT A4, WHAT A5, WHAT A6, WHAT A7, WHAT A8, WHAT A9, WHAT 0, WHAT 1, WHAT 2, WHAT 3, WHAT 4, WHAT 5, WHAT 6, WHAT 7, WHAT 8, WHAT 9, WHAT0, WHAT1, WHAT2, WHAT3, WHAT4, WHAT5, WHAT6, WHAT7, WHAT8, WHAT9, WHA0, WHA1, WHA2, WHA3, WHA4, WHA5, WHA6, WHA7, WHA8, WHA9, WH0, WH1, WH2, WH3, WH4, WH5, WH6, WH7, WH8, WH9, W0, W1, W2, W3, W4, W5, W6, W7, W8, W9
</code>```

Leaderboard

var QUESTION_ID=92156,OVERRIDE_USER=58717;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

```

答:
Dyalog APL, <s>14</s> 11 bytes

Returns list of strings.

,⎕D∘.,⍨⌽,\⍞
```

, listify (make table into list)

⎕D all digits

∘.,⍨ appended to all of (i.e. making all combinations with)

⌽ the reversed list of

,\ the cumulative concatenation of

⍞ the text input

TryAPL online!

Title: Invalid Invali Inval

Body:
Dyalog APL, <s>14</s> 11 bytes

Returns list of strings.

,⎕D∘.,⍨⌽,\⍞

, listify (make table into list)

⎕D all digits

∘.,⍨ appended to all of (i.e. making all combinations with)

⌽ the reversed list of

,\ the cumulative concatenation of

⍞ the text input

TryAPL online!


问:
UNIX Uniq Uknow?

Challenge

You must write a program which takes a string and a flag as input and performs one of the following functions.

Input

If your language does not support command line arguments, you may take the arguments as input via STDIN.

The flag will be two characters: a dash and an ASCII character such as -d or -c.

Functions

The following is the list of functions which you must implement in your program. The title of each is the flag which corresponds to the function.

Counting: -c

This counts the number of duplicate lines in the input file. For example, if the input is:

```<code>aa
aa
bb
bb
bb
xx
</code>```

The output will be:

```<code>2 aa
3 bb
1 xx
</code>```

Because there are two lines of aa, three lines of bb, and one line of xx. The output should be separated by newlines.

Duplication: -d

This shows which lines are duplicates. For example, using the above example string (aa\naa\nbb\nbb\nbb\nxx), the output would be:

```<code>aa
bb
</code>```

Because these are lines which have been duplicated. You should only output each line once.

Duplication: -D

This is almost the same as -d except it outputs each line the number of times that it occurs in the input file. For example, using the example string the output will be:

```<code>aa
aa
bb
bb
bb
</code>```

Because aa occurs twice and bb occurs three times.

Unique: -u

Similar to above except it only prints unique lines. For example, using the example file, the output will be:

```<code>xx
</code>```

Because xx is the only unique line. Also, due to xx being unique, you will only ever have to output this once.

Example

Note that although the input string will not always be sorted, the output must be sorted alphabetically. For example, for the following input:

```<code>hello world
apple pie
zebra
dog
hello world
apple pie
apple pie
apple pie
</code>```

The output for each of the flags would be:

-c

```<code>4 apple pie
1 dog
2 hello world
1 zebra
</code>```

-d

```<code>apple pie
hello world
</code>```

-D

```<code>apple pie
apple pie
apple pie
apple pie
hello world
hello world
</code>```

-u

```<code>dog
zebra
</code>```

Rules

Your programs must not use the UNIX program uniq as, frankly, that is plain cheating.

All output should be to STDOUT.

The file will only ever contain lowercase, alphabetical characters, newlines and spaces:

```<code>2 aa
3 bb
1 xx
</code>```0

The output should be sorted alphabetically.

In case there is any confusion, programs written on any operating system can enter. The challenge is not limited to UNIX.

As per PPCG standard, functions and anonymous functions are allowed, taking input via their arguments and outputting via a returned string.

Winning

As this is code-golf, the shortest code in bytes wins.

答:
R, 179 bytes

```<code>f=function(s,o){s=sort(s);n="\n";z=cat;for(i in unique(s)){v=sum(s%in%i);if(v>1&o=="-d")z(i,n);if(o=="-c")z(v, i,n);if(o=="-D"&v>1)z(rep(c(i,n),v),n,sep="");if(o=="-u"&v<2)z(i,n)}}
</code>```

Input

Input is assumed to be an "R-vector" of strings (inspired by @Arnauld's JS array input, see below) and a string containing the type of function e.g. -d.

Example

An example of how to execute the function where I pre-define the vector of strings (not necessary).

```<code>strings <- c("hello world", "apple pie", "zebra", "dog", "hello world", "apple pie", "apple pie", "apple pie")

f(strings,"-c")
f(strings, "-d")
f(strings,"-D")
f(strings, "-u")
</code>```

Ungolfed

```<code>f=function(s,o){
    s=sort(s)                   # sort vector alphabetically
    n="\n"                      # generate string for newline (used 5x times)
    z=cat                       # generate alias for cat (used 4x times)
    for(i in unique(s)){        # for each unique string of vector
        v=sum(s%in%i)           # count number of occurences
        if(o=="-d"&v>1)z(i,n)   # if occurences >1 & "-d": print each unique string
        if(o=="-D"&v>1)z(rep(c(i,n),v),n,sep="") # repeat string #occurences and then print
        if(o=="-u"&v<2)z(i,n)   # if occurences <2 & "-u": print each uniquely occuring string
        if(o=="-c")z(v,i,n)     # if "-c": print number of occurence and each unique string
   }
}
</code>```

I'm sure this can be golfed further by shortening the control flow statements but couldn't figure out a smart way to do it yet.

Title: UNIX Uniq Uknow?

Body:
R, 179 bytes

f=function(s,o){s=sort(s);n="\n";z=cat;for(i in unique(s)){v=sum(s%in%i);if(v>1&o=="-d")z(i,n);if(o=="-c")z(v, i,n);if(o=="-D"&v>1)z(rep(c(i,n),v),n,sep="");if(o=="-u"&v<2)z(i,n)}}

Input

Input is assumed to be an "R-vector" of strings (inspired by @Arnauld's JS array input, see below) and a string containing the type of function e.g. -d.

Example

An example of how to execute the function where I pre-define the vector of strings (not necessary).

strings <- c("hello world", "apple pie", "zebra", "dog", "hello world", "apple pie", "apple pie", "apple pie")

f(strings,"-c")
f(strings, "-d")
f(strings,"-D")
f(strings, "-u")

Ungolfed

f=function(s,o){
    s=sort(s)                   # sort vector alphabetically
    n="\n"                      # generate string for newline (used 5x times)
    z=cat                       # generate alias for cat (used 4x times)
    for(i in unique(s)){        # for each unique string of vector
        v=sum(s%in%i)           # count number of occurences
        if(o=="-d"&v>1)z(i,n)   # if occurences >1 & "-d": print each unique string
        if(o=="-D"&v>1)z(rep(c(i,n),v),n,sep="") # repeat string #occurences and then print
        if(o=="-u"&v<2)z(i,n)   # if occurences <2 & "-u": print each uniquely occuring string
        if(o=="-c")z(v,i,n)     # if "-c": print number of occurence and each unique string
   }
}

I'm sure this can be golfed further by shortening the control flow statements but couldn't figure out a smart way to do it yet.


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

↑(⌽,\⍞),1↓,\⍞
```

↑ matrify

(⌽,\⍞) reversed (⌽) cumulative concatenation (,\) of character input (⍞)

, prepended to

1↓ one element dropped from

,\⍞ cumulative concatenation of character input

TryAPL online!

Title: Slowly turn a string into another

Body:
The Challenge

Given two strings/an array of strings, output the first string slowly shrinking and expanding back into the second string.

You can assume the strings will always start with the same character.

Example

```<code>Input:
"Test", "Testing"

Output:
Test
Tes
Te
T
Te
Tes
Test
Testi
Testin
Testing
</code>```

First you output the first word:

```<code>Test
</code>```

Then you keep removing one letter until the string is one character long:

```<code>Tes
Te
T
</code>```

Then keep adding one letter of the second word until it's done:

```<code>Te
Tes
Test
Testi
Testin
Testing
</code>```

(if both strings are one character long, then just output one of them once.)

Test Cases

```<code>"Hello!", "Hi."
Hello!
Hello
Hell
Hel
He
H
Hi
Hi.

"O", "O"

O

"z", "zz"

z
zz

".vimrc", ".minecraft"

.vimrc
.vimr
.vim
.vi
.v
.
.m
.mi
.min
.mine
.minec
.minecr
.minecra
.minecraf
.minecraft

"     ", "   "

SSSSS
SSSS
SSS
SS
S
SS
SSS

"0123456789", "02468"

0123456789
012345678
01234567
0123456
012345
01234
0123
012
01
0
02
024
0246
02468
</code>```

(note: on the space/fourth test case, replace the S with spaces)

Rules

This is code-golf, so shortest answer in bytes wins! Tiebreaker is most upvoted post. Winner will be chosen on 09/10/2016.

Standard loopholes are forbidden.

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

↑(⌽,\⍞),1↓,\⍞

↑ matrify

(⌽,\⍞) reversed (⌽) cumulative concatenation (,\) of character input (⍞)

, prepended to

1↓ one element dropped from

,\⍞ cumulative concatenation of character input

TryAPL online!


问:
Rolling three dice and show the probabilities
Roll 3 dice, count the two highest two values and add them to the result. Every 1 must be rolled once again.

Now show the average throw after 1000000 tries and the probabilities for each result occurring:

Desired Result:

avg(9.095855)

  2: 0.0023

  3: 0.0448

  4: 1.1075

  5: 2.8983

  6: 6.116

  7: 10.1234

  8: 15.4687

  9: 18.9496

  10: 19.3575

  11: 16.0886

  12: 9.8433

Body:
Perl (177 169 168)

sub r{1+int rand 6}
for(1..1e6){@l=sort map{($q=r)>1?$q:r}(1..3);++$s{$y=$l[1]+$l[2]};$t+=$y}
print"avg(".$t/1e6.")\n";print"$_: ".$s{$_}/1e4."\n"for sort{$a<=>$b}keys%s

(NOTE: one-liner wrapped for clarity)

stacked output of three consecutive runs:

avg(9.09432)  avg(9.094793)  avg(9.092179)
2: 0.002      2: 0.0026      2: 0.0023
3: 0.0448     3: 0.0454      3: 0.0436
4: 1.0872     4: 1.0904      4: 1.0944
5: 2.8834     5: 2.8933      5: 2.8842
6: 6.1387     6: 6.127       6: 6.1854
7: 10.1648    7: 10.177      7: 10.1669
8: 15.498     8: 15.5758     8: 15.508
9: 18.9483    9: 18.8391     9: 18.9236
10: 19.3557   10: 19.278     10: 19.3234
11: 16.0589   11: 16.0863    11: 16.0256
12: 9.8182    12: 9.8851     12: 9.8426

UPDATES

shortening 1: eliminate $n=1e6 (insp. by Joe)

shortening 2: del space in keys %s


问:
Double rotation

Challenge Description

Cycle all letters from the first part of the alphabet in one direction, and letters from the second half of the alphabet in the other. Other characters stay in place.

Examples

1: Hello world

```<code>Hello_world //Input
Hell     ld //Letters from first half of alphabet
    o wor   //Letters from second half of alphabet
     _      //Other characters
dHel     ll //Cycle first letters
    w oro   //Cycle second letters
     _      //Other characters stay
dHelw_oroll //Solution
</code>```

2: codegolf

```<code>codegolf
c deg lf
 o   o

f cde gl
 o   o

focdeogl
</code>```

3.: empty string

```<code>(empty string) //Input
(empty string) //Output
</code>```

Input

String you need to rotate. May be empty. Does not contain newlines.

Output

Rotated input string, trailing newline allowed

May be written to the screen or returned by a function.

Rules

No loopholes allowed

This is code-golf, so shortest code in bytes solving the problem wins

Program must return the correct solution

答:
Python, 211 Bytes

```<code>x=input()
y=lambda i:'`'<i.lower()<'n'
z=lambda i:'m'<i.lower()<'{'
u=filter(y,x)
d=filter(z,x)
r=l=""
for i in x:
 if y(i):r+=u[-1];u=[i]
 else:r+=i
for i in r[::-1]:
 if z(i):l=d[0]+l;d=[i]
 else:l=i+l
print l
</code>```

Best i could do. Takes the string from STDIN and prints the result to STDOUT.

alternative with 204 Bytes, but unfortunatly prints a newline after each char:

```<code>x=input()
y=lambda i:'`'<i.lower()<'n'
z=lambda i:'m'<i.lower()<'{'
f=filter
u=f(y,x)
d=f(z,x)
r=l=""
for i in x[::-1]:
 if z(i):l=d[0]+l;d=[i]
 else:l=i+l
for i in l:
 a=i
 if y(i):a=u[-1];u=[i]
 print a
</code>```

Title: Double rotation

Body:
Python, 211 Bytes

x=input()
y=lambda i:'`'<i.lower()<'n'
z=lambda i:'m'<i.lower()<'{'
u=filter(y,x)
d=filter(z,x)
r=l=""
for i in x:
 if y(i):r+=u[-1];u=[i]
 else:r+=i
for i in r[::-1]:
 if z(i):l=d[0]+l;d=[i]
 else:l=i+l
print l

Best i could do. Takes the string from STDIN and prints the result to STDOUT.

alternative with 204 Bytes, but unfortunatly prints a newline after each char:

x=input()
y=lambda i:'`'<i.lower()<'n'
z=lambda i:'m'<i.lower()<'{'
f=filter
u=f(y,x)
d=f(z,x)
r=l=""
for i in x[::-1]:
 if z(i):l=d[0]+l;d=[i]
 else:l=i+l
for i in l:
 a=i
 if y(i):a=u[-1];u=[i]
 print a


答:
05AB1E, <s>44</s> <s>43</s> 42 bytes

```<code>Ðžn2äø€J2ä©`ŠÃÁUÃÀVv®`yåiY¬?¦VëyåiX¬?¦Uëy?
</code>```

Explanation

Generate a list of the letters of the alphabet of both cases. ['Aa','Bb', ..., 'Zz']

```<code>Ðžn2äø€J
</code>```

Split into 2 parts and store a copy in the register.

```<code>2ä©
</code>```

Extract the letters from the input that are a part of the 1st half of the alphabet, rotate it and store in X.

```<code>`ŠÃÁU
</code>```

Extract the letters from the input that are a part of the 2nd half of the alphabet, rotate it and store in Y.

```<code>ÃÀV
</code>```

Main loop

```<code>v                         # for each char in input
 ®`                       # push the lists of first and second half of the alphabet
   yåi                    # if current char is part of the 2nd half of the alphabet
      Y¬?                 # push the first char of the rotated letters in Y
         ¦V               # and remove that char from Y
           ëyåi           # else if current char is part of the 1st half of the alphabet
               X¬?        # push the first char of the rotated letters in X
                  ¦U      # and remove that char from X
                    ëy?   # else print the current char
</code>```

Try it online!

Note: The leading Ð can be omitted in 2sable for a 41 byte solution.

Title: Double rotation

Body:
Challenge Description

Cycle all letters from the first part of the alphabet in one direction, and letters from the second half of the alphabet in the other. Other characters stay in place.

Examples

1: Hello world

```<code>Hello_world //Input
Hell     ld //Letters from first half of alphabet
    o wor   //Letters from second half of alphabet
     _      //Other characters
dHel     ll //Cycle first letters
    w oro   //Cycle second letters
     _      //Other characters stay
dHelw_oroll //Solution
</code>```

2: codegolf

```<code>codegolf
c deg lf
 o   o

f cde gl
 o   o

focdeogl
</code>```

3.: empty string

```<code>(empty string) //Input
(empty string) //Output
</code>```

Input

String you need to rotate. May be empty. Does not contain newlines.

Output

Rotated input string, trailing newline allowed

May be written to the screen or returned by a function.

Rules

No loopholes allowed

This is code-golf, so shortest code in bytes solving the problem wins

Program must return the correct solution

Body:
05AB1E, <s>44</s> <s>43</s> 42 bytes

Ðžn2äø€J2ä©`ŠÃÁUÃÀVv®`yåiY¬?¦VëyåiX¬?¦Uëy?

Explanation

Generate a list of the letters of the alphabet of both cases. ['Aa','Bb', ..., 'Zz']

Ðžn2äø€J

Split into 2 parts and store a copy in the register.

2ä©

Extract the letters from the input that are a part of the 1st half of the alphabet, rotate it and store in X.

`ŠÃÁU

Extract the letters from the input that are a part of the 2nd half of the alphabet, rotate it and store in Y.

ÃÀV

Main loop

v                         # for each char in input
 ®`                       # push the lists of first and second half of the alphabet
   yåi                    # if current char is part of the 2nd half of the alphabet
      Y¬?                 # push the first char of the rotated letters in Y
         ¦V               # and remove that char from Y
           ëyåi           # else if current char is part of the 1st half of the alphabet
               X¬?        # push the first char of the rotated letters in X
                  ¦U      # and remove that char from X
                    ëy?   # else print the current char

Try it online!

Note: The leading Ð can be omitted in 2sable for a 41 byte solution.


答:
Python 2, 115 bytes

f,a=input()
f=ord(f[1])%5
for w in sorted(set(a)):C=a.count(w);exec"print'%d '%C*(f>3)+w;"*[C>1,0,C<2,(C>1)*C,1][f]
```

<p>Example:</p>

```golf % python2.7 uniq.py <<<'["-c",["hello world","apple pie","zebra","dog","hello world","apple pie","apple pie","apple pie"]]'
4 apple pie
1 dog
2 hello world
1 zebra
```

Title: UNIX Uniq Uknow?

Body:
Python 2, 115 bytes

f,a=input()
f=ord(f[1])%5
for w in sorted(set(a)):C=a.count(w);exec"print'%d '%C*(f>3)+w;"*[C>1,0,C<2,(C>1)*C,1][f]

Example:

golf % python2.7 uniq.py <<<'["-c",["hello world","apple pie","zebra","dog","hello world","apple pie","apple pie","apple pie"]]'
4 apple pie
1 dog
2 hello world
1 zebra


答:
Javascript (ES6), <s>155</s> <s>142</s> 138 bytes

```<code>s=>(a=[],b=[],S=s,R=m=>s=s.replace(/[a-z]/gi,c=>(c<'N'|c<'n'&c>'Z'?a:b)[m](c)),R`push`,a.unshift(a.pop(b.push(b.shift()))),s=S,R`shift`,s)
</code>```

Edit: saved <s>3</s> 4 bytes by using unshift() (inspired by edc65's answer)

How it works

The R function takes an array method as its parameter m:

```<code>R = m => s = s.replace(/[a-z]/gi, c => (c < 'N' | c < 'n' & c > 'Z' ? a : b)[m](c))
</code>```

It is first used with the push method to store extracted characters in a[] (first half of alphabet) and b[] (second half of alphabet). Once these arrays have been rotated, R() is called a second time with the shift method to inject the new characters in the final string.

Hence the slightly unusual syntax: R`push`  and R`shift` .

Demo

let f =
s=>(a=[],b=[],S=s,R=m=>s=s.replace(/[a-z]/gi,c=>(c<'N'|c<'n'&c>'Z'?a:b)[m](c)),R`push`,a.unshift(a.pop(b.push(b.shift()))),s=S,R`shift`,s)

console.log("Hello_world", "=>", f("Hello_world"));
console.log("codegolf", "=>", f("codegolf"));
console.log("HELLO_WORLD", "=>", f("HELLO_WORLD"));```

Title: Double rotation

Body:
Javascript (ES6), <s>155</s> <s>142</s> 138 bytes

s=>(a=[],b=[],S=s,R=m=>s=s.replace(/[a-z]/gi,c=>(c<'N'|c<'n'&c>'Z'?a:b)[m](c)),R`push`,a.unshift(a.pop(b.push(b.shift()))),s=S,R`shift`,s)

Edit: saved <s>3</s> 4 bytes by using unshift() (inspired by edc65's answer)

How it works

The R function takes an array method as its parameter m:

R = m => s = s.replace(/[a-z]/gi, c => (c < 'N' | c < 'n' & c > 'Z' ? a : b)[m](c))

It is first used with the push method to store extracted characters in a[] (first half of alphabet) and b[] (second half of alphabet). Once these arrays have been rotated, R() is called a second time with the shift method to inject the new characters in the final string.

Hence the slightly unusual syntax: R`push`  and R`shift` .

Demo

let f =
s=>(a=[],b=[],S=s,R=m=>s=s.replace(/[a-z]/gi,c=>(c<'N'|c<'n'&c>'Z'?a:b)[m](c)),R`push`,a.unshift(a.pop(b.push(b.shift()))),s=S,R`shift`,s)

console.log("Hello_world", "=>", f("Hello_world"));
console.log("codegolf", "=>", f("codegolf"));
console.log("HELLO_WORLD", "=>", f("HELLO_WORLD"));


答:
Perl. 53 bytes

Includes +1 for -p

Run with the input on STDIN:

```<code>drotate.pl <<< "Hello_world"
</code>```

drotate.pl:

```<code>#!/usr/bin/perl -p
s%[n-z]%(//g,//g)[1]%ieg;@F=/[a-m]/gi;s//$F[-$.--]/g
</code>```

Title: Double rotation

Body:
Perl. 53 bytes

Includes +1 for -p

Run with the input on STDIN:

drotate.pl <<< "Hello_world"

drotate.pl:

#!/usr/bin/perl -p
s%[n-z]%(//g,//g)[1]%ieg;@F=/[a-m]/gi;s//$F[-$.--]/g


答:
Perl 6, 32 = 31 bytes + 1 for -p

I'm not all that proficient with Perl 6, so there may be ways to reduce it even more.

```<code>$_= ~((~$_,*.chop...^!*)X~ ^10)
</code>```

It uses -p to evaluate once for each input line. The line is placed into $_ and after the program runs, it prints $_.

The (~$_,*.chop...^!*) is a list where the first element is stringified (~) input, each subsequent element is obtained by chopping the last character off the previous one (*.chop) and that continues until the string is empty (!*), excluding the empty string case (the ^ in ...^).

X~ generates all pairs of the lists on the left and right, using the specified operation, in this case, the string concatenation (~) on them. ^10 is a list of 0, 1, ... 9.

Finally, the list is stringified again with ~, giving the required words with space as a separator.

Title: Invalid Invali Inval

Body:
This idea is loosely based upon @TùxCräftîñg's chat message.

Take a look at the below example sequence:

INVALID0, INVALID1, INVALID2 INVALID3, INVALID4... INVALID9

After INVALID9, it goes on like this:

INVALI0, INVALI1, INVALI2, INVALI3... INVALI9

And after INVALI9, it's like this:

INVAL0,INVAL1, INVAL2, INVAL3... INVAL9

After, INVAL9, it's like this:

INVA0, INVA1, INVA2, INVA3, ... INVA9

Notice how we we kept removing a letter from the word INVALID each time.

You'll keep repeating this until you reach a single letter, that is, the letter I:

I0, I1, I2, I3, I4 ... I9

Now, your task is, to take an input of a word, and produce a sequence from it like the above example. Your code must also work with single letters, and in that case the resulting sequence will be shorter.

You may choose any input and output format that you prefer (with or without a separator, as you wish), but you must specify which one you have chosen.

The sequence needs to be in the exact specified order.

The shortest code, in bytes, that successfully completes this challenge, wins the challenge.

Full sequence in the above example:

```<code>INVALID0, INVALID1, INVALID2, INVALID3, INVALID4, INVALID5, INVALID6, INVALID7, INVALID8, INVALID9, INVALI0, INVALI1, INVALI2, INVALI3, INVALI4, INVALI5, INVALI6, INVALI7, INVALI8, INVALI9, INVAL0, INVAL1, INVAL2, INVAL3, INVAL4, INVAL5, INVAL6, INVAL7, INVAL8, INVAL9, INVA0, INVA1, INVA2, INVA3, INVA4, INVA5, INVA6, INVA7, INVA8, INVA9, INV0, INV1, INV2, INV3, INV4, INV5, INV6, INV7, INV8, INV9, IN0, IN1, IN2, IN3, IN4, IN5, IN6, IN7, IN8, IN9, I0, I1, I2, I3, I4, I5, I6, I7, I8, I9
</code>```

Other examples:

Input: MAYBE (Uppercase and lowercase don't matter)

Output:

```<code>MAYBE0, MAYBE1, MAYBE2, MAYBE3, MAYBE4, MAYBE5, MAYBE6, MAYBE7, MAYBE8, MAYBE9, MAYB0, MAYB1, MAYB2, MAYB3, MAYB4, MAYB5, MAYB6, MAYB7, MAYB8, MAYB9, MAY0, MAY1, MAY2, MAY3, MAY4, MAY5, MAY6, MAY7, MAY8, MAY9, MA0, MA1, MA2, MA3, MA4, MA5, MA6, MA7, MA8, MA9, M0, M1, M2, M3, M4, M5, M6, M7, M8, M9
</code>```

Input: AFTER

Output:

```<code>AFTER0, AFTER1, AFTER2, AFTER3, AFTER4, AFTER5, AFTER6, AFTER7, AFTER8, AFTER9, AFTE0, AFTE1, AFTE2, AFTE3, AFTE4, AFTE5, AFTE6, AFTE7, AFTE8, AFTE9, AFT0, AFT1, AFT2, AFT3, AFT4, AFT5, AFT6, AFT7, AFT8, AFT9, AF0, AF1, AF2, AF3, AF4, AF5, AF6, AF7, AF8, AF9, A0, A1, A2, A3, A4, A5, A6, A7, A8, A9
</code>```

Input: WHAT ARE YOU DOING

```<code>WHAT ARE YOU DOING0, WHAT ARE YOU DOING1, WHAT ARE YOU DOING2, WHAT ARE YOU DOING3, WHAT ARE YOU DOING4, WHAT ARE YOU DOING5, WHAT ARE YOU DOING6, WHAT ARE YOU DOING7, WHAT ARE YOU DOING8, WHAT ARE YOU DOING9, WHAT ARE YOU DOIN0, WHAT ARE YOU DOIN1, WHAT ARE YOU DOIN2, WHAT ARE YOU DOIN3, WHAT ARE YOU DOIN4, WHAT ARE YOU DOIN5, WHAT ARE YOU DOIN6, WHAT ARE YOU DOIN7, WHAT ARE YOU DOIN8, WHAT ARE YOU DOIN9, WHAT ARE YOU DOI0, WHAT ARE YOU DOI1, WHAT ARE YOU DOI2, WHAT ARE YOU DOI3, WHAT ARE YOU DOI4, WHAT ARE YOU DOI5, WHAT ARE YOU DOI6, WHAT ARE YOU DOI7, WHAT ARE YOU DOI8, WHAT ARE YOU DOI9, WHAT ARE YOU DO0, WHAT ARE YOU DO1, WHAT ARE YOU DO2, WHAT ARE YOU DO3, WHAT ARE YOU DO4, WHAT ARE YOU DO5, WHAT ARE YOU DO6, WHAT ARE YOU DO7, WHAT ARE YOU DO8, WHAT ARE YOU DO9, WHAT ARE YOU D0, WHAT ARE YOU D1, WHAT ARE YOU D2, WHAT ARE YOU D3, WHAT ARE YOU D4, WHAT ARE YOU D5, WHAT ARE YOU D6, WHAT ARE YOU D7, WHAT ARE YOU D8, WHAT ARE YOU D9, WHAT ARE YOU 0, WHAT ARE YOU 1, WHAT ARE YOU 2, WHAT ARE YOU 3, WHAT ARE YOU 4, WHAT ARE YOU 5, WHAT ARE YOU 6, WHAT ARE YOU 7, WHAT ARE YOU 8, WHAT ARE YOU 9, WHAT ARE YOU0, WHAT ARE YOU1, WHAT ARE YOU2, WHAT ARE YOU3, WHAT ARE YOU4, WHAT ARE YOU5, WHAT ARE YOU6, WHAT ARE YOU7, WHAT ARE YOU8, WHAT ARE YOU9, WHAT ARE YO0, WHAT ARE YO1, WHAT ARE YO2, WHAT ARE YO3, WHAT ARE YO4, WHAT ARE YO5, WHAT ARE YO6, WHAT ARE YO7, WHAT ARE YO8, WHAT ARE YO9, WHAT ARE Y0, WHAT ARE Y1, WHAT ARE Y2, WHAT ARE Y3, WHAT ARE Y4, WHAT ARE Y5, WHAT ARE Y6, WHAT ARE Y7, WHAT ARE Y8, WHAT ARE Y9, WHAT ARE 0, WHAT ARE 1, WHAT ARE 2, WHAT ARE 3, WHAT ARE 4, WHAT ARE 5, WHAT ARE 6, WHAT ARE 7, WHAT ARE 8, WHAT ARE 9, WHAT ARE0, WHAT ARE1, WHAT ARE2, WHAT ARE3, WHAT ARE4, WHAT ARE5, WHAT ARE6, WHAT ARE7, WHAT ARE8, WHAT ARE9, WHAT AR0, WHAT AR1, WHAT AR2, WHAT AR3, WHAT AR4, WHAT AR5, WHAT AR6, WHAT AR7, WHAT AR8, WHAT AR9, WHAT A0, WHAT A1, WHAT A2, WHAT A3, WHAT A4, WHAT A5, WHAT A6, WHAT A7, WHAT A8, WHAT A9, WHAT 0, WHAT 1, WHAT 2, WHAT 3, WHAT 4, WHAT 5, WHAT 6, WHAT 7, WHAT 8, WHAT 9, WHAT0, WHAT1, WHAT2, WHAT3, WHAT4, WHAT5, WHAT6, WHAT7, WHAT8, WHAT9, WHA0, WHA1, WHA2, WHA3, WHA4, WHA5, WHA6, WHA7, WHA8, WHA9, WH0, WH1, WH2, WH3, WH4, WH5, WH6, WH7, WH8, WH9, W0, W1, W2, W3, W4, W5, W6, W7, W8, W9
</code>```

Leaderboard

var QUESTION_ID=92156,OVERRIDE_USER=58717;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

```

Body:
Perl 6, 32 = 31 bytes + 1 for -p

I'm not all that proficient with Perl 6, so there may be ways to reduce it even more.

$_= ~((~$_,*.chop...^!*)X~ ^10)

It uses -p to evaluate once for each input line. The line is placed into $_ and after the program runs, it prints $_.

The (~$_,*.chop...^!*) is a list where the first element is stringified (~) input, each subsequent element is obtained by chopping the last character off the previous one (*.chop) and that continues until the string is empty (!*), excluding the empty string case (the ^ in ...^).

X~ generates all pairs of the lists on the left and right, using the specified operation, in this case, the string concatenation (~) on them. ^10 is a list of 0, 1, ... 9.

Finally, the list is stringified again with ~, giving the required words with space as a separator.


问:
Execute prints backwards
Your task is to reverse the order in which some prints get executed.

Specs:

Your code will be in this form:

```<code>//some lines of code
/*code*/ print "Line1" /*code*/
/*code*/ print "Line2" /*code*/
/*code*/ print "Line3" /*code*/
/*code*/ print "Line4" /*code*/
//some lines of code
</code>```

You will have to print (or echo, or write, or equivalent) those strings from the fourth to the first.

You decide which lines of your program must print the strings, but they must be adjacent;

Every line can contain only one print, and cannot exceed 60 bytes in length;

Since this is popularity-contest, be creative and avoid to write just a goto or a simple for(i){if(i=4)print"Line1";if(i=3)...}

The most upvoted answer in 2 weeks wins this.

Your output MUST be Line4 Line3 Line2 Line1 OR Line4Line3Line2Line1 OR Line4\nLine3\nLine2\nLine1(where \n is a newline), and it must be generated only by executing those prints backwards.

Happy coding!

UPDATE: Contest is over! Thank you all :)

答:
Factor

```<code>[ print "line1"
  print "line2"
  print "line3"
  print "line4" ]
 reverse call
</code>```

Similar to the Common Lisp, Rebol, and Bash+tac answers, actually reverses the code before executing it.

Code-is-data + RPN = Most direct solution... even too trivial to be interesting maybe?

Title: Execute prints backwards

Body:
Factor

[ print "line1"
  print "line2"
  print "line3"
  print "line4" ]
 reverse call

Similar to the Common Lisp, Rebol, and Bash+tac answers, actually reverses the code before executing it.

Code-is-data + RPN = Most direct solution... even too trivial to be interesting maybe?


答:
Python, <s>142</s> 133 bytes

A better variation on the theme:

```<code>import re
def u(s,p):x=re.split('(?i)([%s])'%p,s);x[1::2]=x[3::2]+x[1:2];return ''.join(x)
v=lambda s:u(u(s[::-1],'A-M')[::-1],'N-Z')
</code>```

ungolfed:

```<code>import re
def u(s,p):
    x = re.split('(?i)([%s])'%p,s)  # split returns a list with matches at the odd indices
    x[1::2] = x[3::2]+x[1:2]
    return ''.join(x)

def v(s):
  w = u(s[::-1],'A-M')
  return u(w[::-1],'N-Z')
</code>```

prior solution:

```<code>import re
def h(s,p):t=re.findall(p,s);t=t[1:]+t[:1];return re.sub(p,lambda _:t.pop(0),s)
f=lambda s:h(h(s[::-1],'[A-Ma-m]')[::-1],'[N-Zn-z]')
</code>```

ungolfed:

```<code>import re
def h(s,p):                              # moves matched letters toward front
    t=re.findall(p,s)                    # find all letters in s that match p
    t=t[1:]+t[:1]                        # shift the matched letters
    return re.sub(p,lambda _:t.pop(0),s) # replace with shifted letter

def f(s):
    t = h(s[::-1],'[A-Ma-m]')            # move first half letters toward end
    u = h(t[::-1],'[N-Zn-z]')            # move 2nd half letters toward front
    return u
</code>```

Title: Double rotation

Body:
Python, <s>142</s> 133 bytes

A better variation on the theme:

import re
def u(s,p):x=re.split('(?i)([%s])'%p,s);x[1::2]=x[3::2]+x[1:2];return ''.join(x)
v=lambda s:u(u(s[::-1],'A-M')[::-1],'N-Z')

ungolfed:

import re
def u(s,p):
    x = re.split('(?i)([%s])'%p,s)  # split returns a list with matches at the odd indices
    x[1::2] = x[3::2]+x[1:2]
    return ''.join(x)

def v(s):
  w = u(s[::-1],'A-M')
  return u(w[::-1],'N-Z')

prior solution:

import re
def h(s,p):t=re.findall(p,s);t=t[1:]+t[:1];return re.sub(p,lambda _:t.pop(0),s)
f=lambda s:h(h(s[::-1],'[A-Ma-m]')[::-1],'[N-Zn-z]')

ungolfed:

import re
def h(s,p):                              # moves matched letters toward front
    t=re.findall(p,s)                    # find all letters in s that match p
    t=t[1:]+t[:1]                        # shift the matched letters
    return re.sub(p,lambda _:t.pop(0),s) # replace with shifted letter

def f(s):
    t = h(s[::-1],'[A-Ma-m]')            # move first half letters toward end
    u = h(t[::-1],'[N-Zn-z]')            # move 2nd half letters toward front
    return u


问:
Dimensional countdown
Write a function f(n,k) that displays the k-dimensional countdown from n.

A 1-dimensional countdown from 5 looks like

```<code> 54321
</code>```

A 2-dimensional countdown from 5 looks like

```<code> 54321
 4321
 321
 21
 1
</code>```

Finally, a 3-dimensional countdown from 5 looks like

```<code> 54321
 4321
 321
 21
 1
 4321
 321
 21
 1
 321
 21
 1
 21
 1
 1
</code>```

Formal definition

The 1-dimensional countdown from any n is a single line with the digits n, n-1,...,1 concatenated (followed by a newline).

For any k, the k-dimensional countdown from 1 is the single line

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

For n > 1 and k > 1, a k-dimensional countdown from n is a (k-1)-dimensional countdown from n followed by a k-dimensional countdown from n-1.

Input

Two positive integers k and n <= 9, in any format you choose.

Output

The k-dimensional countdown from n, with a newline after each 1-dimensional countdown. Extra newlines are permitted in the output.

Scoring

Standard golf scoring.

Bonus example

Here's an example with k > n, a 4-dimensional countdown from 3 (with extra comments that are not to be included in actual solutions):

```<code> -- 3-dimensional countdown from 3
 321
 21
 1
 21
 1
 1
 -- 4-dimensional countdown from 2:
 ---- 3-dimensional countdown from 2:
 21
 1
 1
 ---- 4-dimensional countdown from 1:
 1
</code>```

Clarifications:

Digits on a line do not need to be adjacent, but they must be evenly-spaced.

You may write a full program instead of just a function, if you prefer.

答:
Dyalog APL, 18 bytes

Prompts for n, then for k.

~∘'0'⍤1⍕(⌽⍳)⍤0⍣⎕⊢⎕
```

~∘'0'⍤1 remove (~) the (∘) zeros ('0') from the rows (⍤1) (padding with spaces as needed) of

⍕ the character representation of

(⌽⍳)⍤0⍣⎕ the reversed (⌽) count until (⍳) each scalar (⍤0), repeated (⍣) input (⎕) times

⊢ on

⎕ numeric input

TryAPL online!

Title: Dimensional countdown

Body:
Dyalog APL, 18 bytes

Prompts for n, then for k.

~∘'0'⍤1⍕(⌽⍳)⍤0⍣⎕⊢⎕

~∘'0'⍤1 remove (~) the (∘) zeros ('0') from the rows (⍤1) (padding with spaces as needed) of

⍕ the character representation of

(⌽⍳)⍤0⍣⎕ the reversed (⌽) count until (⍳) each scalar (⍤0), repeated (⍣) input (⎕) times

⊢ on

⎕ numeric input

TryAPL online!


问:
Lenient typing test
A typing speed test loads up a dictionary of words, and gives you one to type: pinball. You,  with your fast but inaccurate fingers, type in pinbnal. Darn it!

Make a program that will print out a random word from a dictionary, then ask for the user to type this word back, and finally return whether or not they got the word right. The catch is: the program must accept minor typos.

Accept a typo if it has only one of the following:

one letter is repeated in the input 1 or 2 more times. Only accept the letter if it is directly adjacent to a letter it is next to.

one letter in the word is repeated 1 time.

2-4 of the letters in the input are scrambled.

Some acceptable typos of the word pinball are:

pingball pinbala pinbanll

Some unacceptable typos:

pibnannl maxwell pinbalgl

Shortest code wins. Good luck.

答:
Mathematica 179

Edit: As Primo correctly notes, the following does not adhere to the constraint of pardoning only those intrusions from QWERTY neighbors. DL distance, of course, has nothing to do with distance on a keyboard.  Oh, well. I'll leave up my response, which someone with more patience will easily better.

Code

```<code>d = DictionaryLookup[]; i = d[[RandomInteger@{1, Length@d}]];o = InputString["Type: " <> i];
Print["in: ", i, "\nout: ", o, "\n", Switch[i~DamerauLevenshteinDistance~o, 0, "perfect",
1, "ok", _, "wrong"]]
</code>```

Explanation

d = DictionaryLookup[] stores a built-in dictionary of 92 k English words in d.

i = d[[RandomInteger@{1, Length@d}]] selects a random word and stores it in i.

o = InputString["Type: " <> i]; opens a dialog window (see figure) with the prompt "Type [i]."

i~DamerauLevenshteinDistance~o computes the Damerau-Levenshtein distance beween the requested word  and the word typed by the user. If the DL distance = 0, "perfect"; if the DL distance = 1, "ok"; otherwise, "wrong".

Test Results

For the first 7 tests, the input string, i, was manually set to "pinball".
The results were as desired with the exception of "pinbalgl", which was considered acceptable because it returns a DL distance value of 1.

in: pinball

  out: pinball

  perfect

in: pinball

  out: pingball

  ok

in: pinball

  out: pinbala

  ok

in: pinball

  out: pinbanll

  ok

in: pinball

  out: pinbannl

  wrong

in: pinball

  out: maxwell

  wrong

in: pinball

  out: pinbalgl

  ok

in: tureen

  out: turen

  ok

in: feeder

  out: feedr

  ok

in: tarmacs

  out: tarmax

  wrong

Title: Lenient typing test

Body:
Mathematica 179

Edit: As Primo correctly notes, the following does not adhere to the constraint of pardoning only those intrusions from QWERTY neighbors. DL distance, of course, has nothing to do with distance on a keyboard.  Oh, well. I'll leave up my response, which someone with more patience will easily better.

Code

d = DictionaryLookup[]; i = d[[RandomInteger@{1, Length@d}]];o = InputString["Type: " <> i];
Print["in: ", i, "\nout: ", o, "\n", Switch[i~DamerauLevenshteinDistance~o, 0, "perfect",
1, "ok", _, "wrong"]]

Explanation

d = DictionaryLookup[] stores a built-in dictionary of 92 k English words in d.

i = d[[RandomInteger@{1, Length@d}]] selects a random word and stores it in i.

o = InputString["Type: " <> i]; opens a dialog window (see figure) with the prompt "Type [i]."

i~DamerauLevenshteinDistance~o computes the Damerau-Levenshtein distance beween the requested word  and the word typed by the user. If the DL distance = 0, "perfect"; if the DL distance = 1, "ok"; otherwise, "wrong".

Test Results

For the first 7 tests, the input string, i, was manually set to "pinball".
The results were as desired with the exception of "pinbalgl", which was considered acceptable because it returns a DL distance value of 1.

in: pinball

  out: pinball

  perfect

in: pinball

  out: pingball

  ok

in: pinball

  out: pinbala

  ok

in: pinball

  out: pinbanll

  ok

in: pinball

  out: pinbannl

  wrong

in: pinball

  out: maxwell

  wrong

in: pinball

  out: pinbalgl

  ok

in: tureen

  out: turen

  ok

in: feeder

  out: feedr

  ok

in: tarmacs

  out: tarmax

  wrong


问:
Numeric to Alphabetic Organization
I have a list of images grouped numerically (YI0.png, YI1.png...YI20479.png). I want them sorted alphabetically, like so:

```<code>YI0.png -> YIA.png
YI1.png -> YIAA.png
</code>```

without my last image having 20479 As in it.

Input

A directory name.

Output

All files in that directory will be alphabetically renamed.

Constraints

The pattern is always Prefix Number.Extension

There are no subdirectories

All files in the directory adhere to the pattern

Number starts at 0

Prefix doesn't contain numbers

Example

Directory consisting of Pie0.txt, Pie1.txt, all the way to Pie11.txt would be renamed to PieA.txt, PieB.txt, all the way to PieL.txt.

If it goes to Pie28.txt, they would be renamed like so:

```<code>Pie0.txt -> PieA.txt
Pie1.txt -> PieAA.txt
Pie2.txt -> PieAB.txt
Pie3.txt -> PieB.txt
Pie28.txt -> PieZ.txt
</code>```

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

答:
Perl, 65 bytes

Assumes the number sequence starts with 0 and has no holes (or duplicates if there are extra leading zeros). No error checking.
Assumes only plain files, filenames do not start with . and the user can enter the directory.

Run with the directory as argument

```<code>alphaorg.pl directory
</code>```

alphaorg.pl:

```<code>#!/usr/bin/perl
chdir pop;$a=A;@F=sort map$a++,<*>;rename$_,s/\d+/$F[$&]/r for<*>
</code>```

If the directory name can't contain digits and your sytem will accept / as directory separator (unix and windows do), this 61 byte version is shorter (give directory name on STDIN here):

```<code>#!/usr/bin/perl -ln
$a=A;@F=sort map$a++,@;=<$_/*>;rename$_,s/\d+/$F[$&]/r for@
</code>```

Title: Numeric to Alphabetic Organization

Body:
Perl, 65 bytes

Assumes the number sequence starts with 0 and has no holes (or duplicates if there are extra leading zeros). No error checking.
Assumes only plain files, filenames do not start with . and the user can enter the directory.

Run with the directory as argument

alphaorg.pl directory

alphaorg.pl:

#!/usr/bin/perl
chdir pop;$a=A;@F=sort map$a++,<*>;rename$_,s/\d+/$F[$&]/r for<*>

If the directory name can't contain digits and your sytem will accept / as directory separator (unix and windows do), this 61 byte version is shorter (give directory name on STDIN here):

#!/usr/bin/perl -ln
$a=A;@F=sort map$a++,@;=<$_/*>;rename$_,s/\d+/$F[$&]/r for@


答:
Haskell - 97 bytes

I probably picked the wrong language; Haskell has painfully long names for IO operations

```<code>r p=do f<-getDirectoryContents p;sequence_.zipWith renameFile(sort f).sort$permutations['A'..'Z']
</code>```

(this program has O(26^26) in run-time unless you're on a quantum computer)

Title: Numeric to Alphabetic Organization

Body:
I have a list of images grouped numerically (YI0.png, YI1.png...YI20479.png). I want them sorted alphabetically, like so:

```<code>YI0.png -> YIA.png
YI1.png -> YIAA.png
</code>```

without my last image having 20479 As in it.

Input

A directory name.

Output

All files in that directory will be alphabetically renamed.

Constraints

The pattern is always Prefix Number.Extension

There are no subdirectories

All files in the directory adhere to the pattern

Number starts at 0

Prefix doesn't contain numbers

Example

Directory consisting of Pie0.txt, Pie1.txt, all the way to Pie11.txt would be renamed to PieA.txt, PieB.txt, all the way to PieL.txt.

If it goes to Pie28.txt, they would be renamed like so:

```<code>Pie0.txt -> PieA.txt
Pie1.txt -> PieAA.txt
Pie2.txt -> PieAB.txt
Pie3.txt -> PieB.txt
Pie28.txt -> PieZ.txt
</code>```

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

Body:
Haskell - 97 bytes

I probably picked the wrong language; Haskell has painfully long names for IO operations

r p=do f<-getDirectoryContents p;sequence_.zipWith renameFile(sort f).sort$permutations['A'..'Z']

(this program has O(26^26) in run-time unless you're on a quantum computer)


答:
GNU sed, <s>496</s> 485 + 2(rn flags) = 487 bytes

```<code>1h;1b;$bb;2{:r;$!N;$!br;s/.*/echo "&"|sort/e};:b;x;/[dD]/bd;/c/bc;/u/!b;x;s/^/\n/
s/(\n.*)\1+//g;s/\n//p;b;:d;x;/^(.*)\n\1/!D;:l;x;/D/{x;P;x};x;s/^[^\n]*\n//
/^(.*)\n\1/bl;P;D;:c;s/$/#/;G;x;/^$/bp;s/[^\n]*\n?//;x;s/#(\n[^\n]*).*/\1/
/([^:\n]*)\n\1$/{s/\n[^\n]*$//;:i;s/9(@*:)/@\1/;ti;s/8(@*:)/9\1/;s/7(@*:)/8\1/
s/6(@*:)/7\1/;s/5(@*:)/6\1/;s/4(@*:)/5\1/;s/3(@*:)/4\1/;s/2(@*:)/3\1/;s/1(@*:)/2\1/
s/0(@*:)/1\1/;s/@+:/1&/;y/@/0/;bc};s/:/ /;s/[^\n]*$/1:&/;bc;:p;x;s/...//;s/..$//;s/:/ /gp
</code>```

The code size is not going to compete, but it was fun emulating the uniq command. I wanted to add a simple selection sort to get rid of the sort call, thus solving it in pure sed only, but the code got too long already. The input is read entirely from STDIN, with the flag expected on the first line.

Run:

(echo "-c";cat input_file)|sed -rnf uniq_emulator.sed
```

<p><strong>Output:</strong></p>

```4 apple pie
1 dog
2 hello world
1 zebra
```

<p><strong>Initially submitted code and explanation:</strong> (sections are separated by an extra newline)</p>

<pre class="lang-sed prettyprint-override"><code># The main
    # store the flag in hold space and start next cycle
1h;1b
    # usually a cycle starts with each line read, but I also start it manually,
    #so I need to skip some lines that should run only once
$bb
2{
        # read the entire input into pattern space
    :r;$!N;$!br
        # executes a shell call to sort the pattern space
    s/.*/echo "&"|sort/e
}
    # based on the flag, the appropriate jumps to "functions" are made
:b;x;/[dD]/bd;/c/bc;/u/!b

# Unique: -u
    # all duplicate lines are deleted and what remains is printed
x;s/^/\n/;s/(\n.*)\1+//g
s/\n//p;b

# Duplication: -d and -D
    # if the first 2 lines are different, delete the first and start new cycle
:d;x;/^(.*)\n\1/!D
:l
        # if -D, print the first duplicate line
    x;/D/{x;P;x};x
        # otherwise (-d), delete the first duplicate line
    s/^[^\n]*\n//
        # loop condition, go back to :l if the first 2 lines are duplicate
/^(.*)\n\1/bl
    # print only the first line and start a new cycle
P;D

# Counting: -c
    # in order to count line occurrences, I simulate reading the input again
    # In a loop I append all pattern space to hold space, delete first line of
    #pattern space and from hold space all lines except the first one appended.
:c;s/$/#/;G
x;/^$/bp;s/[^\n]*\n?//;x;s/#(\n[^\n]*).*/\1/
    # if the new line "read" is the same as the previous one, increment the
    #counter of that line (format is "counter:line"), delete and go back to :c
/([^:\n]*)\n\1$/{s/\n[^\n]*$//;bi;:I;bc}
    # otherwise, stop the counter for the previous line, add a counter for the
    #current one and go back to :c
s/:/ /;s/[^\n]*$/1:&/;bc
    # when the loop ends, the hold space with all counts is printed
:p;x;s/...//;s/..$//;s/:/ /gp

# Increment function that works by manually updating the changing digit(s)
:i;s/9(@*:)/@\1/;ti
s/8(@*:)/9\1/;s/7(@*:)/8\1/;s/6(@*:)/7\1/
s/5(@*:)/6\1/;s/4(@*:)/5\1/;s/3(@*:)/4\1/
s/2(@*:)/3\1/;s/1(@*:)/2\1/;s/0(@*:)/1\1/
s/@+:/1&/;y/@/0/;tI
</code>```

Title: UNIX Uniq Uknow?

Body:
Challenge

You must write a program which takes a string and a flag as input and performs one of the following functions.

Input

If your language does not support command line arguments, you may take the arguments as input via STDIN.

The flag will be two characters: a dash and an ASCII character such as -d or -c.

Functions

The following is the list of functions which you must implement in your program. The title of each is the flag which corresponds to the function.

Counting: -c

This counts the number of duplicate lines in the input file. For example, if the input is:

```<code>aa
aa
bb
bb
bb
xx
</code>```

The output will be:

```<code>2 aa
3 bb
1 xx
</code>```

Because there are two lines of aa, three lines of bb, and one line of xx. The output should be separated by newlines.

Duplication: -d

This shows which lines are duplicates. For example, using the above example string (aa\naa\nbb\nbb\nbb\nxx), the output would be:

```<code>aa
bb
</code>```

Because these are lines which have been duplicated. You should only output each line once.

Duplication: -D

This is almost the same as -d except it outputs each line the number of times that it occurs in the input file. For example, using the example string the output will be:

```<code>aa
aa
bb
bb
bb
</code>```

Because aa occurs twice and bb occurs three times.

Unique: -u

Similar to above except it only prints unique lines. For example, using the example file, the output will be:

```<code>xx
</code>```

Because xx is the only unique line. Also, due to xx being unique, you will only ever have to output this once.

Example

Note that although the input string will not always be sorted, the output must be sorted alphabetically. For example, for the following input:

```<code>hello world
apple pie
zebra
dog
hello world
apple pie
apple pie
apple pie
</code>```

The output for each of the flags would be:

-c

```<code>4 apple pie
1 dog
2 hello world
1 zebra
</code>```

-d

```<code>apple pie
hello world
</code>```

-D

```<code>apple pie
apple pie
apple pie
apple pie
hello world
hello world
</code>```

-u

```<code>dog
zebra
</code>```

Rules

Your programs must not use the UNIX program uniq as, frankly, that is plain cheating.

All output should be to STDOUT.

The file will only ever contain lowercase, alphabetical characters, newlines and spaces:

```<code>2 aa
3 bb
1 xx
</code>```0

The output should be sorted alphabetically.

In case there is any confusion, programs written on any operating system can enter. The challenge is not limited to UNIX.

As per PPCG standard, functions and anonymous functions are allowed, taking input via their arguments and outputting via a returned string.

Winning

As this is code-golf, the shortest code in bytes wins.

Body:
GNU sed, <s>496</s> 485 + 2(rn flags) = 487 bytes

1h;1b;$bb;2{:r;$!N;$!br;s/.*/echo "&"|sort/e};:b;x;/[dD]/bd;/c/bc;/u/!b;x;s/^/\n/
s/(\n.*)\1+//g;s/\n//p;b;:d;x;/^(.*)\n\1/!D;:l;x;/D/{x;P;x};x;s/^[^\n]*\n//
/^(.*)\n\1/bl;P;D;:c;s/$/#/;G;x;/^$/bp;s/[^\n]*\n?//;x;s/#(\n[^\n]*).*/\1/
/([^:\n]*)\n\1$/{s/\n[^\n]*$//;:i;s/9(@*:)/@\1/;ti;s/8(@*:)/9\1/;s/7(@*:)/8\1/
s/6(@*:)/7\1/;s/5(@*:)/6\1/;s/4(@*:)/5\1/;s/3(@*:)/4\1/;s/2(@*:)/3\1/;s/1(@*:)/2\1/
s/0(@*:)/1\1/;s/@+:/1&/;y/@/0/;bc};s/:/ /;s/[^\n]*$/1:&/;bc;:p;x;s/...//;s/..$//;s/:/ /gp

The code size is not going to compete, but it was fun emulating the uniq command. I wanted to add a simple selection sort to get rid of the sort call, thus solving it in pure sed only, but the code got too long already. The input is read entirely from STDIN, with the flag expected on the first line.

Run:

(echo "-c";cat input_file)|sed -rnf uniq_emulator.sed

Output:

4 apple pie
1 dog
2 hello world
1 zebra

Initially submitted code and explanation: (sections are separated by an extra newline)

# The main
    # store the flag in hold space and start next cycle
1h;1b
    # usually a cycle starts with each line read, but I also start it manually,
    #so I need to skip some lines that should run only once
$bb
2{
        # read the entire input into pattern space
    :r;$!N;$!br
        # executes a shell call to sort the pattern space
    s/.*/echo "&"|sort/e
}
    # based on the flag, the appropriate jumps to "functions" are made
:b;x;/[dD]/bd;/c/bc;/u/!b

# Unique: -u
    # all duplicate lines are deleted and what remains is printed
x;s/^/\n/;s/(\n.*)\1+//g
s/\n//p;b

# Duplication: -d and -D
    # if the first 2 lines are different, delete the first and start new cycle
:d;x;/^(.*)\n\1/!D
:l
        # if -D, print the first duplicate line
    x;/D/{x;P;x};x
        # otherwise (-d), delete the first duplicate line
    s/^[^\n]*\n//
        # loop condition, go back to :l if the first 2 lines are duplicate
/^(.*)\n\1/bl
    # print only the first line and start a new cycle
P;D

# Counting: -c
    # in order to count line occurrences, I simulate reading the input again
    # In a loop I append all pattern space to hold space, delete first line of
    #pattern space and from hold space all lines except the first one appended.
:c;s/$/#/;G
x;/^$/bp;s/[^\n]*\n?//;x;s/#(\n[^\n]*).*/\1/
    # if the new line "read" is the same as the previous one, increment the
    #counter of that line (format is "counter:line"), delete and go back to :c
/([^:\n]*)\n\1$/{s/\n[^\n]*$//;bi;:I;bc}
    # otherwise, stop the counter for the previous line, add a counter for the
    #current one and go back to :c
s/:/ /;s/[^\n]*$/1:&/;bc
    # when the loop ends, the hold space with all counts is printed
:p;x;s/...//;s/..$//;s/:/ /gp

# Increment function that works by manually updating the changing digit(s)
:i;s/9(@*:)/@\1/;ti
s/8(@*:)/9\1/;s/7(@*:)/8\1/;s/6(@*:)/7\1/
s/5(@*:)/6\1/;s/4(@*:)/5\1/;s/3(@*:)/4\1/
s/2(@*:)/3\1/;s/1(@*:)/2\1/;s/0(@*:)/1\1/
s/@+:/1&/;y/@/0/;tI


问:
Two Symbol Math

Introduction

The four basic math operators (+, -, *, /) can be reduced to just two, due to the fact that:

```<code>x + y = x - (-y)
x * y = x / (1/y), y != 0
x * 0 = 0/x
</code>```

Challenge

The challenge is to take input as a "string" containing:

Numbers

Single character variables ("x", "y")

The four basic math operators (+, -, *, /)

Parenthesis

and output a string manipulated so that it would produce the same mathematical result as the input, but containing only the mathematical symbols '-' and '/'

Specifics

Input can be in any acceptable form (file, STDIN, etc.) and may be represented as a string or character array (but not an array of arrays)

Output can be in any acceptable form (file, STDIN, etc.) and may be represented as a string or character array (but not an array of arrays)

You must recognize and maintain balanced parenthesis

Standard loopholes are disallowed

It is your choice if you want to represent x + y as x - -y or x - (-y)

You must maintain the order of operations

You never have to handle invalid input

Input can be empty or a single number/variable, in that case the program should output the input

Note: You do not have to use the substitutions in the introduction, so long as input = output, your program could change 2 * 2 to 8/2, if you wanted

You can assume that "0" is the only way a zero will appear in the equation (I.e. you don't have to handle 1 * (4 - 4))

Suggestion: to test your program, go to this website type in input = output, where input is the input, and output is the output, and if the result is "true" your program handled that case successfully (example, example)

Test Cases

Below are some test cases, input as a single string and output as a single string.

```<code>x + y
x - (-y)

x * y
x / (1/y)

x / y
x / y

x - y
x - y

1
1

5
5

-6
-6

+x
x

1 + (x * 4) - (512 * 3)
1 - (-(x / (1/4))) - (512 / (1/3))

1 - 3 / 4 + l / g
1 - 3/4 - (-(l / g))

5 * 0 / 2
0/5 / 2

(a + g) * 0
0/(a - (-g))
</code>```

Scoring

It's code-golf, so shortest answer in bytes wins. Ties are resolved by first-post.

Title: Two Symbol Math

Body:
Python 3, 267 bytes

Thanks to @ConorO'Brien

import re
q=re.sub
g=lambda m:'--'+m.group()[1:]
h=lambda m:'/(1/'+m.group()[1:]+')'
i=lambda m:'0/'+m.group()[:-2]
print(q(r'\*[^\(\)]+',h,q(r'[^\(\)]\*0',i,q(r'\+[^\(\)]+',g,q(r'\*\([^\)]+\)',h,q(r'\([^\)]+\)\*0',i,q(r'\+\([^\)]+\)',g,input().replace(' ',''))))))))

Ideone it!


问:
Segmented numbers
The sequence of segmented numbers or prime numbers of measurement (OEIS A002048) is the sequence of numbers such that each member is the smallest positive (greater than zero) number that can't be made of a sum of earlier consecutive numbers, with a(0) = 1.

Example

To calculate a(7) we first calculate a(0->6) = [1, 2, 4, 5, 8, 10, 14]. we then start from zero and go through numbers until we find one that is not the sum of one or more consecutive numbers in the sequence.

```<code>1  = 1
2  = 2
3  = 1 + 2
4  = 4
5  = 5
6  = 2 + 4
7  = 1 + 2 + 4
8  = 8
9  = 4 + 5
10 = 10
11 = 2 + 4 + 5
12 = 1 + 2 + 4 + 5
13 = 5 + 8
14 = 14
15 = ????
</code>```

Since fifteen cannot be made by summing any consecutive subsequence and every number smaller can be fifteen is the next number in the sequence. a(7) = 15

Task

Your task is to take a number (via standard methods) and output the nth term in this sequence (via standard output methods).  This is code-golf and you will be scored as such.

Test Cases

```<code>0 -> 1
1 -> 2
2 -> 4
3 -> 5
4 -> 8
5 -> 10
6 -> 14
7 -> 15
8 -> 16
9 -> 21
</code>```

答:
Haskell, <s>62</s> 58 bytes

-4 bytes thanks to @xnor!

```<code>(x:y)#z=x:filter(`notElem`scanl(+)x z)y#(x:z)
([1..]#[]!!)
</code>```

Sequence is 0-indexed.

Title: Segmented numbers

Body:
Haskell, <s>62</s> 58 bytes

-4 bytes thanks to @xnor!

(x:y)#z=x:filter(`notElem`scanl(+)x z)y#(x:z)
([1..]#[]!!)

Sequence is 0-indexed.


答:
Perl, <s>50</s> 49 bytes

Includes +1 for -p

Run with input on STDIN:

```<code>segmented.pl <<< 7
</code>```

segmented.pl:

```<code>#!/usr/bin/perl -p
${$_-=$\}++for@F;1while${-++$\};++$#F<$_&&redo}{
</code>```

Explanation

@F contains the list of (negative) sums of consecutive numbers that end with the current last number. When a new number is discovered the list is extended with 0 and then all values are decreased by the new number maintaining the invariant.

Global %:: is used as a hash mapping all (negative) numbers that have been seen (through @F) to a non-zero value.

$\ is the current number and gets increased until it reaches a value not yet in %::.

By being a bit careful about the order in which everything happens no initialization is needed, 1 will automatically become the first number.

Since the size of @F is how many numbers have been generated it can be used as a halting condition

Title: Segmented numbers

Body:
The sequence of segmented numbers or prime numbers of measurement (OEIS A002048) is the sequence of numbers such that each member is the smallest positive (greater than zero) number that can't be made of a sum of earlier consecutive numbers, with a(0) = 1.

Example

To calculate a(7) we first calculate a(0->6) = [1, 2, 4, 5, 8, 10, 14]. we then start from zero and go through numbers until we find one that is not the sum of one or more consecutive numbers in the sequence.

```<code>1  = 1
2  = 2
3  = 1 + 2
4  = 4
5  = 5
6  = 2 + 4
7  = 1 + 2 + 4
8  = 8
9  = 4 + 5
10 = 10
11 = 2 + 4 + 5
12 = 1 + 2 + 4 + 5
13 = 5 + 8
14 = 14
15 = ????
</code>```

Since fifteen cannot be made by summing any consecutive subsequence and every number smaller can be fifteen is the next number in the sequence. a(7) = 15

Task

Your task is to take a number (via standard methods) and output the nth term in this sequence (via standard output methods).  This is code-golf and you will be scored as such.

Test Cases

```<code>0 -> 1
1 -> 2
2 -> 4
3 -> 5
4 -> 8
5 -> 10
6 -> 14
7 -> 15
8 -> 16
9 -> 21
</code>```

Body:
Perl, <s>50</s> 49 bytes

Includes +1 for -p

Run with input on STDIN:

segmented.pl <<< 7

segmented.pl:

#!/usr/bin/perl -p
${$_-=$\}++for@F;1while${-++$\};++$#F<$_&&redo}{

Explanation

@F contains the list of (negative) sums of consecutive numbers that end with the current last number. When a new number is discovered the list is extended with 0 and then all values are decreased by the new number maintaining the invariant.

Global %:: is used as a hash mapping all (negative) numbers that have been seen (through @F) to a non-zero value.

$\ is the current number and gets increased until it reaches a value not yet in %::.

By being a bit careful about the order in which everything happens no initialization is needed, 1 will automatically become the first number.

Since the size of @F is how many numbers have been generated it can be used as a halting condition


答:
Pyth - <s>19</s> 17 bytes

Damn off-by one ruining all my implicits. (Same bytes count, literaly incrementing Q: =hQesmaYf!}TsM.:Y)

```<code>esmaYf!}TsM.:Y)1h
</code>```

Test Suite.

Title: Segmented numbers

Body:
Pyth - <s>19</s> 17 bytes

Damn off-by one ruining all my implicits. (Same bytes count, literaly incrementing Q: =hQesmaYf!}TsM.:Y)

esmaYf!}TsM.:Y)1h

Test Suite.


答:
05AB1E, <s>17</s> 16 bytes

```<code>Xˆ$µ>D¯ŒOså_i¼Dˆ
</code>```

Explanation

```<code>Xˆ                # initialize global array to [1]
  $               # push 1 and input to stack
   µ              # while counter != input
    >             # increase variable on stack
      ¯ŒO         # list of all sums of consecutive number in global array
     D   så_i     # if current stack value is not in the list
             ¼    # increase counter
              Dˆ  # add current stack value to global array
</code>```

Try it online!

Saved 1 byte thanks to Adnan

Title: Segmented numbers

Body:
05AB1E, <s>17</s> 16 bytes

Xˆ$µ>D¯ŒOså_i¼Dˆ

Explanation

Xˆ                # initialize global array to [1]
  $               # push 1 and input to stack
   µ              # while counter != input
    >             # increase variable on stack
      ¯ŒO         # list of all sums of consecutive number in global array
     D   så_i     # if current stack value is not in the list
             ¼    # increase counter
              Dˆ  # add current stack value to global array

Try it online!

Saved 1 byte thanks to Adnan


答:
Python, <s>113</s> <s>105</s> <s>92</s> 80 bytes

```<code>s=F={1}
x=1
exec"while{x}<=s:x+=1\nF={x+j for j in{0}|F};s|=F\n"*input()
print x
</code>```

The final bytes I saved were inspired by Ton’s Perl answer: my F does the same thing as his @F; my s does essentially the same thing as his %::.

Title: Segmented numbers

Body:
Python, <s>113</s> <s>105</s> <s>92</s> 80 bytes

s=F={1}
x=1
exec"while{x}<=s:x+=1\nF={x+j for j in{0}|F};s|=F\n"*input()
print x

The final bytes I saved were inspired by Ton’s Perl answer: my F does the same thing as his @F; my s does essentially the same thing as his %::.


答:
Jelly, <s>14</s> <s>13</s> 11 bytes

```<code>Ḷß€Ẇ;ḅ1‘ḟ$Ṃ
</code>```

Try it online!

How it works

```<code>Ḷß€Ẇ;ḅ1‘ḟ$Ṃ  Main link. Argument: n

Ḷ            Unlength; yield [0, ..., n - 1].
 ß€          Recursively map the main link over the range.
   Ẇ         Window; yield all subarrays of consecutive elements of the result.
    ;        Append n to the array of subarrays.
     ḅ1      Convert all subarrays from base 1 to integer.
             This is equivalent to S€ (sum each), but it allows ; to hook.
         $   Combine the previous two links into a monadic chain.
       ‘       Increment all sums.
        ḟ      Filter; remove the original sums from the incremented ones.
          Ṃ  Compute the minimum.
</code>```

Title: Segmented numbers

Body:
Jelly, <s>14</s> <s>13</s> 11 bytes

Ḷß€Ẇ;ḅ1‘ḟ$Ṃ

Try it online!

How it works

Ḷß€Ẇ;ḅ1‘ḟ$Ṃ  Main link. Argument: n

Ḷ            Unlength; yield [0, ..., n - 1].
 ß€          Recursively map the main link over the range.
   Ẇ         Window; yield all subarrays of consecutive elements of the result.
    ;        Append n to the array of subarrays.
     ḅ1      Convert all subarrays from base 1 to integer.
             This is equivalent to S€ (sum each), but it allows ; to hook.
         $   Combine the previous two links into a monadic chain.
       ‘       Increment all sums.
        ḟ      Filter; remove the original sums from the incremented ones.
          Ṃ  Compute the minimum.


问:
Find every digit from the largest column
Here's a relatively simple challenge for you:

Given a list of positive integers:

Line them up in a grid, and sum each column. For example, if the input was [123, 7, 49, 681], the grid would look like this:

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

And the sum of each column would be [18, 19, 4]:

```<code> 1  2  3
 7
 4  9
 6  8  1
 --------
 18 19 4
</code>```

Find the maximum of these sums, which in this case would be 19, and then

Output every digit that is at the same index as this maximum column. In this case, that would be

```<code>2
9
8
</code>```

You do not have to output these numbers in any particular order.
Note that there are only three outputs, even though we had 4 inputs. In the case of a tie, pick the earliest index. For example, if the input was [25, 223, 302], your grid is:

```<code>2  5
2  2  3
3  0  2
-------
7  7  5
</code>```

You should output

```<code>2
2
3
</code>```

You can print these numbers in any format you like. List format, newline separated, space separated, etc. You may not take the input as a 2D array of digits, e.g.

```<code>[[1, 2, 3],
[7],
[4, 9],
[6, 8, 1]
</code>```

But other than that, you can take input as a list of strings, a list of digits, or any other reasonable format.

You may also assume that all inputs will be valid and contain at least two numbers.

As usual, the shortest answer in bytes wins!

Test IO:

```<code>#Input                      #Output
[1, 11, 111, 1111]      --> [1, 1, 1, 1]
[1, 12, 123]            --> [2, 2]
[987654321, 111]        --> [9, 1]
[111, 123456789]        --> [9]
[4, 8, 15, 16, 23, 42]  --> [4, 8, 1, 1, 2, 4]
[4, 8, 12, 26, 27, 38]  --> [2, 6, 7, 8]
[24, 53]                --> [2, 5]
[12, 304, 506]          --> [4, 6]
[30, 285, 121]          --> [0, 8, 2]
</code>```

答:
Pyth - 9 bytes

```<code>esD_.TjRT
</code>```

Test Suite.

Body:
Pyth - 9 bytes

esD_.TjRT

Test Suite.


答:
Javascript, 125 112 110 bytes

Saved 2 bytes thanks to @Neil

f=n=>{a=[[]];for(i=1,z=0;z<=n;i++)a.some(b=>b.includes(i))||(a[z+1]=[0,...a[z++]||[]].map(v=>i+v));alert(i-1)}
```
<p><em>Previous answers</em></p>
<p>112 bytes thanks to @Neil:</p>
<pre class="lang-js prettyprint-override"><code>f=n=>{a=[[]];for(i=1,z=0;z<=n;i++)if(!a.some(b=>b.includes(i))){a[z+1]=[0,...a[z++]||[]].map(v=>i+v)}alert(i-1)}
</code>```

125 bytes:

f=n=>{a=[[]];for(i=1,k=z=0;z<=n;i++)if(a.every(b=>b.every(c=>c-i))){a[i]=[i].concat((a[k]||[]).map(v=>i+v));k=i,z++}alert(k)}
```

Title: Segmented numbers

Body:
Javascript, 125 112 110 bytes

Saved 2 bytes thanks to @Neil

f=n=>{a=[[]];for(i=1,z=0;z<=n;i++)a.some(b=>b.includes(i))||(a[z+1]=[0,...a[z++]||[]].map(v=>i+v));alert(i-1)}

Previous answers

112 bytes thanks to @Neil:

f=n=>{a=[[]];for(i=1,z=0;z<=n;i++)if(!a.some(b=>b.includes(i))){a[z+1]=[0,...a[z++]||[]].map(v=>i+v)}alert(i-1)}

125 bytes:

f=n=>{a=[[]];for(i=1,k=z=0;z<=n;i++)if(a.every(b=>b.every(c=>c-i))){a[i]=[i].concat((a[k]||[]).map(v=>i+v));k=i,z++}alert(k)}


答:
JavaScript (ES6), 77 bytes

```<code>(n,a=[],s=a,i=1)=>s[i]?f(n,a,s,i+1):--n?f(n,[0,...a].map(j=>s[j+=i]=j),s,i):i
</code>```

Basically a recursive port of the algorithm of @TonHospel's Perl answer.

Title: Segmented numbers

Body:
JavaScript (ES6), 77 bytes

(n,a=[],s=a,i=1)=>s[i]?f(n,a,s,i+1):--n?f(n,[0,...a].map(j=>s[j+=i]=j),s,i):i

Basically a recursive port of the algorithm of @TonHospel's Perl answer.


答:
Pyth - 29 bytes

```<code>j+_K.e+*kdjdjF+*bhk*L2>zhkztK
</code>```

Test Suite.

Title: HexaGolf: Wordagons

Body:
See also: Rotatagons

Challenge

Given a string as input, output its wordagon.

Wordagons

A wordagon is a way of representing a string in a hexagon. Now, let's create a wordagon from the string hexa:

Firstly, you start with the first character in the string a place it in the centre:

```<code>h
</code>```

Then, you take the next character in the string and add a hexagonal layer:

```<code> e e
e h e
 e e
</code>```

Then, add the next layer:

```<code>  x x x
 x e e x
x e h e x
 x e e x
  x x x
</code>```

Finally, add the last layer:

```<code>   a a a a
  a x x x a
 a x e e x a
a x e h e x a
 a x e e x a
  a x x x a
   a a a a
</code>```

And you now have the wordagon for the string hexa.

Examples

Here's some I prepared earlier:

hello

```<code>    o o o o o
   o l l l l o
  o l l l l l o
 o l l e e l l o
o l l e h e l l o
 o l l e e l l o
  o l l l l l o
   o l l l l o
    o o o o o
</code>```

PPcg

```<code>   g g g g
  g c c c g
 g c P P c g
g c P P P c g
 g c P P c g
  g c c c g
   g g g g
</code>```

o *

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

(T_T)

```<code>    ) ) ) ) )
   ) T T T T )
  ) T _ _ _ T )
 ) T _ T T _ T )
) T _ T ( T _ T )
 ) T _ T T _ T )
  ) T _ _ _ T )
   ) T T T T )
    ) ) ) ) )
</code>```

Note that trailing and/or leading newlines are allowed.

Winning

The shortest code in bytes wins.

Body:
Pyth - 29 bytes

j+_K.e+*kdjdjF+*bhk*L2>zhkztK

Test Suite.


问:
When is their birthday?
Donald Knuth was born in 1938, on the 20th day of Capricorn.

The first day of Capricorn is the 22nd December.

Donald Knuth was born on the 10th of January (1938).

The challenge

Write a program or function which takes three inputs about a person (any other specified order is fine):

Their (calendar) year of birth (an integer)

Their sign of the zodiac (a string)

- may be whichever you choose from the following, so long as it is consistent:

all lower case except the first character;

all lower case; or

all upper case.

The (1-based) day of the zodiac period on which they were born (an integer)

...and provides two outputs (the other order is fine if specified):

The day of the month on which they were born (an integer)

Their month of birth (an integer)

More details

If your answer were a function, F, then for Donald Knuth we would run F(1938, 'Capricorn', 20) and receive the output (10, 1)

For the purposes of this challenge you do not need to shift the zodiac due to the shift between the Gregorian calendar and the tropical year, but you do need to account correctly for leap years.

February has 29 days rather than 28 on leap years.

A year is usually a leap year if it is divisible by 4 - the exceptions are when it is divisible by 100 but not 400 (so, 1600 and 2000 were, whereas 1700, 1800, and 1900 were not).

For reference the names of the signs of the zodiac and their inclusive ranges are:

```<code>Aries       21 March     – 20 April
Taurus      21 April     – 21 May
Gemini      22 May       – 21 June
Cancer      22 June      – 22 July
Leo         23 July      – 22 August
Virgo       23 August    – 23 September
Libra       24 September – 23 October
Scorpio     24 October   – 22 November
Sagittarius 23 November  – 21 December
Capricorn   22 December  – 20 January
Aquarius    21 January   – 19 February
Pisces      20 February  – 20 March
</code>```

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

No loopholes, yada yada; you know the drill.

Test cases

```<code>Charles Babbage   F(1791, 'Capricorn',  5) -->  (26, 12)
George Boole      F(1815, 'Scorpio',   10) -->  ( 2, 11)
Herman Hollerith  F(1860, 'Pisces',    10) -->  (29,  2)
Vannevar Bush     F(1890, 'Pisces',    20) -->  (11,  3)
Howard H. Aiken   F(1900, 'Pisces',    17) -->  ( 8,  3)  - note 1900 was not a leap year
Donald Knuth      F(1938, 'Capricorn', 20) -->  (10,  1)
<Future Famed>    F(2000, 'Pisces',    17) -->  ( 7,  3)  - note 2000 was a leap year
</code>```

Title: When is their birthday?

Body:
Python 3 - <s>333</s> <s>309</s> <s>299</s> <s>240</s> 238 bytes

from datetime import*
def f(y,s,d):y=datetime(y,1,1)+timedelta((([[[21,80,111,142,173,235,267,297,327,356]['rsuneoapti'.index(s[4])],51][s[2]=='s'],204][len(s)<4])+d)%(365+[[[0,1][y%4==0],0][y%100==0],1][y%400==0])-2);return y.day,y.month

Saved <s>24</s> 26 bytes thanks to @Jonathan Allan


Title: When is their birthday?

Body:
Donald Knuth was born in 1938, on the 20th day of Capricorn.

The first day of Capricorn is the 22nd December.

Donald Knuth was born on the 10th of January (1938).

The challenge

Write a program or function which takes three inputs about a person (any other specified order is fine):

Their (calendar) year of birth (an integer)

Their sign of the zodiac (a string)

- may be whichever you choose from the following, so long as it is consistent:

all lower case except the first character;

all lower case; or

all upper case.

The (1-based) day of the zodiac period on which they were born (an integer)

...and provides two outputs (the other order is fine if specified):

The day of the month on which they were born (an integer)

Their month of birth (an integer)

More details

If your answer were a function, F, then for Donald Knuth we would run F(1938, 'Capricorn', 20) and receive the output (10, 1)

For the purposes of this challenge you do not need to shift the zodiac due to the shift between the Gregorian calendar and the tropical year, but you do need to account correctly for leap years.

February has 29 days rather than 28 on leap years.

A year is usually a leap year if it is divisible by 4 - the exceptions are when it is divisible by 100 but not 400 (so, 1600 and 2000 were, whereas 1700, 1800, and 1900 were not).

For reference the names of the signs of the zodiac and their inclusive ranges are:

```<code>Aries       21 March     – 20 April
Taurus      21 April     – 21 May
Gemini      22 May       – 21 June
Cancer      22 June      – 22 July
Leo         23 July      – 22 August
Virgo       23 August    – 23 September
Libra       24 September – 23 October
Scorpio     24 October   – 22 November
Sagittarius 23 November  – 21 December
Capricorn   22 December  – 20 January
Aquarius    21 January   – 19 February
Pisces      20 February  – 20 March
</code>```

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

No loopholes, yada yada; you know the drill.

Test cases

```<code>Charles Babbage   F(1791, 'Capricorn',  5) -->  (26, 12)
George Boole      F(1815, 'Scorpio',   10) -->  ( 2, 11)
Herman Hollerith  F(1860, 'Pisces',    10) -->  (29,  2)
Vannevar Bush     F(1890, 'Pisces',    20) -->  (11,  3)
Howard H. Aiken   F(1900, 'Pisces',    17) -->  ( 8,  3)  - note 1900 was not a leap year
Donald Knuth      F(1938, 'Capricorn', 20) -->  (10,  1)
<Future Famed>    F(2000, 'Pisces',    17) -->  ( 7,  3)  - note 2000 was a leap year
</code>```

Body:
Javascript (ES6), <s>121</s> <s>120</s> 119 bytes

(y,s,d)=>[(d=new Date(y,m=s[2]=='s'?1:'r.sune0oapti'.search(s[4]||0),23+d-'343322110012'[m])).getDate(),d.getMonth()+1]

Format for the sign of the zodiac is either:

all lower case except the first character

all lower case

Test cases

let f =
(y,s,d)=>[(d=new Date(y,m=s[2]=='s'?1:'r.sune0oapti'.search(s[4]||0),23+d-'343322110012'[m])).getDate(),d.getMonth()+1]

console.log(f(1791, 'Capricorn',  5)); // -->  (26, 12)
console.log(f(1815, 'Scorpio',   10)); // -->  ( 2, 11)
console.log(f(1860, 'Pisces',    10)); // -->  (29,  2)
console.log(f(1890, 'Pisces',    20)); // -->  (11,  3)
console.log(f(1900, 'Pisces',    17)); // -->  ( 8,  3)
console.log(f(1938, 'Capricorn', 20)); // -->  (10,  1)
console.log(f(2000, 'Pisces',    17)); // -->  ( 7,  3)