问:
Character Counting System
GOAL :
 To Implement a character counting program

This is how this counting system works :

input of the program is a set of printable ASCII characters . the program counts each type of character , and outputs the number of each character , starting from first mentioned character to last mentioned character .

Example :

```<code>input : aaaabbbbbcccc    123445b
output : 4 6 4 4 1 1 1 2 1
</code>```

Which 4 is number of as , 6 is number of bs , 4 is number of cs , 4 is number of spaces () and so on . Also you can split answers with space (like example) , EOL , or anything other than numerals .

Rules

Your program must log to STDOUT or an acceptable alternative, if STDOUT is not available.

Your program must be a full, runnable program, and not a function or snippet

It's optional to mention the ungolfed version of program and/or a short explanation  .

Test input :  ThIs Is ThE iNPUT , WITH 72/2 CHARS!

Test output :  4 2 3 2 7 1 1 1 1 1 1 1 2 1 2 1 1 1 1 1 1

答:
C#

```<code>public static void Main(string[] args)
    {
        string str = "aaaabbbbbcccc    123445b";
        Dictionary<char, int> counts = new Dictionary<char, int>();

        for (int i = 0; i < str.Length; i++)
           if (counts.ContainsKey(str[i]))
               counts[str[i]]++;
           else
              counts.Add(str[i], 1);

        foreach (var count in counts)
         Console.WriteLine("{0} = {1}", count.Key, count.Value.ToString());
    }
</code>```

Title: Character Counting System

Body:
C#

public static void Main(string[] args)
    {
        string str = "aaaabbbbbcccc    123445b";
        Dictionary<char, int> counts = new Dictionary<char, int>();

        for (int i = 0; i < str.Length; i++)
           if (counts.ContainsKey(str[i]))
               counts[str[i]]++;
           else
              counts.Add(str[i], 1);

        foreach (var count in counts)
         Console.WriteLine("{0} = {1}", count.Key, count.Value.ToString());
    }


问:
Counting in bijective base 62
The task is to generate all the strings from 'a' to '999' including upper case characters like so:

```<code>'a', 'b', 'c' ... 'y', 'z', 'A', 'B', 'C' ... 'Y', 'Z', '0', '1', 2' ...
'8', '9', 'aa', 'ab', 'ac' ... 'az', 'aA', 'aB' ... 'aZ', 'a0' ... 'a9', 'ba'
</code>```

and so on (filling in the gaps), optionally starting with the empty string.

Input:

The amount of consecutive characters the program has to print up to.

Output:

An array containing each string OR one string per line

Clarifications:

The order doesn't matter, you can print uppercase or lowercase letters first if you want.

The output can return any type of enumerable, doesn't have to be an array specifically, although I doubt printing all the combinations won't be the easiest way to go.

An input of 3 would print all the string from 'a' (or '') to '999'‚ an input of 5 up to '99999' and so on.

答:
J, 50 bytes

```<code>62&(('0123456789',~(,toupper)u:97+i.26){~#~#:i.@^)
</code>```

Half of the bytes, 25 to be exact, are spent generating the letters and digits needed.

ContentLicense: CC BY-SA 3.0

Title: Counting in bijective base 62

Body:
J, 50 bytes

62&(('0123456789',~(,toupper)u:97+i.26){~#~#:i.@^)

Half of the bytes, 25 to be exact, are spent generating the letters and digits needed.


答:
ES6, 90 bytes

a=prompt();b=new Map();for(c of a)b.set(c,(b.get(c)|0)+1);alert([...b.values()].join(' '))```

Title: Character Counting System

Body:
GOAL :
 To Implement a character counting program

This is how this counting system works :

input of the program is a set of printable ASCII characters . the program counts each type of character , and outputs the number of each character , starting from first mentioned character to last mentioned character .

Example :

```<code>input : aaaabbbbbcccc    123445b
output : 4 6 4 4 1 1 1 2 1
</code>```

Which 4 is number of as , 6 is number of bs , 4 is number of cs , 4 is number of spaces () and so on . Also you can split answers with space (like example) , EOL , or anything other than numerals .

Rules

Your program must log to STDOUT or an acceptable alternative, if STDOUT is not available.

Your program must be a full, runnable program, and not a function or snippet

It's optional to mention the ungolfed version of program and/or a short explanation  .

Test input :  ThIs Is ThE iNPUT , WITH 72/2 CHARS!

Test output :  4 2 3 2 7 1 1 1 1 1 1 1 2 1 2 1 1 1 1 1 1


答:
Python 3, <s>76</s> 73 bytes

3 bytes shorter:

```<code>s,a=input(),[]
for y in s:a+=(y,'')[y in a]
print([s.count(x)for x in a])
</code>```

Old version:

```<code>s=input();print([s.count(x)for x in sorted(set(s),key=lambda i:s.index(i))])
</code>```

Iterates over a sorted set of unique characters from the input, counts the occurrences, and outputs a list of the counts.

Title: Character Counting System

Body:
Python 3, <s>76</s> 73 bytes

3 bytes shorter:

s,a=input(),[]
for y in s:a+=(y,'')[y in a]
print([s.count(x)for x in a])

Old version:

s=input();print([s.count(x)for x in sorted(set(s),key=lambda i:s.index(i))])

Iterates over a sorted set of unique characters from the input, counts the occurrences, and outputs a list of the counts.


答:
Python 3, <s>134</s> 81 bytes

```<code>s,r=input(),[]
for c in s:
 k,s=s.count(c),s.replace(c,'')
 if k:r+=[k]
print(*r)
</code>```

Output:

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

Not that short :(

Another approach: 109 bytes

Not shorter than the others but the counting happens in a one-liner.

```<code>s=input()
k=[i[1]for i in sorted({i:str(s.count(i))for i in s}.items(),key=lambda v:s.index(v[0]))]
print(*k)
</code>```

Edit: Golfed 53 bytes thanks to @Dr Green Eggs and Iron Man
Edit 2: Added one-liner method

Title: Character Counting System

Body:
Python 3, <s>134</s> 81 bytes

s,r=input(),[]
for c in s:
 k,s=s.count(c),s.replace(c,'')
 if k:r+=[k]
print(*r)

Output:

4 2 3 2 7 1 1 1 1 1 1 1 2 1 2 1 1 1 1 1 1

Not that short :(

Another approach: 109 bytes

Not shorter than the others but the counting happens in a one-liner.

s=input()
k=[i[1]for i in sorted({i:str(s.count(i))for i in s}.items(),key=lambda v:s.index(v[0]))]
print(*k)

Edit: Golfed 53 bytes thanks to @Dr Green Eggs and Iron Man
Edit 2: Added one-liner method


问:
Play scrabble with the periodic table
You've got a set of tiles with the symbols from the periodic table. Each symbol appears once. You're thinking up words to make but you want to know if it's possible or not.

The Challenge

Write a program in your favourite language that will take in a string as an input parameter. You may assume that input is not null, has no spaces and consists of ASCII characters.

Your program should take that string and output a truthy value if that word can made up of symbols from the periodic table of elements, and a falsey value if the word cannot.

To make this challenge more difficult, you may not use a symbol twice. So if you use Nitrogen N you may not use N again in the same word.

Rules

Standard loopholes are not allowed. You may use symbols from elements 1-118 (Hydrogen to Ununoctium). You can find a list of all the elements here. You may read the list of symbols in from a file or input arguments if you wish.

Test Cases:

```<code>Laos - true (LaOs)
Amputation - true (AmPuTaTiON)
Heinous - true (HeINoUS)
Hypothalamus - true (HYPoThAlAmUS)
Singapore - true (SiNGaPoRe)
Brainfuck - true (BRaInFUCK)
Candycane - false
</code>```

This is a code golf challenge, shortest code wins.

BEFORE YOU CLOSE AS DUPLICATE: While this may seem similar to this challenge, I feel it is different because it is not 'Generate a list of all words that are possible from the periodic table', it is 'Take in arbitrary input and determine if it can be made from the periodic table'

答:
Brachylog, 7 bytes

```<code>spc~@l.
</code>```

Call with the list of symbols (all lowercase) as Input, and the word as Output, e.g. run_from_atom('spc~@l.', ["he":"n":"o":"li"], "Nohe"). .

Warning: this is extremely inefficent when all symbols are in the list.

Explanation

```<code>spc        Create a string from a permutation of a subset of the Input
   ~@l.    This string can unify with the lowercase version of the Output
</code>```

Title: Play scrabble with the periodic table

Body:
Brachylog, 7 bytes

spc~@l.

Call with the list of symbols (all lowercase) as Input, and the word as Output, e.g. run_from_atom('spc~@l.', ["he":"n":"o":"li"], "Nohe"). .

Warning: this is extremely inefficent when all symbols are in the list.

Explanation

spc        Create a string from a permutation of a subset of the Input
   ~@l.    This string can unify with the lowercase version of the Output


答:
Python 2.7 - 103 Bytes (Ungolfed)

```<code>i=list(raw_input())
print ''.join([str(e) for e in map(lambda x,y:x!=y and i.count(x)or' ',i,['']+i) ])
</code>```

edit: Thanks to Dr Green Eggs and Iron Man for helping to reduce 47 Bytes!

Title: Character Counting System

Body:
Python 2.7 - 103 Bytes (Ungolfed)

i=list(raw_input())
print ''.join([str(e) for e in map(lambda x,y:x!=y and i.count(x)or' ',i,['']+i) ])

edit: Thanks to Dr Green Eggs and Iron Man for helping to reduce 47 Bytes!


答:
Jelly, 4 bytes

```<code>Qċ@€
</code>```

Try it online

Explanation

```<code>Qċ@€   Main link. Argument: S

Q      Remove duplicate characters from S.
       Current value v contains each character of S once sorted by first appearance.
  @€   For each character in v.
 ċ       count its occurrence in S.
</code>```

Title: Character Counting System

Body:
Jelly, 4 bytes

Qċ@€

Try it online

Explanation

Qċ@€   Main link. Argument: S

Q      Remove duplicate characters from S.
       Current value v contains each character of S once sorted by first appearance.
  @€   For each character in v.
 ċ       count its occurrence in S.


问:
The plus-minus sequence

The plus-minus sequence

The plus-minus sequence is one that starts with two seeds, a(0) and b(0). Each iteration of this sequence is the addition and subtraction of the previous two members of the sequence. That is, a(N) = a(N-1) + b(N-1) and b(N) = a(N-1) - b(N-1).

Objective Produce the plus-minus sequence, in infinitude or the first K steps given K. You may do this using an infinite output program, a generator, or a function/program that gives the first K steps. The output order does not matter, so long as it is consistent. (I.e., b(K) a(K) or a(K) b(K), with some non-numeric, non-newline separator in between.) The output must start with the input.

Test cases

For inputs 10 2 (of a(0) b(0), this is a possible output for the first K approach (or a subsection of the infinite approach):

```<code>10     2
12     8
20     4
24     16
40     8
48     32
80     16
96     64
160    32
192    128
320    64
384    256
640    128
768    512
1280   256
1536   1024
2560   512
3072   2048
5120   1024
6144   4096
10240  2048
12288  8192
20480  4096
24576  16384
40960  8192
49152  32768
81920  16384
98304  65536
</code>```

For inputs 2 20 10 (a(0) b(0) k):

```<code>2     20
22   -18
4     40
44   -36
8     80
88   -72
16    160
176  -144
32    320
352  -288
</code>```

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

Catalog

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

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

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

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

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

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

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

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

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

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

Shortest Solution by Language

Language	User	Score

Leaderboard

	Author	Language	Size

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

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

```

ContentLicense: CC BY-SA 4.0

Title: The plus-minus sequence

Body:
APL, 37 chars

{⍺←3⊃3↑⍵⋄⎕←z←2↑⍵⋄⍺=1:⋄(⍺-1)∇(+/,-/)z}

Can be used as

    {⍺←3⊃3↑⍵⋄⎕←z←2↑⍵⋄⍺=1:⋄(⍺-1)∇(+/,-/)z} 10 2
10 2
12 8
20 4
24 16
40 8
48 32
80 16
[...]

or

      {⍺←3⊃3↑⍵⋄⎕←z←2↑⍵⋄⍺=1:⋄(⍺-1)∇(+/,-/)z} 10 2 6
10 2
12 8
20 4
24 16
40 8
48 32


问:
Given a number, program must return the alphabet letter correspondent

The program

Given a number, program must return the alphabet letter correspondent.

Rules

The challenge here is to make it as short as possible, everyone knows it is a very easy program to do.

The number is not zero-based, it means 1 is A, 2 is B, 3 is C and so it goes...

Any language will be accepted.

答:
GolfScript, 7

64+]''+
```

<h3>Commentary</h3>

<pre class="lang-golfscript prettyprint-override"><code>64    # corresponds to '@' in ASCII (65 is 'A')
+]    # add the input to 64. ']' is used for ASCII.
''+   # the conversion process
</code>```

1 corresponds to A

26 corresponds to Z

Body:
GolfScript, 7

64+]''+

Commentary

64    # corresponds to '@' in ASCII (65 is 'A')
+]    # add the input to 64. ']' is used for ASCII.
''+   # the conversion process

1 corresponds to A

26 corresponds to Z


答:
J, <s>16</s> 12 bytes

```<code>0&(]+/,-/)~<
</code>```

Produces only the first k values for the sequence based on the given seeds.

Saved 4 bytes using the trick (or syntactic sugar) shown by @randomra in this comment.

Usage

```<code>   f =: 0&(]+/,-/)~<
   2 20 f 10
  2   20
 22  _18
  4   40
 44  _36
  8   80
 88  _72
 16  160
176 _144
 32  320
352 _288
</code>```

Title: The plus-minus sequence

Body:
The plus-minus sequence

The plus-minus sequence is one that starts with two seeds, a(0) and b(0). Each iteration of this sequence is the addition and subtraction of the previous two members of the sequence. That is, a(N) = a(N-1) + b(N-1) and b(N) = a(N-1) - b(N-1).

Objective Produce the plus-minus sequence, in infinitude or the first K steps given K. You may do this using an infinite output program, a generator, or a function/program that gives the first K steps. The output order does not matter, so long as it is consistent. (I.e., b(K) a(K) or a(K) b(K), with some non-numeric, non-newline separator in between.) The output must start with the input.

Test cases

For inputs 10 2 (of a(0) b(0), this is a possible output for the first K approach (or a subsection of the infinite approach):

```<code>10     2
12     8
20     4
24     16
40     8
48     32
80     16
96     64
160    32
192    128
320    64
384    256
640    128
768    512
1280   256
1536   1024
2560   512
3072   2048
5120   1024
6144   4096
10240  2048
12288  8192
20480  4096
24576  16384
40960  8192
49152  32768
81920  16384
98304  65536
</code>```

For inputs 2 20 10 (a(0) b(0) k):

```<code>2     20
22   -18
4     40
44   -36
8     80
88   -72
16    160
176  -144
32    320
352  -288
</code>```

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

Catalog

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

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

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

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

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

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

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

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

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

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

Shortest Solution by Language

Language	User	Score

Leaderboard

	Author	Language	Size

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

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

```

Body:
J, <s>16</s> 12 bytes

0&(]+/,-/)~<

Produces only the first k values for the sequence based on the given seeds.

Saved 4 bytes using the trick (or syntactic sugar) shown by @randomra in this comment.

Usage

   f =: 0&(]+/,-/)~<
   2 20 f 10
  2   20
 22  _18
  4   40
 44  _36
  8   80
 88  _72
 16  160
176 _144
 32  320
352 _288


问:
Convert YYYYMM to MMMYY
Basing on this SO question.

Challenge is rather simple: given a date period in the format YYYYMM output it in the format MMMYY.

Rules:

The input will be a number or a string exactly 6 characters long, consisting only of digits.

Last two digits will be between 01 and 12.

Output must be in the form MMMYY, where MMM represents uppercase three-letter code for the month (below) and YY represents two last digits of the YYYY part of the input.

List of months with corresponding code:

```<code>MM    MMM
01    JAN
02    FEB
03    MAR
04    APR
05    MAY
06    JUN
07    JUL
08    AUG
09    SEP
10    OCT
11    NOV
12    DEC
</code>```

Examples:

```<code>Input     Output
201604    APR16
200001    JAN00
000112    DEC01
123405    MAY34
</code>```

答:
jq, 35 characters

(34 characters code + 1 character command-line option.)

(Just tried whether the ^ trick used by Digital Trauma in his Bash answer works in jq too. Works. Now you know who inspired the most important character of this answer. (The alternative is to use the ascii_upcase function.))

```<code>strptime("%Y%m")|strftime("%^b%y")
</code>```

Sample run (Option -R used only in this sample to pass all test cases.)

```<code>bash-4.3$ jq -Rr 'strptime("%Y%m")|strftime("%^b%y")' <<END
201604
200001
000112
123405
END
APR16
JAN00
DEC01
MAY34
</code>```

On-line test: (Passing -R through URL is not supported – so input passed as JSON string literal. Passing -r through URL is not supported – check Raw Output yourself.)

200001

000112

Title: Convert YYYYMM to MMMYY

Body:
jq, 35 characters

(34 characters code + 1 character command-line option.)

(Just tried whether the ^ trick used by Digital Trauma in his Bash answer works in jq too. Works. Now you know who inspired the most important character of this answer. (The alternative is to use the ascii_upcase function.))

strptime("%Y%m")|strftime("%^b%y")

Sample run (Option -R used only in this sample to pass all test cases.)

bash-4.3$ jq -Rr 'strptime("%Y%m")|strftime("%^b%y")' <<END
201604
200001
000112
123405
END
APR16
JAN00
DEC01
MAY34

On-line test: (Passing -R through URL is not supported – so input passed as JSON string literal. Passing -r through URL is not supported – check Raw Output yourself.)

200001

000112


答:
Pyth - 13 bytes

Just checks if any partition of lowercased input has all parts in the periodic table.

```<code>sm.A}RQd./rzZ
</code>```

On mobile, so couldn't set up an actual test suite, but try this.

Title: Play scrabble with the periodic table

Body:
You've got a set of tiles with the symbols from the periodic table. Each symbol appears once. You're thinking up words to make but you want to know if it's possible or not.

The Challenge

Write a program in your favourite language that will take in a string as an input parameter. You may assume that input is not null, has no spaces and consists of ASCII characters.

Your program should take that string and output a truthy value if that word can made up of symbols from the periodic table of elements, and a falsey value if the word cannot.

To make this challenge more difficult, you may not use a symbol twice. So if you use Nitrogen N you may not use N again in the same word.

Rules

Standard loopholes are not allowed. You may use symbols from elements 1-118 (Hydrogen to Ununoctium). You can find a list of all the elements here. You may read the list of symbols in from a file or input arguments if you wish.

Test Cases:

```<code>Laos - true (LaOs)
Amputation - true (AmPuTaTiON)
Heinous - true (HeINoUS)
Hypothalamus - true (HYPoThAlAmUS)
Singapore - true (SiNGaPoRe)
Brainfuck - true (BRaInFUCK)
Candycane - false
</code>```

This is a code golf challenge, shortest code wins.

BEFORE YOU CLOSE AS DUPLICATE: While this may seem similar to this challenge, I feel it is different because it is not 'Generate a list of all words that are possible from the periodic table', it is 'Take in arbitrary input and determine if it can be made from the periodic table'

Body:
Pyth - 13 bytes

Just checks if any partition of lowercased input has all parts in the periodic table.

sm.A}RQd./rzZ

On mobile, so couldn't set up an actual test suite, but try this.


问:
Swap prime exponents with their neighbours
(Follow-up to my question about swapping bits with their neighbours.)

Task

Given a positive integer x = (2a · 3b) · (5c · 7d) · (11e · 13f) · …, print the integer obtained by swapping the exponents in this factorization for each successive pair of primes, y = (2b · 3a) · (5d · 7c) · (11f · 13e) · …

A061898 in the OEIS. This is code-golf, so the shortest program (in bytes) wins!

Test cases

```<code>1 -> 1
2 -> 3
3 -> 2
10 -> 21
37 -> 31
360 -> 756
12345 -> 11578
67895678 -> 125630871
</code>```

答:
05AB1E, 22 bytes

```<code>Ó¾‚˜2ô€R˜DgL<Ø)øvy`smP
</code>```

Explained

```<code>Ó¾‚˜                    # list of primeexponents with a 0 appended: n=10 -> [1,0,1,0]
    2ô                  # split into pairs: [[1,0],[1,0]]
      €R˜               # reverse each pair and flatten: [0,1,0,1]
         DgL<Ø          # get list of primes corresponding to the exponents: [2,3,5,7]
              )ø        # zip lists: [[0,2],[1,3],[0,5],[1,7]]
                vy`sm   # raise each prime to its new exponent: [1,3,1,7]
                     P  # product: 21
</code>```

Try it online

Body:
05AB1E, 22 bytes

Ó¾‚˜2ô€R˜DgL<Ø)øvy`smP

Explained

Ó¾‚˜                    # list of primeexponents with a 0 appended: n=10 -> [1,0,1,0]
    2ô                  # split into pairs: [[1,0],[1,0]]
      €R˜               # reverse each pair and flatten: [0,1,0,1]
         DgL<Ø          # get list of primes corresponding to the exponents: [2,3,5,7]
              )ø        # zip lists: [[0,2],[1,3],[0,5],[1,7]]
                vy`sm   # raise each prime to its new exponent: [1,3,1,7]
                     P  # product: 21

Try it online


答:
Java 7, <s>172</s> 168 bytes

```<code>class M{public static void main(String[]a){int[]m=new int[256];byte[]b=a[0].getBytes();for(int z:b)m[z]++;for(int z:b){System.out.print(m[z]>0?(m[z]+" "):"");m[z]=0;}}}
</code>```

Stores number of occurrences in an int array, then for each char print number of occurrences and replace this value with zero so it won't be printed again.

Whitespaces and comments added:

```<code>class M{
    public static void main(String[]a){
        int[]m=new int[256]; // map, ascii value to number of occurrences
        byte[b]=a[0].getBytes();
        for(int z:b)m[z]++; // count number of occurrences
        for(int z:b){
            System.out.print(m[z]>0?(m[z]+" "):""); // print result
            m[z]=0; // make it not be printed again
        }
    }
}
</code>```

See it online: https://ideone.com/7X58F9

Title: Character Counting System

Body:
Java 7, <s>172</s> 168 bytes

class M{public static void main(String[]a){int[]m=new int[256];byte[]b=a[0].getBytes();for(int z:b)m[z]++;for(int z:b){System.out.print(m[z]>0?(m[z]+" "):"");m[z]=0;}}}

Stores number of occurrences in an int array, then for each char print number of occurrences and replace this value with zero so it won't be printed again.

Whitespaces and comments added:

class M{
    public static void main(String[]a){
        int[]m=new int[256]; // map, ascii value to number of occurrences
        byte[b]=a[0].getBytes();
        for(int z:b)m[z]++; // count number of occurrences
        for(int z:b){
            System.out.print(m[z]>0?(m[z]+" "):""); // print result
            m[z]=0; // make it not be printed again
        }
    }
}

See it online: https://ideone.com/7X58F9


问:
Bytes/Character

Task

Given a UTF-8 string (by any means) answer (by any means) an equivalent list where every element is the number of bytes used to encode the corresponding input character.

Examples

! → 1

Ciao → 1 1 1 1

tʃaʊ → 1 2 1 2

Adám → 1 1 2 1

ĉaŭ → 2 1 2 (single characters)

ĉaŭ → 1 2 1 1 2 (uses combining overlays)

チャオ → 3 3 3

 (empty input) →  (empty output)

!±≡ → 1 2 3 4

� (a null byte) → 1

Null bytes

If the only way to keep reading input beyond null bytes is by knowing the total byte count, you may get the byte count by any means (even user input).

If your language cannot handle null bytes at all, you may assume the input does not contain nulls.

答:
JavaScript (ES6), <s>54</s> <s>45</s> 43 bytes

```<code>s=>[...s].map(c=>encodeURI(c).length/3-8&7)
</code>```

Edit: Saved 2 bytes with help from @l4m2.

Title: Bytes/Character

Body:
JavaScript (ES6), <s>54</s> <s>45</s> 43 bytes

s=>[...s].map(c=>encodeURI(c).length/3-8&7)

Edit: Saved 2 bytes with help from @l4m2.


答:
APL, 15 chars

```<code>≢¨'UTF-8'∘⎕ucs¨
</code>```

In English: convert each character to UTF-8 (meaning: vector of bytes representation) and get its tally.

Title: Bytes/Character

Body:
Task

Given a UTF-8 string (by any means) answer (by any means) an equivalent list where every element is the number of bytes used to encode the corresponding input character.

Examples

! → 1

Ciao → 1 1 1 1

tʃaʊ → 1 2 1 2

Adám → 1 1 2 1

ĉaŭ → 2 1 2 (single characters)

ĉaŭ → 1 2 1 1 2 (uses combining overlays)

チャオ → 3 3 3

 (empty input) →  (empty output)

!±≡ → 1 2 3 4

� (a null byte) → 1

Null bytes

If the only way to keep reading input beyond null bytes is by knowing the total byte count, you may get the byte count by any means (even user input).

If your language cannot handle null bytes at all, you may assume the input does not contain nulls.

Body:
APL, 15 chars

≢¨'UTF-8'∘⎕ucs¨

In English: convert each character to UTF-8 (meaning: vector of bytes representation) and get its tally.


答:
Python 3, 93 bytes

```<code>s=input();c,o=[],""
for i in s:
 if i not in c:c+=i
for i in c:o+=str(s.count(i))+" "
print o
</code>```

Title: Character Counting System

Body:
GOAL :
 To Implement a character counting program

This is how this counting system works :

input of the program is a set of printable ASCII characters . the program counts each type of character , and outputs the number of each character , starting from first mentioned character to last mentioned character .

Example :

```<code>input : aaaabbbbbcccc    123445b
output : 4 6 4 4 1 1 1 2 1
</code>```

Which 4 is number of as , 6 is number of bs , 4 is number of cs , 4 is number of spaces () and so on . Also you can split answers with space (like example) , EOL , or anything other than numerals .

Rules

Your program must log to STDOUT or an acceptable alternative, if STDOUT is not available.

Your program must be a full, runnable program, and not a function or snippet

It's optional to mention the ungolfed version of program and/or a short explanation  .

Test input :  ThIs Is ThE iNPUT , WITH 72/2 CHARS!

Test output :  4 2 3 2 7 1 1 1 1 1 1 1 2 1 2 1 1 1 1 1 1

Body:
Python 3, 93 bytes

s=input();c,o=[],""
for i in s:
 if i not in c:c+=i
for i in c:o+=str(s.count(i))+" "
print o


Body:
The program

Given a number, program must return the alphabet letter correspondent.

Rules

The challenge here is to make it as short as possible, everyone knows it is a very easy program to do.

The number is not zero-based, it means 1 is A, 2 is B, 3 is C and so it goes...

Any language will be accepted.

Body:
Brainfuck, 107 bytes

>,----------[>++++++[-<------>],----------]<[<]>>[<--[->++++++++++<]>>]+++++++[-<+++++++++>]<-.>++++++++++.


答:
Python 3, <s>42</s> 36 bytes

```<code>lambda x:[len(i.encode())for i in x]
</code>```

Title: Bytes/Character

Body:
Python 3, <s>42</s> 36 bytes

lambda x:[len(i.encode())for i in x]


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

```<code>string C(string s)=>System.DateTime.Parse(s.Insert(4,"-")).ToString("MMMyy").ToUpper();
</code>```

Saved 7 bytes by using C#6 Syntax.

Try Online

Title: Convert YYYYMM to MMMYY

Body:
Basing on this SO question.

Challenge is rather simple: given a date period in the format YYYYMM output it in the format MMMYY.

Rules:

The input will be a number or a string exactly 6 characters long, consisting only of digits.

Last two digits will be between 01 and 12.

Output must be in the form MMMYY, where MMM represents uppercase three-letter code for the month (below) and YY represents two last digits of the YYYY part of the input.

List of months with corresponding code:

```<code>MM    MMM
01    JAN
02    FEB
03    MAR
04    APR
05    MAY
06    JUN
07    JUL
08    AUG
09    SEP
10    OCT
11    NOV
12    DEC
</code>```

Examples:

```<code>Input     Output
201604    APR16
200001    JAN00
000112    DEC01
123405    MAY34
</code>```

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

string C(string s)=>System.DateTime.Parse(s.Insert(4,"-")).ToString("MMMyy").ToUpper();

Saved 7 bytes by using C#6 Syntax.

Try Online


答:
Pyth, 17 bytes

```<code>mhxS+11+16,7lCdlC
</code>```

Try it online!

Use the code-point of the characters with some arithmetics.

Title: Bytes/Character

Body:
Pyth, 17 bytes

mhxS+11+16,7lCdlC

Try it online!

Use the code-point of the characters with some arithmetics.


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

Thanks to @Maltysen for saving 2 bytes!

```<code>mlc.Bd8
</code>```

Test suite

Converts every character of the input to it's binary representation and then splits this into chunks of length 8. The number of those chunks is then the amount of bytes needed to encode that character.

Title: Bytes/Character

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

Thanks to @Maltysen for saving 2 bytes!

mlc.Bd8

Test suite

Converts every character of the input to it's binary representation and then splits this into chunks of length 8. The number of those chunks is then the amount of bytes needed to encode that character.


答:
R, <s>154</s> <s>150</s> <s>114</s> 112 bytes

Takes six digit input into "b", separates the first four digits from the last two digits, abbreviates the 2-digit month and makes it uppercase, and concatenates it with the 3rd and 4th digit.

Golfed:

```<code>function(b){h=substr;i=sprintf;o="%06d";cat(toupper(month.abb[as.numeric(h(i(o,b),5,6))]),h(i(o,b),3,4),sep="")}
</code>```

Ungolfed:

```<code>function(b){
   h=substr;i=sprintf;o="%06d";

   cat(
      toupper(month.abb[as.numeric(h(i(o,b),5,6))]),
      h(i(o,b),3,4),
   sep="")
}
</code>```

EDITS: replaced duplicitous names with variables; fixed me being stupid. -2 bytes by turning function anonymous (thanks, cat).

Title: Convert YYYYMM to MMMYY

Body:
R, <s>154</s> <s>150</s> <s>114</s> 112 bytes

Takes six digit input into "b", separates the first four digits from the last two digits, abbreviates the 2-digit month and makes it uppercase, and concatenates it with the 3rd and 4th digit.

Golfed:

function(b){h=substr;i=sprintf;o="%06d";cat(toupper(month.abb[as.numeric(h(i(o,b),5,6))]),h(i(o,b),3,4),sep="")}

Ungolfed:

function(b){
   h=substr;i=sprintf;o="%06d";

   cat(
      toupper(month.abb[as.numeric(h(i(o,b),5,6))]),
      h(i(o,b),3,4),
   sep="")
}

EDITS: replaced duplicitous names with variables; fixed me being stupid. -2 bytes by turning function anonymous (thanks, cat).


答:
Matlab, 47 chars

```<code>@(y)arrayfun(@(x)sum(y==x),unique(y,'stable'))
</code>```

Reasonably straightforward, though the default behavior of Matlab's unique function to sort the values makes the function rather longer.

Title: Character Counting System

Body:
Matlab, 47 chars

@(y)arrayfun(@(x)sum(y==x),unique(y,'stable'))

Reasonably straightforward, though the default behavior of Matlab's unique function to sort the values makes the function rather longer.


答:
Java 10, <s>100</s> <s>96</s> <s>95</s> <s>67</s> 61 bytes

a->{for(var c:a)System.out.print(c.getBytes("utf8").length);}
```
<p>-4 bytes removing spaces because this is allowed in the comments<br />
-1 byte changing <code>UTF-8</code> to <code>utf8</code><br />
-28 bytes going from Java 7 to 8 (<code>a->{...}</code> instead of <code>void c(char[]i)throws Exception{...}</code>)<br />
-3 bytes taking the input as String-array instead of character-array, and<br />
-3 bytes going from Java 8 to 10 (<code>var</code> instead of <code>String</code>)</p>
<p><strong>Explanation:</strong></p>
<p>Try it online.</p>
<pre class="lang-java prettyprint-override"><code>a->{                      // Method with String-array parameter and no return-type
  for(var c:a)            //  Loop over the input-array
    System.out.print(     //   Print:
      c.getBytes("utf8")  //    The bytes as array in UTF-8 of the current item,
       .length);}         //    and print the amount of bytes in this array
</code>```

Title: Bytes/Character

Body:
Java 10, <s>100</s> <s>96</s> <s>95</s> <s>67</s> 61 bytes

a->{for(var c:a)System.out.print(c.getBytes("utf8").length);}

-4 bytes removing spaces because this is allowed in the comments

-1 byte changing UTF-8 to utf8

-28 bytes going from Java 7 to 8 (a->{...} instead of void c(char[]i)throws Exception{...})

-3 bytes taking the input as String-array instead of character-array, and

-3 bytes going from Java 8 to 10 (var instead of String)

Explanation:

Try it online.

a->{                      // Method with String-array parameter and no return-type
  for(var c:a)            //  Loop over the input-array
    System.out.print(     //   Print:
      c.getBytes("utf8")  //    The bytes as array in UTF-8 of the current item,
       .length);}         //    and print the amount of bytes in this array


答:
PowerShell v4, 58 bytes

```<code>[char[]]$args[0]|%{[Text.Encoding]::UTF8.GetByteCount($_)}
</code>```

NB

OK, this should work, and does in almost all of the test cases except for  which is somehow counted as 3,3 on my machine. That character even shows as 7 bytes on my computer. I suspect this is due to some sort of bug in the Windows or .NET version that I'm running locally, as @Mego doesn't have that issue. (Edit: @cat points out this is due to BOM. Thanks for solving that mystery, @cat!)

However, that still doesn't account for all of the problem. I think I know where some of the problems are coming from, though. Inside .NET, all strings are composed of UTF-16 code units (which is the System.Char type). With the very loose typecasting that PowerShell uses, there's a lot of implicit casting and conversion between types in the background. Likely this is a contributing factor to the behavior we're seeing -- for example, [system.text.encoding]::utf8.getchars([System.Text.UTF8Encoding]::UTF8.GetBytes('')) returns two unprintables, rather than a single character.

Explanation

Very straightforward code. Takes the input $args[0] and explicitly casts it as a char-array so we can loop through each component of the string |%{...}. Each iteration, we use the .NET call [System.Text.Encoding]::UTF8.GetByteCount() (the System. is implied) to get the byte count of the current character $_. That's placed on the pipeline for later output. Since it's a collection of [int]s that are returned, casting to an array is implicit.

Test Runs

```<code>PS C:\Tools\Scripts\golfing> .\bytes-per-character.ps1 'tʃaʊ'
1
2
1
2

PS C:\Tools\Scripts\golfing> .\bytes-per-character.ps1 'Adám'
1
1
2
1

PS C:\Tools\Scripts\golfing> .\bytes-per-character.ps1 'ĉaŭ'
2
1
2

PS C:\Tools\Scripts\golfing> .\bytes-per-character.ps1 'ĉaŭ'
1
2
1
1
2

PS C:\Tools\Scripts\golfing> .\bytes-per-character.ps1 'チャオ'
3
3
3

PS C:\Tools\Scripts\golfing> .\bytes-per-character.ps1 '!±≡'
1
2
3
3
3
</code>```

Edited to add This does properly account for the null-bytes requirement that was added to the challenge after I originally posted, provided you pull the data from a text file and pipe it as follows:

```<code>PS C:\Tools\Scripts\golfing> gc .\z.txt -Encoding UTF8|%{.\bytes-per-character.ps1 $_}
2
1
1
1
</code>```

Title: Bytes/Character

Body:
PowerShell v4, 58 bytes

[char[]]$args[0]|%{[Text.Encoding]::UTF8.GetByteCount($_)}

NB

OK, this should work, and does in almost all of the test cases except for  which is somehow counted as 3,3 on my machine. That character even shows as 7 bytes on my computer. I suspect this is due to some sort of bug in the Windows or .NET version that I'm running locally, as @Mego doesn't have that issue. (Edit: @cat points out this is due to BOM. Thanks for solving that mystery, @cat!)

However, that still doesn't account for all of the problem. I think I know where some of the problems are coming from, though. Inside .NET, all strings are composed of UTF-16 code units (which is the System.Char type). With the very loose typecasting that PowerShell uses, there's a lot of implicit casting and conversion between types in the background. Likely this is a contributing factor to the behavior we're seeing -- for example, [system.text.encoding]::utf8.getchars([System.Text.UTF8Encoding]::UTF8.GetBytes('')) returns two unprintables, rather than a single character.

Explanation

Very straightforward code. Takes the input $args[0] and explicitly casts it as a char-array so we can loop through each component of the string |%{...}. Each iteration, we use the .NET call [System.Text.Encoding]::UTF8.GetByteCount() (the System. is implied) to get the byte count of the current character $_. That's placed on the pipeline for later output. Since it's a collection of [int]s that are returned, casting to an array is implicit.

Test Runs

PS C:\Tools\Scripts\golfing> .\bytes-per-character.ps1 'tʃaʊ'
1
2
1
2

PS C:\Tools\Scripts\golfing> .\bytes-per-character.ps1 'Adám'
1
1
2
1

PS C:\Tools\Scripts\golfing> .\bytes-per-character.ps1 'ĉaŭ'
2
1
2

PS C:\Tools\Scripts\golfing> .\bytes-per-character.ps1 'ĉaŭ'
1
2
1
1
2

PS C:\Tools\Scripts\golfing> .\bytes-per-character.ps1 'チャオ'
3
3
3

PS C:\Tools\Scripts\golfing> .\bytes-per-character.ps1 '!±≡'
1
2
3
3
3

Edited to add This does properly account for the null-bytes requirement that was added to the challenge after I originally posted, provided you pull the data from a text file and pipe it as follows:

PS C:\Tools\Scripts\golfing> gc .\z.txt -Encoding UTF8|%{.\bytes-per-character.ps1 $_}
2
1
1
1


问:
Write a chicken interpreter!
You have to write an interpreter for a cool language called Chicken!

You should read a Chicken program from a file, standard input, program or function arguments, or whatever is most convenient for your language, as well as input to the program.

You should print or return the result of interpreting the program according to the Chicken language specification.

More description about the language.

Chicken Program Overview

Chicken operates on a single stack, which composes its entire memory model. As instructions are executed, the program will push and pop values from the stack, but there are also instructions that allow the program to modify other parts of the stack at will.

There are three segments in the stack:

The registers, at indices 0 and 1. Index 0 is a reference to the stack itself, and index 1 is a reference to the user input. Mostly used for instruction 6 (see below).

The loaded code: for each line of code there is cell in this segment that contains the number of "chicken"s in the line. This is padded with a 0 (opcode for terminate program) at the end.

The actual program stack, where values are pushed/popped as the program runs. Note that the segments are not isolated, which means that it is possible to create self-modifying code or execute code from this segment of the stack space.

The Chicken ISA

Chicken's instruction set is based around the number of times the word "chicken" appears on each line of the program. An empty line terminates the program and prints the topmost value in the stack.

The Chicken instruction set, by number of "chicken"s per line:

Push the literal string "chicken" to the stack

Add top two stack values as natural numbers and push the result.

Subtract top two values as natural numbers and push the result.

Multiply top two values as natural numbers and push the result.

Compare two top values for equality, push 1 if they are equal and 0 otherwise.

Look at the next instruction to determine which source to load from: 0 loads from stack, 1 loads from user input. Top of stack points to address/index to load from the given source; load that value and push it onto stack. Since this is a double wide instruction, the instruction pointer skips the instruction used to determine the source.

Top of stack points to address/index to store to. The value below that will be popped and stored in the stack at the given index.

Top of stack is a relative offset to jump to. If the value below that is truthy, then the program jumps by the offset.

Interprets the top of the stack as ascii and pushes the corresponding character.

(10 + N) Pushes the literal number n-10 onto the stack.

Example

Assume the program is:

```<code>chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken
(an empty line)
</code>```

(A cat program. Note that the empty line is required because of the preceding line having 6 "chicken".)

Input provided to Chicken program

```<code>Chicken
</code>```

Output

```<code>Chicken
</code>```

The Chicken.js reference implementation.

Error detection

The interpreter should leave an error and terminate when any word not "chicken" is present in the source.

Good luck!

答:
Javascript ES6, 398 bytes

By far the longest golf I have ever done, I'm sure this can be improved but my brain doesn't recognize anything other than chicken at this point.

```<code>(a,b)=>{for(c='chicken',s=[j=0,b,...A=a.split`
`.map(m=>m.split(c).length-1)],i=A.length+2;j<A.length;([_=>s[++i]=c,_=>s[--i]=s[i]+s[i+1],_=>s[--i]=s[i]-s[i+1],_=>s[--i]=s[i]*s[i+1],_=>s[--i]=s[i]==s[i+1],_=>s[i]=s[2+j++]?b[s[i]]:s[s[i]],_=>s[s[i--]]=s[i--],_=>j+=s[--i]?s[--i+2]:0,_=>s[i]=String.fromCharCode(s[i])][s[j+2]-1]||(_=>s[++i]=s[j+1]-10))(j++));return /[^chicken \n]\w/g.test(a)?0:s[i]}
</code>```

I will edit the explanation in when my brain starts functioning again. Here's a slightly ungolfed version for now.

Outputs a falsey value (0) for everything which isn't chicken

```<code>(a,b)=>{
    for(c='chicken',s=[j=0,b,...A=a.split`
    `.map(m=>m.split(c).length-1)],i=A.length+2; // loop init
    j<A.length; // loop condition
    ( // everything else
        [
            _=>s[++i]=c,
            _=>s[--i]=s[i]+s[i+1],
            _=>s[--i]=s[i]-s[i+1],
            _=>s[--i]=s[i]*s[i+1],
            _=>s[--i]=s[i]==s[i+1],
            _=>s[i]=s[2+j++]?b[s[i]]:s[s[i]],
            _=>s[s[i--]]=s[i--],
            _=>j+=s[--i]?s[--i+2]:0,
            _=>s[i]=String.fromCharCode(s[i])
        ][s[j+2]-1]
        ||(_=>s[++i]=s[j+1]-10)
    )(j++)
);
return /[^chicken \n]\w/g.test(a)?0:s[i]}
</code>```

Try it here

f=
  (a,b)=>{for(c='chicken',s=[j=0,b,...A=a.split`
`.map(m=>m.split(c).length-1)],i=A.length+2;js[++i]=c,_=>s[--i]=s[i]+s[i+1],_=>s[--i]=s[i]-s[i+1],_=>s[--i]=s[i]*s[i+1],_=>s[--i]=s[i]==s[i+1],_=>s[i]=s[2+j++]?b[s[i]]:s[s[i]],_=>s[s[i--]]=s[i--],_=>j+=s[--i]?s[--i+2]:0,_=>s[i]=String.fromCharCode(s[i])][s[j+2]-1]||(_=>s[++i]=s[j+1]-10))(j++));return /[^chicken \n]\w/g.test(a)?0:s[i]}

i.innerHTML = f(`chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken
`, 'Hello world!')```
<pre class="snippet-code-html lang-html prettyprint-override"><code><pre id=i></code>```

Title: Write a chicken interpreter!

Body:
Javascript ES6, 398 bytes

By far the longest golf I have ever done, I'm sure this can be improved but my brain doesn't recognize anything other than chicken at this point.

(a,b)=>{for(c='chicken',s=[j=0,b,...A=a.split`
`.map(m=>m.split(c).length-1)],i=A.length+2;j<A.length;([_=>s[++i]=c,_=>s[--i]=s[i]+s[i+1],_=>s[--i]=s[i]-s[i+1],_=>s[--i]=s[i]*s[i+1],_=>s[--i]=s[i]==s[i+1],_=>s[i]=s[2+j++]?b[s[i]]:s[s[i]],_=>s[s[i--]]=s[i--],_=>j+=s[--i]?s[--i+2]:0,_=>s[i]=String.fromCharCode(s[i])][s[j+2]-1]||(_=>s[++i]=s[j+1]-10))(j++));return /[^chicken \n]\w/g.test(a)?0:s[i]}

I will edit the explanation in when my brain starts functioning again. Here's a slightly ungolfed version for now.

Outputs a falsey value (0) for everything which isn't chicken

(a,b)=>{
    for(c='chicken',s=[j=0,b,...A=a.split`
    `.map(m=>m.split(c).length-1)],i=A.length+2; // loop init
    j<A.length; // loop condition
    ( // everything else
        [
            _=>s[++i]=c,
            _=>s[--i]=s[i]+s[i+1],
            _=>s[--i]=s[i]-s[i+1],
            _=>s[--i]=s[i]*s[i+1],
            _=>s[--i]=s[i]==s[i+1],
            _=>s[i]=s[2+j++]?b[s[i]]:s[s[i]],
            _=>s[s[i--]]=s[i--],
            _=>j+=s[--i]?s[--i+2]:0,
            _=>s[i]=String.fromCharCode(s[i])
        ][s[j+2]-1]
        ||(_=>s[++i]=s[j+1]-10)
    )(j++)
);
return /[^chicken \n]\w/g.test(a)?0:s[i]}

Try it here

f=
  (a,b)=>{for(c='chicken',s=[j=0,b,...A=a.split`
`.map(m=>m.split(c).length-1)],i=A.length+2;j<A.length;([_=>s[++i]=c,_=>s[--i]=s[i]+s[i+1],_=>s[--i]=s[i]-s[i+1],_=>s[--i]=s[i]*s[i+1],_=>s[--i]=s[i]==s[i+1],_=>s[i]=s[2+j++]?b[s[i]]:s[s[i]],_=>s[s[i--]]=s[i--],_=>j+=s[--i]?s[--i+2]:0,_=>s[i]=String.fromCharCode(s[i])][s[j+2]-1]||(_=>s[++i]=s[j+1]-10))(j++));return /[^chicken \n]\w/g.test(a)?0:s[i]}

i.innerHTML = f(`chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken
`, 'Hello world!')

<pre id=i>


问:
Oneliner to merge lines with same first field
This is my first codegolf question, so I apologize in advance if it's not appropriate, and I welcome any feedback.

I have a file with this format:

```<code>a | rest of first line
b | rest of second line
b | rest of third line
c | rest of fourth line
d | rest of fifth line
d | rest of sixth line
</code>```

The actual contents vary, as does the delimiter. The contents are just text. The delimiter only appears once per line. For this puzzle, feel free to change the delimiter, e.g. use "%" as the delimiter.

Desired output:

```<code>a | rest of first line
b | rest of second line % rest of third line
c | rest of fourth line
d | rest of fifth line % rest of sixth line
</code>```

I already have both ruby and awk scripts to merge this, but I suspect it's possible to have a short oneliner. i.e. a one-liner that can be used along with pipes and other commands on the command line. I can't figure it out, and my own script is to long to just compress on the command line.

Shortest characters preferred. Input is not necessarily sorted, but we are only interested in merging consecutive lines with matching first fields. There are unlimited lines with matching first fields. Field 1 could be anything, e.g. names of fruits, proper names, etc.

(I run on MacOS, so I am personally most interested in implementations that run on the mac).

Here is a second example/test. Notice "|" is the delimiter. The space before the "|" is irrelevant, and if resent should be considered part of the key. I am using "%" as a delimited in the output, but again, feel free to change the delimiter (but don't used square brackets).

Input:

```<code>why|[may express] surprise, reluctance, impatience, annoyance, indignation
whom|[used in] questions, subordination
whom|[possessive] whose
whom|[subjective] who
whoever|[objective] whomever
whoever|[possessive] whosever
who|[possessive] whose
who|[objective] whom
</code>```

Desired output:

```<code>why|[may express] surprise, reluctance, impatience, annoyance, indignation
whom|[used in] questions, subordination%[possessive] whose%[subjective] who
whoever|[objective] whomever%[possessive] whosever
who|[possessive] whose%[objective] whom
</code>```

Body:
APL, 42 chars

{⊃{∊⍺,{⍺'%'⍵}/⍵}⌸/↓[1]↑{(1,¯1↓'|'=⍵)⊂⍵}¨⍵}


答:
Pyke, 3 bytes

```<code>}F/
</code>```

Try it here!

```<code>for i in uniquify(input): print input.count(i)
</code>```

Title: Character Counting System

Body:
Pyke, 3 bytes

}F/

Try it here!

for i in uniquify(input): print input.count(i)


答:
PHP, 78 bytes

<?=fscanf(STDIN,"%4d%d",$y,$m)?strtoupper(date("My",mktime(0,0,0,$m,1,$y))):0;
```

The "year 2038 problem" may occur on some computers, as here. But not in others, as here.

Title: Convert YYYYMM to MMMYY

Body:
PHP, 78 bytes

<?=fscanf(STDIN,"%4d%d",$y,$m)?strtoupper(date("My",mktime(0,0,0,$m,1,$y))):0;

The "year 2038 problem" may occur on some computers, as here. But not in others, as here.


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

02/02/2020

12/02/2021

03/02/2030

The Challenge

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

Rules

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

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

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

Shortest answer wins!

Example

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

答:
MATL, <s>24</s> 23 bytes

```<code>YOZ}&:"@23XOtt47>)tP=?8M
</code>```

Accepts  input in the form of an array of string {lower, upper} where the date format is 'MM/DD/YYYY'. Output is in the format MM/DD/YYYY as well.

Try it Online

Explanation

```<code>        % Implicitly grab the two inputs
YO      % Convert to serial date format
Z}      % Push them onto the stack separately
&:      % Create an array from [lower...upper] incrementing 1 day
"       % For each day
  @23XO % Get the string version of the date (mm/dd/yyyy)
  tt    % Duplicate twice
  47>)  % Get the numeric parts
  tP=   % Compare numeric part with the flipped version of the numeric part
  ?8M   % If they are the same push it to the stack
        % Implicitly display stack contents
</code>```

Title: Forecast Palindromic Dates

Body:
MATL, <s>24</s> 23 bytes

YOZ}&:"@23XOtt47>)tP=?8M

Accepts  input in the form of an array of string {lower, upper} where the date format is 'MM/DD/YYYY'. Output is in the format MM/DD/YYYY as well.

Try it Online

Explanation

        % Implicitly grab the two inputs
YO      % Convert to serial date format
Z}      % Push them onto the stack separately
&:      % Create an array from [lower...upper] incrementing 1 day
"       % For each day
  @23XO % Get the string version of the date (mm/dd/yyyy)
  tt    % Duplicate twice
  47>)  % Get the numeric parts
  tP=   % Compare numeric part with the flipped version of the numeric part
  ?8M   % If they are the same push it to the stack
        % Implicitly display stack contents


答:
Sed, 55 bytes

```<code>:a N;:b s/^\([^|]*\)|\([^\n]*\)\n\1|/\1|\2 %/;ta;P;D;tb
</code>```

Test run :

```<code>$ echo """why|[may express] surprise, reluctance, impatience, annoyance, indignation
> whom|[used in] questions, subordination
> whom|[possessive] whose
> whom|[subjective] who
> whoever|[objective] whomever
> whoever|[possessive] whosever
> who|[possessive] whose
> who|[objective] whom""" | sed ':a N;:b s/^\([^|]*\)|\([^\n]*\)\n\1|/\1|\2 %/;ta;P;D;tb'
why|[may express] surprise, reluctance, impatience, annoyance, indignation
whom|[used in] questions, subordination %[possessive] whose %[subjective] who
whoever|[objective] whomever %[possessive] whosever
who|[possessive] whose %[objective] whom
</code>```

Title: Oneliner to merge lines with same first field

Body:
This is my first codegolf question, so I apologize in advance if it's not appropriate, and I welcome any feedback.

I have a file with this format:

```<code>a | rest of first line
b | rest of second line
b | rest of third line
c | rest of fourth line
d | rest of fifth line
d | rest of sixth line
</code>```

The actual contents vary, as does the delimiter. The contents are just text. The delimiter only appears once per line. For this puzzle, feel free to change the delimiter, e.g. use "%" as the delimiter.

Desired output:

```<code>a | rest of first line
b | rest of second line % rest of third line
c | rest of fourth line
d | rest of fifth line % rest of sixth line
</code>```

I already have both ruby and awk scripts to merge this, but I suspect it's possible to have a short oneliner. i.e. a one-liner that can be used along with pipes and other commands on the command line. I can't figure it out, and my own script is to long to just compress on the command line.

Shortest characters preferred. Input is not necessarily sorted, but we are only interested in merging consecutive lines with matching first fields. There are unlimited lines with matching first fields. Field 1 could be anything, e.g. names of fruits, proper names, etc.

(I run on MacOS, so I am personally most interested in implementations that run on the mac).

Here is a second example/test. Notice "|" is the delimiter. The space before the "|" is irrelevant, and if resent should be considered part of the key. I am using "%" as a delimited in the output, but again, feel free to change the delimiter (but don't used square brackets).

Input:

```<code>why|[may express] surprise, reluctance, impatience, annoyance, indignation
whom|[used in] questions, subordination
whom|[possessive] whose
whom|[subjective] who
whoever|[objective] whomever
whoever|[possessive] whosever
who|[possessive] whose
who|[objective] whom
</code>```

Desired output:

```<code>why|[may express] surprise, reluctance, impatience, annoyance, indignation
whom|[used in] questions, subordination%[possessive] whose%[subjective] who
whoever|[objective] whomever%[possessive] whosever
who|[possessive] whose%[objective] whom
</code>```

Body:
Sed, 55 bytes

:a N;:b s/^\([^|]*\)|\([^\n]*\)\n\1|/\1|\2 %/;ta;P;D;tb

Test run :

$ echo """why|[may express] surprise, reluctance, impatience, annoyance, indignation
> whom|[used in] questions, subordination
> whom|[possessive] whose
> whom|[subjective] who
> whoever|[objective] whomever
> whoever|[possessive] whosever
> who|[possessive] whose
> who|[objective] whom""" | sed ':a N;:b s/^\([^|]*\)|\([^\n]*\)\n\1|/\1|\2 %/;ta;P;D;tb'
why|[may express] surprise, reluctance, impatience, annoyance, indignation
whom|[used in] questions, subordination %[possessive] whose %[subjective] who
whoever|[objective] whomever %[possessive] whosever
who|[possessive] whose %[objective] whom


答:
Julia, 34 bytes

s->s>""?map(sizeof,split(s,"")):[]
```

This is an anonymous function that accepts a string and returns an integer array. To call it, assign it to a variable.

The approach is quite straightforward: If the input is empty, the output is empty. Otherwise we map the sizeof function, which counts the number of bytes in a string, to each one-character substring.

Try it online! (includes all test cases)

Title: Bytes/Character

Body:
Task

Given a UTF-8 string (by any means) answer (by any means) an equivalent list where every element is the number of bytes used to encode the corresponding input character.

Examples

! → 1

Ciao → 1 1 1 1

tʃaʊ → 1 2 1 2

Adám → 1 1 2 1

ĉaŭ → 2 1 2 (single characters)

ĉaŭ → 1 2 1 1 2 (uses combining overlays)

チャオ → 3 3 3

 (empty input) →  (empty output)

!±≡ → 1 2 3 4

� (a null byte) → 1

Null bytes

If the only way to keep reading input beyond null bytes is by knowing the total byte count, you may get the byte count by any means (even user input).

If your language cannot handle null bytes at all, you may assume the input does not contain nulls.

Body:
Julia, 34 bytes

s->s>""?map(sizeof,split(s,"")):[]

This is an anonymous function that accepts a string and returns an integer array. To call it, assign it to a variable.

The approach is quite straightforward: If the input is empty, the output is empty. Otherwise we map the sizeof function, which counts the number of bytes in a string, to each one-character substring.

<a href="http://julia.tryitonline.net/#code=Zj1zLT5zPiIiP21hcChzaXplb2Ysc3BsaXQocywiIikpOltdCgpmb3IgdGVzdCBpbiBbKCIhIiwgWzFdKSwKICAgICAgICAgICAgICgiQ2lhbyIsIFsxLDEsMSwxXSksCiAgICAgICAgICAgICAoInTKg2HKiiIsIFsxLDIsMSwyXSksCiAgICAgICAgICAgICAoIkFkw6FtIiwgWzEsMSwyLDFdKSwKICAgICAgICAgICAgICgixIlhxa0iLCBbMiwxLDJdKSwgICAgICAjIHNpbmdsZSBjaGFyYWN0ZXJzCiAgICAgICAgICAgICAoImPMgmF1zIYiLCBbMSwyLDEsMSwyXSksICAjIHVzZXMgY29tYmluaW5nIG92ZXJsYXlzCiAgICAgICAgICAgICAoIuODgeODo-OCqiIsIFszLDMsM10pLAogICAgICAgICAgICAgKCIiLCBbXSksCiAgICAgICAgICAgICAoIiHCseKJofCpuL0iLCBbMSwyLDMsNF0pXQogICAgcHJpbnRsbihmKHRlc3RbMV0pID09IHRlc3RbMl0pCmVuZA&input=" rel="nofollow">Try it online! (includes all test cases)


问:
Partition of a positive integer N
Find the number of partitions of a positive integer n. Hope someone uses the explicit finite formula for the partition function defined in Jan Hendrik Brunier and Ken Ono paper here.

```<code>Sample Input
8
Sample Output
22
</code>```

N is less than or equal to 1000.
Write the complete program. More than anything I would like to see the different approaches.

答:
Perl, 70 chars

Since there was no time limit:

```<code>sub p{my($k,$n)=@_;$k<$n?p($k+1,$n)+p($k,$n-$k):$n==$k}print p(1,pop);
</code>```

Partitions 50 in 2.3 s.

ContentLicense: CC BY-SA 2.5

Title: Partition of a positive integer N

Body:
Perl, 70 chars

Since there was no time limit:

sub p{my($k,$n)=@_;$k<$n?p($k+1,$n)+p($k,$n-$k):$n==$k}print p(1,pop);

Partitions 50 in 2.3 s.


问:
Generate a Kolakoski sequence

Definition1

A Kolakoski sequence is a self-describing infinite sequence {kn} of alternating blocks of 1's and 2's, given by the following rules:

k0 = 1

kn = the length of the (n+1)'th block

The Task

Given a positive integer n, generate the first n elements of the Kolakoski sequence.

Details

Input will be provided as a single command line argument n. Please write a full program that will print the first n elements of the Kolakoski sequence (in order) to STDOUT, with each element separated by your favorite whitespace.

Scoring

Lets count source code bytes this time with all whitespace included. Fewest number of bytes wins. In the event of a tie, the solution with the earliest submission time wins.

The Sequence2

1, 2, 2, 1, 1, 2, 1, 2, 2, 1, 2, 2, 1, 1, 2, 1, 1, 2, 2, 1, 2, 1, 1, 2, 1, 2, 2, 1, 1, 2, 1, 1, 2, 1, 2, 2, 1, 2, 2, 1, 1, 2, 1, 2, 2, 1, 2, 1, 1, 2, 1, 1, 2, 2, 1, 2, 2, 1, 1, 2, 1, 2, 2, 1, 2, 2, 1, 1, 2, 1, 1, 2, 1, 2, 2, 1, 2, 1, 1, 2, 2, 1, 2, 2, 1, 1, 2, 1, 2, 2, 1, 2, 2, 1, 1, 2, 1, 1, 2, 2, 1, 2, 1, 1, 2, 1, 2, 2, ...

References

John Smith, Ariel Scolnicov, yark. "Kolakoski sequence" (version 3). PlanetMath.org. Freely available at http://planetmath.org/KolakoskiSequence.html.

The Online Encyclopedia of Integer Sequences http://oeis.org/A000002

Other resources

Kolakoski Sequence at Wikipedia http://en.wikipedia.org/wiki/Kolakoski_sequence

Kolakoski Sequence at Wolfram MathWorld http://mathworld.wolfram.com/KolakoskiSequence.html

答:
Haskell 157 144

Haskell is kind of verbose so I expect this will be significantly longer than the shortest answer, but here it is.

```<code>import System
a=1:2:drop 2(concat.zipWith replicate a.cycle$[1,2])
main=do args<-getArgs;putStr$concatMap((' ':).show)$take(read$args!!0::Int)a
</code>```

Edit:

Implemented FUZxxl's suggestions and also a few other small fixes.

Title: Generate a Kolakoski sequence

Body:
Haskell 157 144

Haskell is kind of verbose so I expect this will be significantly longer than the shortest answer, but here it is.

import System
a=1:2:drop 2(concat.zipWith replicate a.cycle$[1,2])
main=do args<-getArgs;putStr$concatMap((' ':).show)$take(read$args!!0::Int)a

Edit:

Implemented FUZxxl's suggestions and also a few other small fixes.


答:
PHP, 126 bytes

```<code><?php $s=fgets(STDIN);echo $s!=''?implode(' ',array_map(function($x){return strlen($x);},preg_split('/(?<!^)(?!$)/u',$s))):'';
</code>```

Try it online!

Title: Bytes/Character

Body:
PHP, 126 bytes

<?php $s=fgets(STDIN);echo $s!=''?implode(' ',array_map(function($x){return strlen($x);},preg_split('/(?<!^)(?!$)/u',$s))):'';

Try it online!


答:
Perl 6, <s> 77 69 </s> 63 bytes

<s>

put +$0 if $_».base(2).fmt("%8d")~~/^(1)**2..*|^(" ")/ while $_=$*IN.read: 1
```

<pre class="lang-perl6 prettyprint-override"><code>put +$0 if $_».fmt("%8b")~~/^(1)**2..*|^(" ")/ while $_=$*IN.read: 1
</code>```

</s>

put 1+$0 if $_».fmt("%8b")~~/^1(1)+|^" "/while $_=$*IN.read: 1
```

<pre class="lang-perl6 prettyprint-override"><code>put 1+$0 if $_».fmt("%0.8b")~~/^1(1)+|^0/while $_=$*IN.read: 1
</code>```

Since Perl 6 uses NFG strings I have to pull in the bytes directly, which sidesteps the feature.

(NFG is like NFC except it also creates synthetic composed codepoints)

The output is separated by newlines.

Test:

for text in '!' 'Ciao' 'tʃaʊ' 'Adám' 'ĉaŭ' 'ĉaŭ' 'チャオ' '' '!±≡' '\0';
do
  echo -en $text |
  perl6 -e 'put 1+$0 if $_».fmt("%8b")~~/^1(1)+|^" "/while $_=$*IN.read: 1' |

  # combine all of the lines into a single one for display purposes
  env text=$text perl6 -e 'put qq["%*ENV<text>"], "\t\t", lines.gist'
done
```

<pre class="lang-perl6 prettyprint-override"><code>"!"     (1)
"tʃaʊ"      (1 2 1 2)
"Adám"      (1 1 2 1)
"ĉaŭ"       (2 1 2)
"ĉaŭ"     (1 2 1 1 2)
"チャオ"       (3 3 3)
""      ()
"!±≡"     (1 2 3 4)
"\0"        (4 1 4)
</code>```

Explanation:

# turns the list in ｢$0｣ into a count, and adds one
# ｢put｣ prints that with a trailing newline
put 1+$0

   # if the following is true
   if

       # format the input byte to base 2 and pad it out to 8 characters
       $_».fmt("%8b")

       ~~ # smart match against

       # check to see if it starts with more than one 1s, or a space
       # ( also sets ｢$0｣ to a list that is 1 shorter
       # than the number of bytes in this codepoint )
       / ^1 (1)+ | ^" " /

           # for every byte in STDIN
           while
               $_ = $*IN.read: 1
```

This works because the first byte in a multi-byte codepoint has the number of bytes encoded inside of it, and the other bytes in the codepoint have the highest bit set, but not the next highest. While the single byte codepoints don't have the highest bit set.

Title: Bytes/Character

Body:
Perl 6, <s> 77 69 </s> 63 bytes

<s>

put +$0 if $_».base(2).fmt("%8d")~~/^(1)**2..*|^(" ")/ while $_=$*IN.read: 1

put +$0 if $_».fmt("%8b")~~/^(1)**2..*|^(" ")/ while $_=$*IN.read: 1

</s>

put 1+$0 if $_».fmt("%8b")~~/^1(1)+|^" "/while $_=$*IN.read: 1

put 1+$0 if $_».fmt("%0.8b")~~/^1(1)+|^0/while $_=$*IN.read: 1

Since Perl 6 uses NFG strings I have to pull in the bytes directly, which sidesteps the feature.

(NFG is like NFC except it also creates synthetic composed codepoints)

The output is separated by newlines.

Test:

for text in '!' 'Ciao' 'tʃaʊ' 'Adám' 'ĉaŭ' 'ĉaŭ' 'チャオ' '' '!±≡' '\0';
do
  echo -en $text |
  perl6 -e 'put 1+$0 if $_».fmt("%8b")~~/^1(1)+|^" "/while $_=$*IN.read: 1' |

  # combine all of the lines into a single one for display purposes
  env text=$text perl6 -e 'put qq["%*ENV<text>"], "\t\t", lines.gist'
done

"!"     (1)
"tʃaʊ"      (1 2 1 2)
"Adám"      (1 1 2 1)
"ĉaŭ"       (2 1 2)
"ĉaŭ"     (1 2 1 1 2)
"チャオ"       (3 3 3)
""      ()
"!±≡"     (1 2 3 4)
"\0"        (4 1 4)

Explanation:

# turns the list in ｢$0｣ into a count, and adds one
# ｢put｣ prints that with a trailing newline
put 1+$0

   # if the following is true
   if

       # format the input byte to base 2 and pad it out to 8 characters
       $_».fmt("%8b")

       ~~ # smart match against

       # check to see if it starts with more than one 1s, or a space
       # ( also sets ｢$0｣ to a list that is 1 shorter
       # than the number of bytes in this codepoint )
       / ^1 (1)+ | ^" " /

           # for every byte in STDIN
           while
               $_ = $*IN.read: 1

This works because the first byte in a multi-byte codepoint has the number of bytes encoded inside of it, and the other bytes in the codepoint have the highest bit set, but not the next highest. While the single byte codepoints don't have the highest bit set.


答:
Python 2, 197 bytes

One byte saved thanks to @cat!

from datetime import*
def g(a,b):
 for s in"ab":exec"%s=date(*[int(x)for x in %s.split('-')])"%(s,s)
 for d in range((b-a).days+1):
    x=str(a+timedelta(d));y=x.replace("-","")
    if y==y[::-1]:print x
```

Try it here!

Input and output format is YYYY-MM-DD. First intendation level is spaces, second one is tabs.

Nothing too special going on here. Uses some exec abuse to convert the input to date objects by splitting the date string on - and splatting the list into the date constructor. Then we just iterate over all dates in their inclusive range and print the ones which are palindromic.

Title: Forecast Palindromic Dates

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

02/02/2020

12/02/2021

03/02/2030

The Challenge

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

Rules

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

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

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

Shortest answer wins!

Example

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

Body:
Python 2, 197 bytes

One byte saved thanks to @cat!

from datetime import*
def g(a,b):
 for s in"ab":exec"%s=date(*[int(x)for x in %s.split('-')])"%(s,s)
 for d in range((b-a).days+1):
    x=str(a+timedelta(d));y=x.replace("-","")
    if y==y[::-1]:print x

Try it here!

Input and output format is YYYY-MM-DD. First intendation level is spaces, second one is tabs.

Nothing too special going on here. Uses some exec abuse to convert the input to date objects by splitting the date string on - and splatting the list into the date constructor. Then we just iterate over all dates in their inclusive range and print the ones which are palindromic.


问:
Alternating Sign Sequence

Introduction

The sign of a number is either a +, or a - for every non-zero integer. Zero itself is signless (+0 is the same as -0). In the following sequence, we are going to alternate between the positive sign, the zero and the negative sign. The sequence starts with 1, so we write 1 with a positive sign, with zero (this one is weird, but we just multiply the number by 0) and the negative sign:

```<code>1, 0, -1
</code>```

The next number is 2, and we do the same thing again:

```<code>2, 0, -2
</code>```

The sequence eventually is:

```<code>1, 0, -1, 2, 0, -2, 3, 0, -3, 4, 0, -4, 5, 0, -5, 6, 0, -6, 7, 0, -7, ...
</code>```

Or a more readable form:

```<code>a(0) = 1
a(1) = 0
a(2) = -1
a(3) = 2
a(4) = 0
a(5) = -2
a(6) = 3
a(7) = 0
a(8) = -3
a(9) = 4
...
</code>```

The Task

Given a non-negative integer n, output the nth term of the above sequence. You can choose if you use the zero-indexed or one-indexed version.

Test cases:

Zero-indexed:

```<code>a(0) = 1
a(11) = -4
a(76) = 0
a(134) = -45
a(296) = -99
</code>```

Or if you prefer one-indexed:

```<code>a(1) = 1
a(12) = -4
a(77) = 0
a(135) = -45
a(297) = -99
</code>```

This is code-golf, so the submission with the smallest number of bytes wins!

答:
APL, 12 chars

```<code>-×/1-0 3⊤6+⎕
</code>```

0 3⊤ is APL's divmod 3.

Title: Alternating Sign Sequence

Body:
APL, 12 chars

-×/1-0 3⊤6+⎕

0 3⊤ is APL's divmod 3.


问:
Falsify brief truths
Find the longest run of true in a list of booleans. Return the same list, with all other trues falsified.

Input, output

A list; any usual format (e.g., a delimited list as a string).

Details

True and false can be anything your language typically uses for those values, or the integers 1 and 0. If you use single characters, the list can be a concatenation (e.g., 10001).

If there's a tie for longest run, keep all tying runs true, and falsify all shorter runs.

Examples

```<code>input ↦ output
1,0,1,0,1 ↦ 1,0,1,0,1
1,1,0,1,1,0,1 ↦ 1,1,0,1,1,0,0
1,1,0,1,1,1,0,1,1 ↦ 0,0,0,1,1,1,0,0,0
1,1,1 ↦ 1,1,1
0,0,1 ↦ 0,0,1
0,0 ↦ 0,0
1,1,1,0,0,0,1,1,1,1,0,1,0,0,1,1,0,1,1,1,1,0,0,1,0 ↦ 0,0,0,0,0,0,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,0,0,0,0
</code>```

(directly from https://stackoverflow.com/q/37447114)

答:
APL, 22 chars

```<code>(⊣=⌈/)∊(⊣×+/¨)(~⊂⊣)0,⎕
</code>```

In English (from right to left in blocks):

prepend 0 to the input

box starting with each 0

multiply each box by its sum

flatten

1 if number equal to the max, 0 otherwise

Title: Falsify brief truths

Body:
APL, 22 chars

(⊣=⌈/)∊(⊣×+/¨)(~⊂⊣)0,⎕

In English (from right to left in blocks):

prepend 0 to the input

box starting with each 0

multiply each box by its sum

flatten

1 if number equal to the max, 0 otherwise


答:
Java 7, 38 37 36 bytes

My first golf, be gentle

```<code>int a(int i){return(1+i/3)*(1-i%3);}
</code>```

Try it here! (test cases included)

Edit: I miscounted, and also golfed off one more character by replacing (-i%3+1) with (1-i%3).

Title: Alternating Sign Sequence

Body:
Introduction

The sign of a number is either a +, or a - for every non-zero integer. Zero itself is signless (+0 is the same as -0). In the following sequence, we are going to alternate between the positive sign, the zero and the negative sign. The sequence starts with 1, so we write 1 with a positive sign, with zero (this one is weird, but we just multiply the number by 0) and the negative sign:

```<code>1, 0, -1
</code>```

The next number is 2, and we do the same thing again:

```<code>2, 0, -2
</code>```

The sequence eventually is:

```<code>1, 0, -1, 2, 0, -2, 3, 0, -3, 4, 0, -4, 5, 0, -5, 6, 0, -6, 7, 0, -7, ...
</code>```

Or a more readable form:

```<code>a(0) = 1
a(1) = 0
a(2) = -1
a(3) = 2
a(4) = 0
a(5) = -2
a(6) = 3
a(7) = 0
a(8) = -3
a(9) = 4
...
</code>```

The Task

Given a non-negative integer n, output the nth term of the above sequence. You can choose if you use the zero-indexed or one-indexed version.

Test cases:

Zero-indexed:

```<code>a(0) = 1
a(11) = -4
a(76) = 0
a(134) = -45
a(296) = -99
</code>```

Or if you prefer one-indexed:

```<code>a(1) = 1
a(12) = -4
a(77) = 0
a(135) = -45
a(297) = -99
</code>```

This is code-golf, so the submission with the smallest number of bytes wins!

Body:
Java 7, 38 37 36 bytes

My first golf, be gentle

int a(int i){return(1+i/3)*(1-i%3);}

Try it here! (test cases included)

Edit: I miscounted, and also golfed off one more character by replacing (-i%3+1) with (1-i%3).


答:
Python 3, <s>30</s> 25 bytes

I tried to replicate the results of Leaky Nun's Python post for 10 minutes before realising it was for Python 2, not 3.

Zero-indexed:

lambda n:(n//3+1)*(1-n%3)
```

<h2>Full program:</h2>

<pre class="lang-py prettyprint-override"><code>a = lambda n:(n//3+1)*(1-n%3)
print(a(0))   #   1
print(a(11))  #  -4
print(a(76))  #   0
print(a(134)) # -45
print(a(296)) # -99
</code>```

Title: Alternating Sign Sequence

Body:
Python 3, <s>30</s> 25 bytes

I tried to replicate the results of Leaky Nun's Python post for 10 minutes before realising it was for Python 2, not 3.

Zero-indexed:

lambda n:(n//3+1)*(1-n%3)

Full program:

a = lambda n:(n//3+1)*(1-n%3)
print(a(0))   #   1
print(a(11))  #  -4
print(a(76))  #   0
print(a(134)) # -45
print(a(296)) # -99


答:
C#, <s>89</s> 82 bytes

```<code>I=>{var J="";foreach(char c in I){J+=Encoding.UTF8.GetByteCount(c+"");}return J;};
</code>```

A simple C# lambda that iterates through the string and returns the space separated list.

Edit: saved 6 bytes thanks to some very nice comments.

Title: Bytes/Character

Body:
C#, <s>89</s> 82 bytes

I=>{var J="";foreach(char c in I){J+=Encoding.UTF8.GetByteCount(c+"");}return J;};

A simple C# lambda that iterates through the string and returns the space separated list.

Edit: saved 6 bytes thanks to some very nice comments.


答:
Bash + GNU utilities, 116 84

Requires 64-bit version of date for the given testcase.

set date -uf- +%
jot -w@ - `$@s` 86400|$@F|sed -r 'h
:
s/-|^(.)(.*)\1$/\2/
t
/./d
g'
```

<p>I/O is in <code>YYYY-MM-DD</code> format.  Input is taken from two lines of stdin, e.g.</p>

<pre class="lang-bash prettyprint-override"><code>printf "%s\n" 2050-05-02 2060-12-12 | ./palindate.sh
</code>```

Explanation

set saves the date command template so it may be accessed using the $@ parameter

date -uf- +%s converts endpoint dates to number of seconds since the Unix epoch

jot interpolates this to give a list of seconds-from-the-epoch, one per day, each prefixed with @

date -uf- +%F formats each list entry as YYYY-MM-DD

sed checks for palindromes:

h save the input line to the hold buffer

: define "unnamed" label

s/-|^(.)(.*)\1$/\2/ if a dash is found, remove it or if the first and last characters match, remove them

t if there was a match above, jump back to the unnamed label

/./d if there are any characters left over, the line is not a palindrome - delete it and continue to the next line

g if we got here, then no line deletion happened, thus the line must have been a palindrome.  Get the line back from the hold buffer and implicitly display it.

Title: Forecast Palindromic Dates

Body:
Bash + GNU utilities, 116 84

Requires 64-bit version of date for the given testcase.

set date -uf- +%
jot -w@ - `$@s` 86400|$@F|sed -r 'h
:
s/-|^(.)(.*)\1$/\2/
t
/./d
g'

I/O is in YYYY-MM-DD format.  Input is taken from two lines of stdin, e.g.

printf "%s\n" 2050-05-02 2060-12-12 | ./palindate.sh

Explanation

set saves the date command template so it may be accessed using the $@ parameter

date -uf- +%s converts endpoint dates to number of seconds since the Unix epoch

jot interpolates this to give a list of seconds-from-the-epoch, one per day, each prefixed with @

date -uf- +%F formats each list entry as YYYY-MM-DD

sed checks for palindromes:

h save the input line to the hold buffer

: define "unnamed" label

s/-|^(.)(.*)\1$/\2/ if a dash is found, remove it or if the first and last characters match, remove them

t if there was a match above, jump back to the unnamed label

/./d if there are any characters left over, the line is not a palindrome - delete it and continue to the next line

g if we got here, then no line deletion happened, thus the line must have been a palindrome.  Get the line back from the hold buffer and implicitly display it.


问:
Separate alphabets and numbers
A paragraph of text has numbers and alphabetic letters mixed. Your task is to separate the numbers to the left side and the alphabetic letters to the right side in the same order of each line.

Rules:

Numbers are plain integers; so no decimal point, and no negative/positive signs.

Numbers may or may not be contiguous, but whatever the case may be, they have to be pushed to left side in the same order.

Numbers may occur in between words.

The text contains only ASCII alphabetic letters and numbers, along with spaces, underscores, commas and dots.

The one who does this with minimum keystrokes (like vim macros) or least amount of bytes in case of scripting is the winner.

Example Text:

```<code>A word can have any number of text like 433884,
but all the numb89ers has to be moved left side
but alph6abetical va9lues has to be pas46ted on right side.
The text might con4tain chara29cters s2huffled like hlep or dfeintino or even
meaningless1 words co43mbined togeth81er.
</code>```

Expected output:

```<code>433884A word can have any number of text like ,
89but all the numbers has to be moved left side
6946but alphabetical values has to be pasted on right side.
4292The text might contain characters shuffled like hlep or dfeintino or even
14381meaningless words combined together.
</code>```

答:
APL, 28 chars

```<code>{⍵[⍋(~⍵∊⎕D)++\¯1⌽⍵=⎕UCS 13]}
</code>```

Title: Separate alphabets and numbers

Body:
APL, 28 chars

{⍵[⍋(~⍵∊⎕D)++\¯1⌽⍵=⎕UCS 13]}


问:
Generate a valid sequence of numbers with specific rules

The challenge

The program must return a valid sequence of numbers into some rules

Rules

x is the size of the sequence;

x cannot be less than 4 or greater than 9 (Thanks David Carraher);

Digits of the sentence can't repeat, each one must appear once;

All digits between 1 to x must be in the sequence;

A valid sequence never begins nor ends with 1 or x;

Into the sequence, numbers can never appear "together";

Examples

If x=4:

2413 valid

3142 valid

1423 not valid, because begins with 1 and 23 are "together".

2134 not valid, because ends with x and 34 are "together".

Still don't get it?
Other example:

If x=8:

28375146 valid, because don't start with 1 nor x(8), don't end with 1 nor x, and no numbers are "together"(no numbers touches, no numbers are the next or previous)

Sorry, I really don't know how to explain the last rule. Hope the example make it understandable.

Additional Information

x does not need to be an input, you can show the outputs for x=4 and x=9 working;

Since any language will be accepted and, I don't know how all of them work, I will ask you people to help me with this;

The winner will be the one who got more up-votes in 1 week, so please, vote the answer you find the best; I will mark it as the Correct one;

Good, luck. =)

Body:
May I try to answer my own challenge?

Javascript (35 chars)

a="1";for(i=x;i>1;i--)a=i%2?a+i:i+a

Outputs

document.write(a);

4 => 2413
5 => 24153
6 => 246153
7 => 2461753
8 => 24681753
9 => 246819753


答:
Perl 5, 68 bytes

67, plus 1 for -pe instead of -e

```<code>y/0/ /;$_<${[sort@a]}[-1]&&y/1/0/for@a=split/\b/;$_=join"",@a;y; ;0
</code>```

Expects and prints a string (concatenation) of 0s and 1s.

Title: Falsify brief truths

Body:
Find the longest run of true in a list of booleans. Return the same list, with all other trues falsified.

Input, output

A list; any usual format (e.g., a delimited list as a string).

Details

True and false can be anything your language typically uses for those values, or the integers 1 and 0. If you use single characters, the list can be a concatenation (e.g., 10001).

If there's a tie for longest run, keep all tying runs true, and falsify all shorter runs.

Examples

```<code>input ↦ output
1,0,1,0,1 ↦ 1,0,1,0,1
1,1,0,1,1,0,1 ↦ 1,1,0,1,1,0,0
1,1,0,1,1,1,0,1,1 ↦ 0,0,0,1,1,1,0,0,0
1,1,1 ↦ 1,1,1
0,0,1 ↦ 0,0,1
0,0 ↦ 0,0
1,1,1,0,0,0,1,1,1,1,0,1,0,0,1,1,0,1,1,1,1,0,0,1,0 ↦ 0,0,0,0,0,0,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,0,0,0,0
</code>```

(directly from https://stackoverflow.com/q/37447114)

Body:
Perl 5, 68 bytes

67, plus 1 for -pe instead of -e

y/0/ /;$_<${[sort@a]}[-1]&&y/1/0/for@a=split/\b/;$_=join"",@a;y; ;0

Expects and prints a string (concatenation) of 0s and 1s.


答:
GolfScript, 16 bytes

```<code>{64/2=}%1,/{,)}*
</code>```

Try it online!

Background

GolfScript doesn't have a clue what Unicode is; all strings (input, output, internal) are composed of bytes. While that can be pretty annoying, it's perfect for this challenge.

UTF-8 encodes ASCII and non-ASCII characters differently:

All code points below 128 are encoded as 0xxxxxxx.

All other code points are encoded as 11xxxxxx 10xxxxxx ... 10xxxxxx.

This means that the encoding of each Unicode character contains either a single 0xxxxxxx byte or a single 11xxxxxx byte and 1 to 5 10xxxxxx bytes.

By dividing all bytes of the input by 64, we turn 0xxxxxxx into 0 or 1, 11xxxxxx into 3, and 10xxxxxx into 2.

If we compare the quotient with 2 – pushing 1 for 2; and 0 for 0, 1, and 3 – each character will be turned into a 0, followed by 1 to 5 1's.

All that's left is to split the resulting string at occurrences of 0, count the number of 1's between those zeroes and add one to the amount.

How it works

```<code>{     }%          Map the following over all bytes in the input.
 64/                Divide the byte by 64.
    2=              Compare the quotient with 2, pushing 1 or 0.
        1,        Push range(1), i.e., [0].
          /       Split the array of Booleans around zeroes.
           {  }*  Fold; for each run of ones but the first:
            ,       Push its length.
             )      Increment.
</code>```

Title: Bytes/Character

Body:
Task

Given a UTF-8 string (by any means) answer (by any means) an equivalent list where every element is the number of bytes used to encode the corresponding input character.

Examples

! → 1

Ciao → 1 1 1 1

tʃaʊ → 1 2 1 2

Adám → 1 1 2 1

ĉaŭ → 2 1 2 (single characters)

ĉaŭ → 1 2 1 1 2 (uses combining overlays)

チャオ → 3 3 3

 (empty input) →  (empty output)

!±≡ → 1 2 3 4

� (a null byte) → 1

Null bytes

If the only way to keep reading input beyond null bytes is by knowing the total byte count, you may get the byte count by any means (even user input).

If your language cannot handle null bytes at all, you may assume the input does not contain nulls.

Body:
GolfScript, 16 bytes

{64/2=}%1,/{,)}*

Try it online!

Background

GolfScript doesn't have a clue what Unicode is; all strings (input, output, internal) are composed of bytes. While that can be pretty annoying, it's perfect for this challenge.

UTF-8 encodes ASCII and non-ASCII characters differently:

All code points below 128 are encoded as 0xxxxxxx.

All other code points are encoded as 11xxxxxx 10xxxxxx ... 10xxxxxx.

This means that the encoding of each Unicode character contains either a single 0xxxxxxx byte or a single 11xxxxxx byte and 1 to 5 10xxxxxx bytes.

By dividing all bytes of the input by 64, we turn 0xxxxxxx into 0 or 1, 11xxxxxx into 3, and 10xxxxxx into 2.

If we compare the quotient with 2 – pushing 1 for 2; and 0 for 0, 1, and 3 – each character will be turned into a 0, followed by 1 to 5 1's.

All that's left is to split the resulting string at occurrences of 0, count the number of 1's between those zeroes and add one to the amount.

How it works

{     }%          Map the following over all bytes in the input.
 64/                Divide the byte by 64.
    2=              Compare the quotient with 2, pushing 1 or 0.
        1,        Push range(1), i.e., [0].
          /       Split the array of Booleans around zeroes.
           {  }*  Fold; for each run of ones but the first:
            ,       Push its length.
             )      Increment.


问:
Calculate Euler's totient function

Background

Euler's totient
function φ(n) is defined as the number of whole numbers less than or equal to n that are relatively prime to n,
that is, the number of possible values of x in 0 < x <= n for which
gcd(n, x) == 1.
We've had
a
few totient-related challenges
before, but never one which is just calculating it.

The mapping of the totient function onto the whole numbers is OEIS A000010.

Challenge

Given an integer n > 0, calculate φ(n).
You may take input through
command-line arguments,
standard input,
function arguments,
or anything else reasonable.
You may give output through
standard output,
return values,
or anything else reasonable.
Anonymous functions are acceptable.
You may assume that the input will not overflow your natural method of storing integers, e.g. int in C, but you must support inputs up to 255.
If your language has a built-in totient function, you may not use it.

Examples

```<code>φ(1) => 1
φ(2) => 1
φ(3) => 2
φ(8) => 4
φ(9) => 6
φ(26) => 12
φ(44) => 20
φ(105) => 48
</code>```

Shortest answer in bytes wins. If your language uses an encoding other than UTF-8, mention it in your answer.

答:
Ruby, 32 bytes

```<code>->n{(1..n).count{|i|i.gcd(n)<2}}
</code>```

a lambda that takes an integer n, and returns the counts of how many integers in the range (1..n) are coprime with n.

Title: Calculate Euler's totient function

Body:
Ruby, 32 bytes

->n{(1..n).count{|i|i.gcd(n)<2}}

a lambda that takes an integer n, and returns the counts of how many integers in the range (1..n) are coprime with n.


答:
Julia, 132 bytes

f(a,b,t=s->DateTime(s,"mm/dd/y"),g=d->Dates.format(d,"mm/dd/yyyy"))=map(g,filter(d->(r=replace(g(d),"/",""))==reverse(r),t(a):t(b)))
```

<p>This is a function that accepts two strings and returns an array of strings.</p>

<p>Ungolfed:</p>

<pre class="lang-default prettyprint-override"><code>function f(a, b)
    # Define a function to create a DateTime object from a string
    t = s -> DateTime(s, "mm/dd/y")

    # Define a function to create a string from a DateTime object
    g = d -> Dates.format(d, "mm/dd/yyyy")

    # Filter the range a:b to palindromic dates
    p = filter(d -> (r = replace(g(d), "/", "")) == reverse(r), t(a):t(b))

    # Format all dates in the array
    m = map(g, p)

    return m
end
</code>```

Try it online!

Title: Forecast Palindromic Dates

Body:
Julia, 132 bytes

f(a,b,t=s->DateTime(s,"mm/dd/y"),g=d->Dates.format(d,"mm/dd/yyyy"))=map(g,filter(d->(r=replace(g(d),"/",""))==reverse(r),t(a):t(b)))

This is a function that accepts two strings and returns an array of strings.

Ungolfed:

function f(a, b)
    # Define a function to create a DateTime object from a string
    t = s -> DateTime(s, "mm/dd/y")

    # Define a function to create a string from a DateTime object
    g = d -> Dates.format(d, "mm/dd/yyyy")

    # Filter the range a:b to palindromic dates
    p = filter(d -> (r = replace(g(d), "/", "")) == reverse(r), t(a):t(b))

    # Format all dates in the array
    m = map(g, p)

    return m
end

Try it online!


答:
JavaScript (ES6), <s>159</s> 154 bytes

```<code>(s,e)=>{for(r=[],s=Date.parse(s),e=Date.parse(e);s<=e;s+=864e5){d=new Date(s).toJSON().slice(0,10);`${a=d.match(/\d/g)}`==a.reverse()&&r.push(d)}return r}
</code>```

I/O in ISO format. Ungolfed:

```<code>function date_palindrome(start, end) {
    start = Date.parse(start);
    end = Date.parse(end);
    var result = [];
    while (start <= end) {
        var date = new Date(start).toISOString().slice(0, 10);
        var digits = date.match(/d/g);
        if (digits.join() == digits.reverse.join()) {
            result.push(date);
        }
        start += 24 * 60 * 60 * 1000; // ms
    }
    return result;
}
</code>```

Title: Forecast Palindromic Dates

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

02/02/2020

12/02/2021

03/02/2030

The Challenge

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

Rules

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

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

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

Shortest answer wins!

Example

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

Body:
JavaScript (ES6), <s>159</s> 154 bytes

(s,e)=>{for(r=[],s=Date.parse(s),e=Date.parse(e);s<=e;s+=864e5){d=new Date(s).toJSON().slice(0,10);`${a=d.match(/\d/g)}`==a.reverse()&&r.push(d)}return r}

I/O in ISO format. Ungolfed:

function date_palindrome(start, end) {
    start = Date.parse(start);
    end = Date.parse(end);
    var result = [];
    while (start <= end) {
        var date = new Date(start).toISOString().slice(0, 10);
        var digits = date.match(/d/g);
        if (digits.join() == digits.reverse.join()) {
            result.push(date);
        }
        start += 24 * 60 * 60 * 1000; // ms
    }
    return result;
}


答:
Factor, <s>57</s> <s>87</s> <s>82</s> 80 bytes

```<code>[ [ dup zero? [ drop "1"] [ >bin length 4 /i 10 >base ] if ] { } map-as ""join ]
</code>```

Explained:

```<code>USING: kernel math math.parser sequences ;
IN: byte-counts

: string>byte-counts ( str -- counts )
  [                  ! new quotation: takes a char as a fixnum
    dup zero?        ! true if this is a NUL byte
    [ drop "1" ]     ! NUL bytes have length 1
    [ >bin           ! else, convert to binary string
      length         ! length of binary string
      4              ! the constant 4
      /i             ! integer division
      number>string  ! 4 -> "4"
    ] if             ! conditionally execute one of the previous quotations
  ]                  ! end
  { } map-as         ! map and clone-like an { } array
  "" join ;          ! join array of 1strings on empty string
</code>```

Unit tests:

```<code>USING: tools.test byte-counts ;
IN: byte-counts.tests

{ "1" } [ "!" string>byte-counts ] unit-test
{ "1111" } [ "Ciao" string>byte-counts ] unit-test
{ "1212"} [ "tʃaʊ" string>byte-counts ] unit-test
{ "1121" } [ "Adám" string>byte-counts ] unit-test
{ "212" } [ "ĉaŭ" string>byte-counts ] unit-test
{ "12112" } [ "ĉaŭ" string>byte-counts ] unit-test
{ "333" } [ "チャオ" string>byte-counts ] unit-test
{ "" } [ "" string>byte-counts ] unit-test
{ "1234" } [ "!±≡" string>byte-counts ] unit-test
{ "1" } [ "\0" string>byte-counts ] unit-test
</code>```

They all pass, now. c:

Title: Bytes/Character

Body:
Factor, <s>57</s> <s>87</s> <s>82</s> 80 bytes

[ [ dup zero? [ drop "1"] [ >bin length 4 /i 10 >base ] if ] { } map-as ""join ]

Explained:

USING: kernel math math.parser sequences ;
IN: byte-counts

: string>byte-counts ( str -- counts )
  [                  ! new quotation: takes a char as a fixnum
    dup zero?        ! true if this is a NUL byte
    [ drop "1" ]     ! NUL bytes have length 1
    [ >bin           ! else, convert to binary string
      length         ! length of binary string
      4              ! the constant 4
      /i             ! integer division
      number>string  ! 4 -> "4"
    ] if             ! conditionally execute one of the previous quotations
  ]                  ! end
  { } map-as         ! map and clone-like an { } array
  "" join ;          ! join array of 1strings on empty string

Unit tests:

USING: tools.test byte-counts ;
IN: byte-counts.tests

{ "1" } [ "!" string>byte-counts ] unit-test
{ "1111" } [ "Ciao" string>byte-counts ] unit-test
{ "1212"} [ "tʃaʊ" string>byte-counts ] unit-test
{ "1121" } [ "Adám" string>byte-counts ] unit-test
{ "212" } [ "ĉaŭ" string>byte-counts ] unit-test
{ "12112" } [ "ĉaŭ" string>byte-counts ] unit-test
{ "333" } [ "チャオ" string>byte-counts ] unit-test
{ "" } [ "" string>byte-counts ] unit-test
{ "1234" } [ "!±≡" string>byte-counts ] unit-test
{ "1" } [ "\0" string>byte-counts ] unit-test

They all pass, now. c:


问:
The handshake problem
The handshake problem is the classic problem that for n people in a room, if they all shake hands, what's the total number of handshakes that occur.

You code should take an input of any number and output the number of handshakes, both in base ten.

Also the code should not let non-integers through. You should output a falsey in this case. The only expected inputs are positive whole integers and positive real numbers - you don't need to worry about complex numbers or strings as inputs.
This should mean that you should expect n >= 0

Test cases

```<code>(N:handshakes)
0:0
10:45
20:190
10.5:0
1337:893116
</code>```

Normal golfing rules apply and shortest code wins.
If your code isn't self explanatory, please explain.

Jelly and 05AB1E are the winners, both at 2 bytes

答:
Python 3, 32 16 bytes

```<code>lambda n:n*~-n/2
</code>```

Throws an error if n is not an integer.

Old Version:

```<code>lambda n:(0,n*~-n/2)[n==int(n)]
</code>```

Title: The handshake problem

Body:
Python 3, 32 16 bytes

lambda n:n*~-n/2

Throws an error if n is not an integer.

Old Version:

lambda n:(0,n*~-n/2)[n==int(n)]


答:
PowerShell v2+, 127 bytes

```<code>for($a,$b=[datetime[]]$args;$a-le$b){if(($c="{0:yyyyMMdd}"-f$a)-eq-join$c[$c.length..0]){"{0:MM/dd/yyyy}"-f$a}$a=$a.AddDays(1)}
</code>```

Takes input as command-line arguments $args in MM/DD/YYYY (or similar) format and recasts as a [datetime] array, stores them in $a and $b. That's the setup step of the for loop. The conditional is so long as $a is less-than-or-equal-to $b.

Each iteration, we set $c equal to a -formatted string of yyyyMMdd style, based on $a. We then compare if that's -equal to $c reversed (using an array-join trick). If so, we output $a in the proper format. Either way, we increment $a with .AddDays(1) to move to the next day.

Example

```<code>PS C:\Tools\Scripts\golfing> .\forecast-palindromic-dates.ps1 '06/23/2016' '12/12/2020'
02/02/2020
</code>```

Title: Forecast Palindromic Dates

Body:
PowerShell v2+, 127 bytes

for($a,$b=[datetime[]]$args;$a-le$b){if(($c="{0:yyyyMMdd}"-f$a)-eq-join$c[$c.length..0]){"{0:MM/dd/yyyy}"-f$a}$a=$a.AddDays(1)}

Takes input as command-line arguments $args in MM/DD/YYYY (or similar) format and recasts as a [datetime] array, stores them in $a and $b. That's the setup step of the for loop. The conditional is so long as $a is less-than-or-equal-to $b.

Each iteration, we set $c equal to a -formatted string of yyyyMMdd style, based on $a. We then compare if that's -equal to $c reversed (using an array-join trick). If so, we output $a in the proper format. Either way, we increment $a with .AddDays(1) to move to the next day.

Example

PS C:\Tools\Scripts\golfing> .\forecast-palindromic-dates.ps1 '06/23/2016' '12/12/2020'
02/02/2020


答:
Haskell, 60 bytes

```<code>import Data.List;g(n,l)=n++l;f=g.partition(`elem`['0'..'9'])
</code>```

Usage

```<code>f "A word can have any number of text like 433884,"
</code>```

Title: Separate alphabets and numbers

Body:
A paragraph of text has numbers and alphabetic letters mixed. Your task is to separate the numbers to the left side and the alphabetic letters to the right side in the same order of each line.

Rules:

Numbers are plain integers; so no decimal point, and no negative/positive signs.

Numbers may or may not be contiguous, but whatever the case may be, they have to be pushed to left side in the same order.

Numbers may occur in between words.

The text contains only ASCII alphabetic letters and numbers, along with spaces, underscores, commas and dots.

The one who does this with minimum keystrokes (like vim macros) or least amount of bytes in case of scripting is the winner.

Example Text:

```<code>A word can have any number of text like 433884,
but all the numb89ers has to be moved left side
but alph6abetical va9lues has to be pas46ted on right side.
The text might con4tain chara29cters s2huffled like hlep or dfeintino or even
meaningless1 words co43mbined togeth81er.
</code>```

Expected output:

```<code>433884A word can have any number of text like ,
89but all the numbers has to be moved left side
6946but alphabetical values has to be pasted on right side.
4292The text might contain characters shuffled like hlep or dfeintino or even
14381meaningless words combined together.
</code>```

Body:
Haskell, 60 bytes

import Data.List;g(n,l)=n++l;f=g.partition(`elem`['0'..'9'])

Usage

f "A word can have any number of text like 433884,"


答:
JavaScript (Node), 27 bytes

s=>s.map(Buffer.byteLength)
```

<p>This takes input as an array of individual characters, and returns an array of byte counts.</p>

<p><code>Buffer</code> is a method of representing raw binary data. Buffer.byteLength(string) gives the number of bytes in the string. UTF-8 is the default encoding. Note that only Node.js has buffers, not browser JS. The rough browser equivalent is called Blob, which comes in at 31 bytes:</p>

<pre class="lang-js prettyprint-override"><code>s=>s.map(e=>new Blob([e]).size)
</code>```

Test

Save this file and run it through node, or try it online.

var f =
  s=>s.map(Buffer.byteLength)

var tests = [
  ["!"],
  ["C","i","a","o"],
  ["t","ʃ","a","ʊ"],
  ["A","d","á","m"],
  ["ĉ","a","ŭ"],
  ["c","̂","a","u","̆"],
  ["チ","ャ","オ"],
  [],
  ["!","±","≡",""]
];

tests.forEach(test => {
  console.log(test, f(test));
});
```

<p>This should be the result:</p>

<pre class="lang-js prettyprint-override"><code>$ node bytes.js
[ '!' ] [ 1 ]
[ 'C', 'i', 'a', 'o' ] [ 1, 1, 1, 1 ]
[ 't', 'ʃ', 'a', 'ʊ' ] [ 1, 2, 1, 2 ]
[ 'A', 'd', 'á', 'm' ] [ 1, 1, 2, 1 ]
[ 'ĉ', 'a', 'ŭ' ] [ 2, 1, 2 ]
[ 'c', '̂', 'a', 'u', '̆' ] [ 1, 2, 1, 1, 2 ]
[ 'チ', 'ャ', 'オ' ] [ 3, 3, 3 ]
[] []
[ '!', '±', '≡', '�' ] [ 1, 2, 3, 4 ]
</code>```

Title: Bytes/Character

Body:
JavaScript (Node), 27 bytes

s=>s.map(Buffer.byteLength)

This takes input as an array of individual characters, and returns an array of byte counts.

Buffer is a method of representing raw binary data. Buffer.byteLength(string) gives the number of bytes in the string. UTF-8 is the default encoding. Note that only Node.js has buffers, not browser JS. The rough browser equivalent is called Blob, which comes in at 31 bytes:

s=>s.map(e=>new Blob([e]).size)

Test

Save this file and run it through node, or try it online.

var f =
  s=>s.map(Buffer.byteLength)

var tests = [
  ["!"],
  ["C","i","a","o"],
  ["t","ʃ","a","ʊ"],
  ["A","d","á","m"],
  ["ĉ","a","ŭ"],
  ["c","̂","a","u","̆"],
  ["チ","ャ","オ"],
  [],
  ["!","±","≡",""]
];

tests.forEach(test => {
  console.log(test, f(test));
});

This should be the result:

$ node bytes.js
[ '!' ] [ 1 ]
[ 'C', 'i', 'a', 'o' ] [ 1, 1, 1, 1 ]
[ 't', 'ʃ', 'a', 'ʊ' ] [ 1, 2, 1, 2 ]
[ 'A', 'd', 'á', 'm' ] [ 1, 1, 2, 1 ]
[ 'ĉ', 'a', 'ŭ' ] [ 2, 1, 2 ]
[ 'c', '̂', 'a', 'u', '̆' ] [ 1, 2, 1, 1, 2 ]
[ 'チ', 'ャ', 'オ' ] [ 3, 3, 3 ]
[] []
[ '!', '±', '≡', '�' ] [ 1, 2, 3, 4 ]