问:
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>```

答:
Retina, 16 bytes

Stable bubble sort.

```<code>%+`(\D)(\d)
$2$1
</code>```

Sample input:

```<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>```

Sample 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>```

Try it online!

Title: Separate alphabets and numbers

Body:
Retina, 16 bytes

Stable bubble sort.

%+`(\D)(\d)
$2$1

Sample input:

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.

Sample output:

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.

Try it online!


答:
CJam, 9 13 16 bytes

```<code>qN/{{A,s-,}$}%N*
</code>```

There isn't f$...

This 13 bytes version nearly works:

```<code>{l{A,s-,}$N}h
</code>```

ContentLicense: CC BY-SA 3.0

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:
CJam, 9 13 16 bytes

qN/{{A,s-,}$}%N*

There isn't f$...

This 13 bytes version nearly works:

{l{A,s-,}$N}h


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

1 byte thanks to @FryAmTheEggman.

```<code>jms+@J`MTd-dJ.z
</code>```

Try it online!

Sample input:

```<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>```

Sample 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>```

How it works

```<code>jms+@J`MTd-dJ.z

 m           .z    for each line (d):
         d           yield d (the line)
     J                 assign J to
        T              [0,1,2,3,...,9]
      `M               with each number converted to string
    @                intersect with J
   +                 append:
          -dJ          filter d for characters not in J
  s                  convert to one string
j                  join by newline
</code>```

Title: Separate alphabets and numbers

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

1 byte thanks to @FryAmTheEggman.

jms+@J`MTd-dJ.z

Try it online!

Sample input:

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.

Sample output:

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.

How it works

jms+@J`MTd-dJ.z

 m           .z    for each line (d):
         d           yield d (the line)
     J                 assign J to
        T              [0,1,2,3,...,9]
      `M               with each number converted to string
    @                intersect with J
   +                 append:
          -dJ          filter d for characters not in J
  s                  convert to one string
j                  join by newline


问:
Mean bits: an average challenge
Given an integer N >= 1, output the mean number of bits in an integer from 0 to N - 1

Specification

The output can be calculated as the sum of the number of bits in the binary representation of each integer from 0 to N-1, divided by N.

The binary representation of an integer has no leading zeroes in this context, with the exception of zero, which is represented as 0 in binary.

The output should be accurate to at least 7 significant figures.

Example

N = 6

```<code>0: 0   : 1 bit
1: 1   : 1 bit
2: 10  : 2 bits
3: 11  : 2 bits
4: 100 : 3 bits
5: 101 : 3 bits
</code>```

Mean number of bits = (1 + 1 + 2 + 2 + 3 + 3) / 6 = 2

Test cases

Input => output

```<code>1 => 1
2 => 1
3 => 1.3333333
4 => 1.5
5 => 1.8
6 => 2
7 => 2.1428571
</code>```

Leaderboard Snippet

(from here)

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

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

```

Note that the sum (before dividing to find the mean) is a sequence on OEIS.

答:
Vitsy, 26 bytes

This is a first attempt, I'll golf this down more and add an explanation later.

```<code>0vVV1HV1-\[2L_1+v+v]v1+V/N</code>```

Try it online!

Title: Mean bits: an average challenge

Body:
Vitsy, 26 bytes

This is a first attempt, I'll golf this down more and add an explanation later.

0vVV1HV1-\[2L_1+v+v]v1+V/N

Try it online!


答:
Octave, <s>37</s> 32 bytes

```<code>@(s)disp([s(x=s>47&s<58),s(~x)])

ans('The text might con4tain chara29cters s2huffled like hlep or dfeintino or even')
4292The text might contain characters shuffled like hlep or dfeintino or even
</code>```

Title: Separate alphabets and numbers

Body:
Octave, <s>37</s> 32 bytes

@(s)disp([s(x=s>47&s<58),s(~x)])

ans('The text might con4tain chara29cters s2huffled like hlep or dfeintino or even')
4292The text might contain characters shuffled like hlep or dfeintino or even


答:
MATL, <s>13</s> 12 bytes

```<code>`jt4Y2m&)hDT
</code>```

Exits with an error (allowed by default), producing the correct output.

Try it online!

Explanation

```<code>`          T    % infinite loop
 j              % input one line as a string
  t             % duplicate
   4Y2          % predefined literal: '0123456789'
      m         % true for elements of string that are digits, false for the rest
       &)       % two-output indexing: push digits, then non-digits
         h      % concatenate the two strings
          D     % display
</code>```

Title: Separate alphabets and numbers

Body:
MATL, <s>13</s> 12 bytes

`jt4Y2m&)hDT

Exits with an error (allowed by default), producing the correct output.

Try it online!

Explanation

`          T    % infinite loop
 j              % input one line as a string
  t             % duplicate
   4Y2          % predefined literal: '0123456789'
      m         % true for elements of string that are digits, false for the rest
       &)       % two-output indexing: push digits, then non-digits
         h      % concatenate the two strings
          D     % display


答:
Perl 5.10, 54 bytes

```<code>for(1..<>){$u+=length sprintf"%b",$_;$n++}$u/=$n;say$u
</code>```

Pretty much straightforward. sprintf"%b" is a neat way to output a number in binary in Perl without using additional libraries.

Try it online!

Title: Mean bits: an average challenge

Body:
Given an integer N >= 1, output the mean number of bits in an integer from 0 to N - 1

Specification

The output can be calculated as the sum of the number of bits in the binary representation of each integer from 0 to N-1, divided by N.

The binary representation of an integer has no leading zeroes in this context, with the exception of zero, which is represented as 0 in binary.

The output should be accurate to at least 7 significant figures.

Example

N = 6

```<code>0: 0   : 1 bit
1: 1   : 1 bit
2: 10  : 2 bits
3: 11  : 2 bits
4: 100 : 3 bits
5: 101 : 3 bits
</code>```

Mean number of bits = (1 + 1 + 2 + 2 + 3 + 3) / 6 = 2

Test cases

Input => output

```<code>1 => 1
2 => 1
3 => 1.3333333
4 => 1.5
5 => 1.8
6 => 2
7 => 2.1428571
</code>```

Leaderboard Snippet

(from here)

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

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

```

Note that the sum (before dividing to find the mean) is a sequence on OEIS.

Body:
Perl 5.10, 54 bytes

for(1..<>){$u+=length sprintf"%b",$_;$n++}$u/=$n;say$u

Pretty much straightforward. sprintf"%b" is a neat way to output a number in binary in Perl without using additional libraries.

Try it online!


答:
Perl, 17 bytes

16 bytes code + 1 switch

```<code>s/\d/!print$&/ge
</code>```

Requires -p.

Usage

```<code>perl -pe 's/\d/!print$&/ge' <<< 'a1b2c3d4e5f6'
123456abcdef
</code>```

Alternatively:

```<code>print/\d/g,/\D/g
</code>```

Requires -n.

Usage

```<code>perl -ne 'print/\d/g,/\D/g' <<< 'a1b2c3d4e5f6'
123456abcdef
</code>```

Title: Separate alphabets and numbers

Body:
Perl, 17 bytes

16 bytes code + 1 switch

s/\d/!print$&/ge

Requires -p.

Usage

perl -pe 's/\d/!print$&/ge' <<< 'a1b2c3d4e5f6'
123456abcdef

Alternatively:

print/\d/g,/\D/g

Requires -n.

Usage

perl -ne 'print/\d/g,/\D/g' <<< 'a1b2c3d4e5f6'
123456abcdef


问:
Every Possible Cycle Length
A function (or program) which takes inputs and provides outputs can be said to have a cycle if calling the function on its own output repeatedly eventually reaches the original number. For instance, take the following function:

```<code>Input:  n    1 2 3 4 5 6
Output: f(n) 5 7 1 3 4 9
</code>```

If we start with n=1, f(n)=5, f(f(n))=f(5)=4, f(f(f(n)))=f(4)=3, f(f(f(f(n))))=f(3)=1.

This is written (1 5 4 3). Since there are 4 unique numbers in this loop, this is a cycle of length 4.

Your challenge is to write a program or function which has cycles of every possible length. That is, there must be a cycle of length 1, of length 2, and so on.

In addition, your function/program must be from the positive integers to positive integers, and it must be bijective, meaning that there must be a exactly one input value for every possible output value, over all positive integers. To put it another way, the function/program must compute a permutaion of the positive integers.

Details: Any standard input/output system is allowed, including STDIN, STDOUT, function argument, return, etc. Standard loopholes prohibited.

You do not need to worry about the limitations of your data types - the above properties need only hold under the assumption that an int or float can hold any value, for instance.

There are no restrictions on the behavior of the function on inputs which are not positive integers, and those inputs/outputs will be ignored.

Scoring is code golf in bytes, shortest code wins.

Title: Every Possible Cycle Length

Body:
JavaScript (ES6), 43 bytes

f=(n,i=1,j=1)=>n>j?f(n,++i,j+i):n++<j?n:n-i


问:
Tips for golfing in C++
What general tips do you have for golfing in C++?

I'm looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to C++ (e.g. "remove comments" is not an answer). Please post one tip per answer.

(Tips that apply to C as well can be found in Tips for golfing in C - but note that some C tips don't work in C++.  For example, C++ does require function prototypes and return values.)

答:
You may use the ternary operator ?: without any expressions in the true-block (it saves a byte)

#include <iostream>

int foo()
{
    std::cout << "Foo\n";
}

int main()
{
    1?foo():0;  // if (true) foo()
    0?:foo();   // if (!false) foo()
}
```

Check it here

ContentLicense: CC BY-SA 4.0

Title: Tips for golfing in C++

Body:
You may use the ternary operator ?: without any expressions in the true-block (it saves a byte)

#include <iostream>

int foo()
{
    std::cout << "Foo\n";
}

int main()
{
    1?foo():0;  // if (true) foo()
    0?:foo();   // if (!false) foo()
}

Check it here


答:
05AB1E, <s>14</s> 10 bytes

Code:

```<code>|vyþyyþ-¶J
</code>```

Explanation:

```<code>|                 # push all lines in input as array of strings
 v                # for each line in array
  yþ              # push only digits from line
    yyþ-          # push line without digits
        ¶         # push newline char
         J        # join as string
                  # end loop and print explicitly
</code>```

Example Input:

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

meaningless words co43mbined togeth81er.

Example Output:

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

4381meaningless words combined together.

Try it online

Title: Separate alphabets and numbers

Body:
05AB1E, <s>14</s> 10 bytes

Code:

|vyþyyþ-¶J

Explanation:

|                 # push all lines in input as array of strings
 v                # for each line in array
  yþ              # push only digits from line
    yyþ-          # push line without digits
        ¶         # push newline char
         J        # join as string
                  # end loop and print explicitly

Example Input:

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

meaningless words co43mbined togeth81er.

Example Output:

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

4381meaningless words combined together.

Try it online


答:
Javascript ES6, 40 bytes

a=>a.replace(/\D/g,'')+a.replace(/\d/g,'')

Tried several other solutions, but couldn't get it smaller than this.

My first try was a=>[...a.match(/\d/g),...a.match(/\D/g)].join`` but that's 5 bytes longer

Try it here

f=
a=>a.replace(/\D/g,'')+a.replace(/\d/g,'')

a.innerHTML='```'+
  ['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',
 'meaningless words co43mbined togeth81er.'].map(b=>f(b)).join('<br>')+'```'```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id=a></code>```

Title: Separate alphabets and numbers

Body:
Javascript ES6, 40 bytes

a=>a.replace(/\D/g,'')+a.replace(/\d/g,'')

Tried several other solutions, but couldn't get it smaller than this.

My first try was a=>[...a.match(/\d/g),...a.match(/\D/g)].join`` but that's 5 bytes longer

Try it here

f=
a=>a.replace(/\D/g,'')+a.replace(/\d/g,'')

a.innerHTML='<pre>'+
  ['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',
 'meaningless words co43mbined togeth81er.'].map(b=>f(b)).join('<br>')+'</pre>'

<div id=a>


答:
Retina, 14 bytes

```<code>O%$`\d|(.)
$#1
</code>```

Try it online!

Explanation

O introduces a sorting stage. % tells Retina to apply the transformation to each line separately. $ tells it to sort the matches by the result of the specified substitution.

The regex itself is \d|(.) which either matches a digit, or anything else which is captured into group 1. This is substituted with $#1 which is the number of captures of group 1. That is, the sorting key for digits is 0 and the sorting key for everything else is 1. Since sorting in Retina is stable, this simply moves digits to the left and everything else to the right.

Title: Separate alphabets and numbers

Body:
Retina, 14 bytes

O%$`\d|(.)
$#1

Try it online!

Explanation

O introduces a sorting stage. % tells Retina to apply the transformation to each line separately. $ tells it to sort the matches by the result of the specified substitution.

The regex itself is \d|(.) which either matches a digit, or anything else which is captured into group 1. This is substituted with $#1 which is the number of captures of group 1. That is, the sorting key for digits is 0 and the sorting key for everything else is 1. Since sorting in Retina is stable, this simply moves digits to the left and everything else to the right.


答:
Python 3, 64 bytes

Three equivalent solutions! I can’t pick.

```<code>while 1:print(*sorted(input(),key=lambda x:-x.isdigit()),sep='')
while 1:print(*sorted(input(),key=lambda x:x<'0'or'9'<x),sep='')
while 1:print(*sorted(input(),key=str.isdigit,reverse=1),sep='')
</code>```

Title: Separate alphabets and numbers

Body:
Python 3, 64 bytes

Three equivalent solutions! I can’t pick.

while 1:print(*sorted(input(),key=lambda x:-x.isdigit()),sep='')
while 1:print(*sorted(input(),key=lambda x:x<'0'or'9'<x),sep='')
while 1:print(*sorted(input(),key=str.isdigit,reverse=1),sep='')


答:
Pyke, 8 bytes

```<code>Qmb2slQ/
</code>```

Try it here!

Title: Mean bits: an average challenge

Body:
Pyke, 8 bytes

Qmb2slQ/

Try it here!


答:
PowerShell v2+, 64 bytes

```<code>param($n)0..($n-1)|%{$o+=[convert]::ToString($_,2).Length};$o/$n
</code>```

Very straightforward implementation of the spec. Loops from 0 to $n-1 with |%{...}. Each iteration, we [convert] our input number $_ to a string base2 and take its length. We accumulate that in $o. After the loops, we simply divide $o/$n, leaving that on the pipeline, and output is implicit.

As long as this is, it's actually shorter than the formula that Sp & others are using, since [math]::Ceiling() and [math]::Log() are ridiculously wordy. Base conversion in PowerShell is yucky.

Title: Mean bits: an average challenge

Body:
PowerShell v2+, 64 bytes

param($n)0..($n-1)|%{$o+=[convert]::ToString($_,2).Length};$o/$n

Very straightforward implementation of the spec. Loops from 0 to $n-1 with |%{...}. Each iteration, we [convert] our input number $_ to a string base2 and take its length. We accumulate that in $o. After the loops, we simply divide $o/$n, leaving that on the pipeline, and output is implicit.

As long as this is, it's actually shorter than the formula that Sp & others are using, since [math]::Ceiling() and [math]::Log() are ridiculously wordy. Base conversion in PowerShell is yucky.


答:
Hoon, <s>92</s> 83 bytes

```<code>|*
*
(turn (lore +<) |=(@ `tape`(welp (skid (trip +<) |=(@ !=(~ (rush +< nud)))))))
</code>```

++lore splits a multi-line cord into a (list cord), (trip +<) turns it into a tape. ++skid seperates a list in two: one side where the function returns yes, one side where it returns no. Our function tries to parse the character with ++nud (numeric) and checks if it parses fully, and then we weld the two lists back together into a tape.

```<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.
  '''
  |*
  *
  (turn (lore +<) |=(@ `tape`(welp (skid (trip +<) |=(@ !=(~ (rush +< nud)))))))
<<
  "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>```

Title: Separate alphabets and numbers

Body:
Hoon, <s>92</s> 83 bytes

|*
*
(turn (lore +<) |=(@ `tape`(welp (skid (trip +<) |=(@ !=(~ (rush +< nud)))))))

++lore splits a multi-line cord into a (list cord), (trip +<) turns it into a tape. ++skid seperates a list in two: one side where the function returns yes, one side where it returns no. Our function tries to parse the character with ++nud (numeric) and checks if it parses fully, and then we weld the two lists back together into a tape.

> %.
  '''
  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.
  '''
  |*
  *
  (turn (lore +<) |=(@ `tape`(welp (skid (trip +<) |=(@ !=(~ (rush +< nud)))))))
<<
  "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."
>>


问:
Female and Male Sequences
This question is probably harder than all of those "generate a sequence of numbers" tasks, because this requires TWO sequences working in unison.

Really looking forward to the answers!

In his book "Gödel, Escher, Bach: An Eternal Golden Braid", Douglas Hofstadter has a quite few sequences of numbers inside, all of them rely on the previous term in some way. For information on all of the sequences, see this Wikipedia page.

One pair of sequences that's really interesting is the Female and Male sequences, which are defined like so:

for n > 0.

Here's the Female sequence and the Male sequence.

Your task is, when given an integer n as input, return a list of the Female sequence and the Male sequence, with the amount of terms equal to n, in two lines of output, with the Female sequence on the first line and the Male sequence on the second.

Sample inputs and outputs:
Input: 5
Output: [1, 1, 2, 2, 3]  [0, 0, 1, 2, 2]

Input: 10
Output: [1, 1, 2, 2, 3, 3, 4, 5, 5, 6]  [0, 0, 1, 2, 2, 3, 4, 4, 5, 6]

NOTE: The separation between lists signifies a line break.

This is code-golf, so shortest code in bytes wins. Also, put an explanation in as well for your code.

Leaderboard

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

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

```

答:
Mathematica, <s>69</s> 62 bytes

Thanks to Sp3000 for suggesting a functional form which saved 14 bytes.

```<code>k_~f~0=1-k
k_~f~n_:=n-f[1-k,f[k,n-1]]
Print/@Array[f,{2,#},0]&
</code>```

This defines a named helper function f and then evaluates to an unnamed function which solves the actual task of printing both sequences.

Title: Female and Male Sequences

Body:
Mathematica, <s>69</s> 62 bytes

Thanks to Sp3000 for suggesting a functional form which saved 14 bytes.

k_~f~0=1-k
k_~f~n_:=n-f[1-k,f[k,n-1]]
Print/@Array[f,{2,#},0]&

This defines a named helper function f and then evaluates to an unnamed function which solves the actual task of printing both sequences.


答:
Haskell, 57 bytes

```<code>l#s=scanl(\a b->b-l!!a)s[1..]
v=w#1
w=v#0
(<$>[v,w]).take
</code>```

Usage example: (<$>[v,w]).take $ 5 -> [[1,1,2,2,3],[0,0,1,2,2]]

The helper function # builds an infinite list with starting value s and a list l for looking up all further elements (at index of the previous value). v = w#1 is the female and w = v#0 the male sequence. In the main function we take the first n elements of both v and w.

Title: Female and Male Sequences

Body:
This question is probably harder than all of those "generate a sequence of numbers" tasks, because this requires TWO sequences working in unison.

Really looking forward to the answers!

In his book "Gödel, Escher, Bach: An Eternal Golden Braid", Douglas Hofstadter has a quite few sequences of numbers inside, all of them rely on the previous term in some way. For information on all of the sequences, see this Wikipedia page.

One pair of sequences that's really interesting is the Female and Male sequences, which are defined like so:

for n > 0.

Here's the Female sequence and the Male sequence.

Your task is, when given an integer n as input, return a list of the Female sequence and the Male sequence, with the amount of terms equal to n, in two lines of output, with the Female sequence on the first line and the Male sequence on the second.

Sample inputs and outputs:
Input: 5
Output: [1, 1, 2, 2, 3]  [0, 0, 1, 2, 2]

Input: 10
Output: [1, 1, 2, 2, 3, 3, 4, 5, 5, 6]  [0, 0, 1, 2, 2, 3, 4, 4, 5, 6]

NOTE: The separation between lists signifies a line break.

This is code-golf, so shortest code in bytes wins. Also, put an explanation in as well for your code.

Leaderboard

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

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

```

Body:
Haskell, 57 bytes

l#s=scanl(\a b->b-l!!a)s[1..]
v=w#1
w=v#0
(<$>[v,w]).take

Usage example: (<$>[v,w]).take $ 5 -> [[1,1,2,2,3],[0,0,1,2,2]]

The helper function # builds an infinite list with starting value s and a list l for looking up all further elements (at index of the previous value). v = w#1 is the female and w = v#0 the male sequence. In the main function we take the first n elements of both v and w.


答:
PowerShell v2+, 55 bytes

```<code>$args[0]-split"`n"|%{($_-replace'\D')+($_-replace'\d')}
</code>```

Due to the need to support multi-line input, we have to encapsulate our -replace statements with a loop and -split on newlines. Otherwise basically equivalent to the JavaScript solution.

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:
PowerShell v2+, 55 bytes

$args[0]-split"`n"|%{($_-replace'\D')+($_-replace'\d')}

Due to the need to support multi-line input, we have to encapsulate our -replace statements with a loop and -split on newlines. Otherwise basically equivalent to the JavaScript solution.


答:
Java 8, <s>130</s> <s>126</s> 86 bytes

a->{for(String s:a)System.out.println(s.replaceAll("\\D","")+s.replaceAll("\\d",""));}
```
<p>-4 bytes converting Java 7 to 8 and removing an unused character<br />
-40 bytes converting program to function and changing <code>[^\\d]</code> to <code>\\D</code></p>
<p><strong>Explanation:</strong></p>
<p>Try it here.</p>
<pre class="lang-java prettyprint-override"><code>a->{                             // Method with String-array parameter and no return-type
  for(String s:a)                //  Loop over the array
    System.out.println(          //   Print with a trailing new-line:
      s.replaceAll("\\D","")     //    All digits,
      +s.replaceAll("\\d",""));  //    plus all non-digits
</code>```

Title: Separate alphabets and numbers

Body:
Java 8, <s>130</s> <s>126</s> 86 bytes

a->{for(String s:a)System.out.println(s.replaceAll("\\D","")+s.replaceAll("\\d",""));}

-4 bytes converting Java 7 to 8 and removing an unused character

-40 bytes converting program to function and changing [^\\d] to \\D

Explanation:

<a href="https://tio.run/##XZHNTsMwEITvPMUop0aUSNAItVQgIXGFC9yAwybZNAZnHdmbAEJ99uKk5UdcLHnWM/vt@oUGOnEdy0v1uisthYBbMvJ5BBhR9jWVjLvxCgzOVChn9@qNbB6fQek66tujeAQlNSXuILjEjk6uPmvnDy8RLii9/wjKbeZ6zbooqpVZyDx3NuZfWztLnp5uknmSpMf/5WqS0/V2tx47dX1hY6dDwwmpjcA/VOQ3Id3zSlbOhN/wXdqrQHKNN@fjKCRoaGCQfED6tmAPV0P5XWHNKyNfLJbLfJ7Mv41FryBroQ1PhuWKfYgZAepQMFo3cAXLtSKYivHf2TXnVHAEJ4uBVrbnv@6OQn6uMcAJvNk0@5DsN@Qhtp3o2qlaOsk1zo6yIU9nq1JHmnDW9HVtR45xhsZyB@dR1RzXbsSNFx5YfmNbJokLshzC6bSZEKPzRVsYiSnqNqzN8pR9lkyO7eHbt7sv" rel="nofollow noreferrer">Try it here.

a->{                             // Method with String-array parameter and no return-type
  for(String s:a)                //  Loop over the array
    System.out.println(          //   Print with a trailing new-line:
      s.replaceAll("\\D","")     //    All digits,
      +s.replaceAll("\\d",""));  //    plus all non-digits


答:
V, 12 bytes

```<code>òí¨Ä©¨ä©/²±

</code>```

V, is an unfinished, 2D string based golfing language. Although it is unfinished, this program works as of commit 45, which was published last night, making this a competing answer. (Most of my previous V answers were non-competing.)

Note, the trailing newline is necessary, although this is due to a bug.

Try it online!

Explanation:

```<code>ò            #Recursively, do:
 í           #Substitute on every line
  ¨Ä©¨ä©/²±  #The following regex.
</code>```

¨Ä©¨ä©/²± expands into the vim regex:

```<code>:%s/\(\D\)\(\d\)/\2\1
</code>```

which is a non-digit (\D) followed by a digit (\d), and swap them.

Since this is filled with gross unicode characters, here is a reversible hexdump:

```<code>00000000: f2ed a8c4 a9a8 e4a9 2fb2 b10a            ......../...
</code>```

Title: Separate alphabets and numbers

Body:
V, 12 bytes

òí¨Ä©¨ä©/²±

V, is an unfinished, 2D string based golfing language. Although it is unfinished, this program works as of commit 45, which was published last night, making this a competing answer. (Most of my previous V answers were non-competing.)

Note, the trailing newline is necessary, although this is due to a bug.

Try it online!

Explanation:

ò            #Recursively, do:
 í           #Substitute on every line
  ¨Ä©¨ä©/²±  #The following regex.

¨Ä©¨ä©/²± expands into the vim regex:

:%s/\(\D\)\(\d\)/\2\1

which is a non-digit (\D) followed by a digit (\d), and swap them.

Since this is filled with gross unicode characters, here is a reversible hexdump:

00000000: f2ed a8c4 a9a8 e4a9 2fb2 b10a            ......../...


问:
What is the smallest positive base 10 integer that can be printed by a program shorter (in characters) than itself?
I think the question as above is clear, but just in case:

Write a full program (not just a function) which prints a positive base 10 integer, optionally followed by a single newline.

Qualifying programs will be those whose output is longer (in bytes) than the source code of the program, measured in bytes (assuming ASCII or UTF-8 encoding for the program source code).

I.e. the code must be shorter than the number of digits in the resulting number.

Leading zeros are disallowed under all circumstances. Counting leading zeroes trivialises the problem; ignoring leading zeros unnecessarily complicates the question.

The winning program will be the qualifying program which prints the integer with the smallest magnitude.

Leaderboard snippet

var QUESTION_ID = 67921;
var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe"; var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk";
var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page;
function answersUrl(index) { return "https://api.stackexchange.com/2.2/questions/" + QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER; }
function commentUrl(index, answers) { return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER; }
function getAnswers() { jQuery.ajax({ url: answersUrl(answer_page++), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { answers.push.apply(answers, data.items); answers_hash = []; answer_ids = []; data.items.forEach(function(a) { a.comments = []; var id = +a.share_link.match(/\d+/); answer_ids.push(id); answers_hash[id] = a; }); if (!data.has_more) more_answers = false; comment_page = 1; getComments(); } }); } function getComments() { jQuery.ajax({ url: commentUrl(comment_page++, answer_ids), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { if (data.has_more) getComments(); else if (more_answers) getAnswers(); else process(); } }); }
getAnswers();
var SCORE_REG = /<h\d>\s*([^\n,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*)(?:,|[-\u2013] ).*?([\d,^!e+]+)(?=\:?[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/;
var OVERRIDE_REG = /^Override\s*header:\s*/i;
function getAuthorName(a) { return a.owner.display_name; }
function process() { var valid = []; answers.forEach(function(a) { var body = a.body; a.comments.forEach(function(c) { if(OVERRIDE_REG.test(c.body)) body = '
' + c.body.replace(OVERRIDE_REG, '') + '
'; }); var match = body.replace(/([^\n<]*)<\/sup>/g, "^$1").replace(/\(\d+(?:\^\d+,)? [\w\s]+\)/g, "").replace(/floor\(10\^(\d+)\/9\)/g, "$1 ones").replace(/(\d+) ones/g, function (_, x) { return Array(+x + 1).join(1); }).match(SCORE_REG); if (match) valid.push({ user: getAuthorName(a), size: +match[2].replace(/,/g, "").replace(/(\d+)\s*\^\s*(\d+)/, function (_, a, b) { return Math.pow(a, b); }).replace(/(\d+)!/, function (_, n) { for (var i = 1, j = 1; i <= n; i++) j *= i; return j; }), language: match[1], link: a.share_link, }); else console.log(body); }); valid.sort(function (a, b) { var aB = a.size, bB = b.size; return aB - bB }); var languages = {}; var place = 1; var lastSize = null; var lastPlace = 1; valid.forEach(function (a) { if (a.size != lastSize) lastPlace = place; lastSize = a.size; ++place; var answer = jQuery("#answer-template").html(); answer = answer.replace("{{PLACE}}", lastPlace + ".") .replace("{{NAME}}", a.user) .replace("{{LANGUAGE}}", a.language) .replace("{{SIZE}}", a.size) .replace("{{LINK}}", a.link); answer = jQuery(answer); jQuery("#answers").append(answer); var lang = a.language; lang = jQuery(''+lang+'').text(); languages[lang] = languages[lang] || {lang: a.language, lang_raw: lang.toLowerCase(), user: a.user, size: a.size, link: a.link}; }); var langs = []; for (var lang in languages) if (languages.hasOwnProperty(lang)) langs.push(languages[lang]); langs.sort(function (a, b) { if (a.lang_raw > b.lang_raw) return 1; if (a.lang_raw < b.lang_raw) return -1; return 0; }); for (var i = 0; i < langs.length; ++i) { var language = jQuery("#language-template").html(); var lang = langs[i]; language = language.replace("{{LANGUAGE}}", lang.lang) .replace("{{NAME}}", lang.user) .replace("{{SIZE}}", lang.size) .replace("{{LINK}}", lang.link); language = jQuery(language); jQuery("#languages").append(language); } }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<style>body { text-align: left !important} #answer-list { padding: 10px; width: 290px; float: left; } #language-list { padding: 10px; width: 290px; float: left; } table thead { font-weight: bold; } table td { padding: 5px; }</style>
<link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">
<div id="language-list"> <h2>Shortest Solution by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr> </thead> <tbody id="languages"> </tbody> </table> </div> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr> </thead> <tbody id="answers"> </tbody> </table> </div> <table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td>Link</td></tr> </tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td>Link</td></tr> </tbody> </table></code>```

Body:
marioLANG, 700666666005555550044444400333333002222220011111100 (51 digits for 49 bytes)

still no marioLANG anwser? well here's one,

Try it online

+
+
+
+
+
+!::::::<
+#======"
:>)::(-[!
="======#


问:
AppleSauce Fader
Back in the day, all the 1337 kids used text faders in chatrooms. I don't know about you guys, but I want to feel cool like they did. The only problem is that their old scripts and applications were heavily coupled to the software they were made for, so I can't just make use of this amazing functionality wherever I want. I also want the solution to be easily portable so you're going to need to make the code as small as possible so that it will fit on my floppy disk (I'd rather only carry one floppy but if your source code is too big I can carry more than one :P).

Input

A list of colors (rgb, hex, names, etc)

Text to format

Your program should expect the list of colors to contain at least 2 colors.

Text to format can be any length greater than zero and characters will be limited to printable ascii. (Hint: Longer text inputs may require you to reuse intermediate colors for consecutive characters)

Output

The output text should not differ from the input text in any way other than font  and/or markup/styling (Note: if your output contains html markup then you'll need to html encode the input). You may output text with markup/styling (html style tags, console colors, etc.) or a picture of the faded text. All color hexes should be present in the output unless the input does not contain enough characters to meet this requirement. If this is the case, then consult the priority rules to determine which color hexes should be present in your output. The order or these colors in your output should still be input order.

Color Priority Rules

In the event that the input is one character, the first color will be used

In the event that there are only two characters, the first and last color will be used

In the event that there are more than three colors and more colors than characters, the first and last colors should be prioritized, then the rest of the colors in their inputted order.

In the event that there are more characters than colors, the characters should fade from one color to the next using intermediate colors

Examples (Priority rules 1-3 respectively):

# Colors | Color0 | ... | Colorn | Text

3 ff0000 0000ff ffff00 M ->

3 ff0000 0000ff ffff00 hi ->

4 ff0000 0000ff ffff00 0fff00 sup ->

To be clear, the text color should fade from one color hex to the next. The fade does not have to be perfectly uniform but it shouldn't be an abrupt color change unless there aren't enough characters to fade nicely. Generally this fade is achieved by choosing intermediate colors for each of the characters by incrementing/decrementing the rgb values by some interval determined by the number of characters you have to work with and the difference between the colors. For example if we needed a single color between  (#ff0000) and  (#000000), we might choose  as it sits right in the middle.  Optimal output will look rather pretty.

Example (Priority rule 4):

3 ff0000 ff7f00 f0ff00 To be or not to be, that is the question... ->

-OR-

```<code><span style="color:#ff0000;">T</span><span style="color:#ff0600;">o</span><span style="color:#ff0c00;"> </span><span style="color:#ff1200;">b</span><span style="color:#ff1800;">e</span><span style="color:#ff1e00;"> </span><span style="color:#ff2400;">o</span><span style="color:#ff2a00;">r</span><span style="color:#ff3000;"> </span><span style="color:#ff3600;">n</span><span style="color:#ff3c00;">o</span><span style="color:#ff4300;">t</span><span style="color:#ff4900;"> </span><span style="color:#ff4f00;">t</span><span style="color:#ff5500;">o</span><span style="color:#ff5b00;"> </span><span style="color:#ff6100;">b</span><span style="color:#ff6700;">e</span><span style="color:#ff6d00;">,</span><span style="color:#ff7300;"> </span><span style="color:#ff7900;">t</span><span style="color:#ff7f00;">h</span><span style="color:#fe8500;">a</span><span style="color:#fe8b00;">t</span><span style="color:#fd9100;"> </span><span style="color:#fc9700;">i</span><span style="color:#fb9d00;">s</span><span style="color:#fba400;"> </span><span style="color:#faaa00;">t</span><span style="color:#f9b000;">h</span><span style="color:#f9b600;">e</span><span style="color:#f8bc00;"> </span><span style="color:#f7c200;">q</span><span style="color:#f6c800;">u</span><span style="color:#f6ce00;">e</span><span style="color:#f5d400;">s</span><span style="color:#f4da00;">t</span><span style="color:#f4e100;">i</span><span style="color:#f3e700;">o</span><span style="color:#f2ed00;">n</span><span style="color:#f1f300;">.</span><span style="color:#f1f900;">.</span><span style="color:#f0ff00;">.</span>
</code>```

In your answer please specify how your output should be displayed (as html, in a console, as an image, etc.).

* All black backgrounds are only for color emphasis and are not required

Scoring

This is code-golf, so the shortest answer (in bytes) wins.

If you manage to add fade to individual characters then I'll forever think you're cool (but no bonus to score as this will not be fair for some langs)

答:
JavaScript (ES6), 290 bytes

h=a=>f(a,a.shift());f=
(a,w)=>[...w].map((c,i)=>{l=w.length-1;m=a.length-1;s=o.appendChild(document.createElement('span'));s.textContent=c;s.style.color=`#${i?i-l?a[r=l%m,n=l/m|0,i<r*n+r?++n:i-=r,k=i/n|0,k++].replace(/./g,(c,d)=>((parseInt(c,16)*(n-i%n)+i%n*parseInt(a[k][d],16))/n|0).toString(16)):a[m]:a[0]}`;})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><textarea rows=10 cols=40 oninput="o.textContent='';h(this.value.split`\n`)">Type the text here and the colours on subsequent lines.
FF0000
00FF00
0000FF</textarea><div id=o></code>```

Title: AppleSauce Fader

Body:
JavaScript (ES6), 290 bytes

h=a=>f(a,a.shift());f=
(a,w)=>[...w].map((c,i)=>{l=w.length-1;m=a.length-1;s=o.appendChild(document.createElement('span'));s.textContent=c;s.style.color=`#${i?i-l?a[r=l%m,n=l/m|0,i<r*n+r?++n:i-=r,k=i/n|0,k++].replace(/./g,(c,d)=>((parseInt(c,16)*(n-i%n)+i%n*parseInt(a[k][d],16))/n|0).toString(16)):a[m]:a[0]}`;})

<textarea rows=10 cols=40 oninput="o.textContent='';h(this.value.split`\n`)">Type the text here and the colours on subsequent lines.
FF0000
00FF00
0000FF</textarea><div id=o>


答:
Java, 169 bytes total

```<code>int f(int n,int i){return n>0?n-f(f(n-1,i),-i):i>0?1:0;}void p(int n,int i){if(n>0)p(n-1,i);System.out.print(i==0?"\n":f(n,i)+" ");}void p(int n){p(n,1);p(0,0);p(n,-1);}
</code>```

F(), M() 56 bytes

```<code>int f(int n,int i){
    return n>0?n-f(f(n-1,i),-i):i>0?1:0;
}
</code>```

recursive-for-loop and printing 77 Bytes

```<code>void p(int n,int i) {
    if(n>0) {
        p(n-1,i);
    }
    System.out.print(i==0?"\n":f(n,i)+" ");
}
</code>```

outputting the lists in two different lines 37 Bytes

```<code>void p(int n) {
    p(n,1);
    p(0,0);
    p(n,-1);
}
</code>```

input : p(10)

output :

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

Title: Female and Male Sequences

Body:
Java, 169 bytes total

int f(int n,int i){return n>0?n-f(f(n-1,i),-i):i>0?1:0;}void p(int n,int i){if(n>0)p(n-1,i);System.out.print(i==0?"\n":f(n,i)+" ");}void p(int n){p(n,1);p(0,0);p(n,-1);}

F(), M() 56 bytes

int f(int n,int i){
    return n>0?n-f(f(n-1,i),-i):i>0?1:0;
}

recursive-for-loop and printing 77 Bytes

void p(int n,int i) {
    if(n>0) {
        p(n-1,i);
    }
    System.out.print(i==0?"\n":f(n,i)+" ");
}

outputting the lists in two different lines 37 Bytes

void p(int n) {
    p(n,1);
    p(0,0);
    p(n,-1);
}

input : p(10)

output :

1 1 2 2 3 3 4 5 5 6 6 7 8 8 9 9
0 0 1 2 2 3 4 4 5 6 6 7 7 8 9 9


答:
C#, 59 bytes

```<code>I=>Regex.Replace(I,"[^0-9]","")+Regex.Replace(I,@"\d+","");
</code>```

A simple C# lambda function using regex.

Sample 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>```

Title: Separate alphabets and numbers

Body:
C#, 59 bytes

I=>Regex.Replace(I,"[^0-9]","")+Regex.Replace(I,@"\d+","");

A simple C# lambda function using regex.

Sample output

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.


答:
Perl 6, <s> 34 </s> 32 bytes

<s>

{$_ R/[+] map *.base(2).chars,^$_}
```

<p></s></p>

<pre class="lang-perl6 prettyprint-override"><code>{$_ R/[+] map {(.msb||0)+1},^$_}
</code>```

Explanation:

{
  $_  # the input
  R/  # divides ( ｢$a R/ $b｣ is the same as ｢$b / $a｣ )
  [+] # the sum of:
  map
    {
      (
       .msb # the most significant digit (0 based)
       || 0 # which returns Nil for ｢0.msb｣ so use 0 instead
            # should be ｢(.msb//0)｣ but the highlighting gets it wrong
            # it still works because it has the same end result
      )
      + 1   # make it 1 based
    },
    ^$_ # ｢0 ..^ $_｣ all the numbers up to the input, excluding the input
}
```

<h3>Test:</h3>

<pre class="lang-perl6 prettyprint-override"><code>use v6.c;

# give it a name
my &mean-bits = {$_ R/[+] map {(.msb||0)+1},^$_}

for 1..7 {
  say .&mean-bits
}

say '';

say mean-bits(7).perl;
say mean-bits(7).base-repeating(10);
</code>```

1
1
1.333333
1.5
1.8
2
2.142857

<15/7>
(2. 142857)
```

Title: Mean bits: an average challenge

Body:
Given an integer N >= 1, output the mean number of bits in an integer from 0 to N - 1

Specification

The output can be calculated as the sum of the number of bits in the binary representation of each integer from 0 to N-1, divided by N.

The binary representation of an integer has no leading zeroes in this context, with the exception of zero, which is represented as 0 in binary.

The output should be accurate to at least 7 significant figures.

Example

N = 6

```<code>0: 0   : 1 bit
1: 1   : 1 bit
2: 10  : 2 bits
3: 11  : 2 bits
4: 100 : 3 bits
5: 101 : 3 bits
</code>```

Mean number of bits = (1 + 1 + 2 + 2 + 3 + 3) / 6 = 2

Test cases

Input => output

```<code>1 => 1
2 => 1
3 => 1.3333333
4 => 1.5
5 => 1.8
6 => 2
7 => 2.1428571
</code>```

Leaderboard Snippet

(from here)

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

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

```

Note that the sum (before dividing to find the mean) is a sequence on OEIS.

Body:
Perl 6, <s> 34 </s> 32 bytes

<s>

{$_ R/[+] map *.base(2).chars,^$_}

</s>

{$_ R/[+] map {(.msb||0)+1},^$_}

Explanation:

{
  $_  # the input
  R/  # divides ( ｢$a R/ $b｣ is the same as ｢$b / $a｣ )
  [+] # the sum of:
  map
    {
      (
       .msb # the most significant digit (0 based)
       || 0 # which returns Nil for ｢0.msb｣ so use 0 instead
            # should be ｢(.msb//0)｣ but the highlighting gets it wrong
            # it still works because it has the same end result
      )
      + 1   # make it 1 based
    },
    ^$_ # ｢0 ..^ $_｣ all the numbers up to the input, excluding the input
}

Test:

use v6.c;

# give it a name
my &mean-bits = {$_ R/[+] map {(.msb||0)+1},^$_}

for 1..7 {
  say .&mean-bits
}

say '';

say mean-bits(7).perl;
say mean-bits(7).base-repeating(10);

1
1
1.333333
1.5
1.8
2
2.142857

<15/7>
(2. 142857)


问:
The Nine Pattern

Introduction

I stumbled across this (useless) pattern the other day while I was watching TV.
I named it "the 9 pattern" because the first number to use it was 9.
The gist of it is, you enter a number (let's say x), and then you get back:

x

x + (x / 3) [let's call this y]

two-thirds of y [let's call this z]

z + 1

So, if I put inside this pattern the number 9 as x, this is what would come out:

9 (9)

12 (9 + 9 / 3) [9 over 3 is 3, and 9 + 3 is 12]

8 (12 times two-thirds) [a third of 12 is 4, and 4 * 2 is 8]

9 (8 + 1 is 9)

Challenge

Write me a function (in any programming language) that takes in a number, and outputs an integer array using the pattern.

Somewhat like this psuedo-code:

```<code>function ninePattern(int myInt) returns IntegerArray {
    int iterationA = myInt + (myInt / 3);
    int iterationB = iterationA * (2 / 3);
    int iterationC = iterationB + 1;
    IntegerArray x = [myInt, iterationA, iterationB, iterationC];
    return x;
}
</code>```

Clarifications

Discussions have been arousing in comments regarding the specifications of the question. This section is meant to clarify some of those.

"better to count in bytes than characters"

I picked characters because (for me, at least) it would be easier to judge. Of course, I can't change that now. (lots of answers are already posted)

"rounding"

Rounding follows this rhyme:

If it's 5 or more, raise the score

  If it's 4 or less, let it rest

Simply, put, if it is something like 4.7 or 3.85, round them to 5 and 4 respectively.

Examples

```<code>Input => Result
9 => [9, 12, 8, 9]
8 => [8, 11, 7, 8]
6 => [6, 8, 5, 6]
23 => [23, 31, 21, 22]
159 => [159, 212, 141, 142]
</code>```

If, however, the numbers are something like 2.3 or 10.435446, round them to 2 and 10 respectively.

"language support"

You are free to not use functions and/or arrays IF AND ONLY IF the language of your choice does not support them.  If it does (even if it will increase your characters count), you must use them.

答:
Mathematica, 51 bytes

```<code>FoldList[#2@#&,{#,Round[4#/3]&,Round[2#/3]&,#+1&}]&
</code>```

Anonymous function that conforms to the current (at time of posting) version of post, which implies rounding at every step.

FoldList is a typical operation in programming. It is invoked as FoldList[f, list] and applies the two-argument function f repeatedly to the result (or the first element of the list in the first iteration), taking the next element of the list as its second argument.

Ungolfed:
#2 @ # & is an anonymous functions that applies its second argument to the first. Therefore, the list argument of FoldList consists of the successive functions to be applied to the input.

```<code>FoldList[#2 @ # &,
  {#, (* note the absence of '&' here,
         this '#' stands for the argument
         of the complete function and is
         covered by the & at the end      *)
   Round[4 # / 3] &, (* anonymous function that rounds 4/3 of its input *)
   Round[2 # / 3] &, (* ditto, 2/3 *)
   # + 1 &           (* add one function *)
  }] &               (* and the '&' makes the entire
                        thing an anonymous function,
                        whose argument is the '#' up
                        at the top.                  *)
</code>```

Because input is integer and the divisions are by 3, there will never be a result like 4.5, therefore there's no need to worry about rules of rounding when the last digit is a 5: it will always be clearly closer to one integer, or another.

Title: The Nine Pattern

Body:
Mathematica, 51 bytes

FoldList[#2@#&,{#,Round[4#/3]&,Round[2#/3]&,#+1&}]&

Anonymous function that conforms to the current (at time of posting) version of post, which implies rounding at every step.

FoldList is a typical operation in programming. It is invoked as FoldList[f, list] and applies the two-argument function f repeatedly to the result (or the first element of the list in the first iteration), taking the next element of the list as its second argument.

Ungolfed:
#2 @ # & is an anonymous functions that applies its second argument to the first. Therefore, the list argument of FoldList consists of the successive functions to be applied to the input.

FoldList[#2 @ # &,
  {#, (* note the absence of '&' here,
         this '#' stands for the argument
         of the complete function and is
         covered by the & at the end      *)
   Round[4 # / 3] &, (* anonymous function that rounds 4/3 of its input *)
   Round[2 # / 3] &, (* ditto, 2/3 *)
   # + 1 &           (* add one function *)
  }] &               (* and the '&' makes the entire
                        thing an anonymous function,
                        whose argument is the '#' up
                        at the top.                  *)

Because input is integer and the divisions are by 3, there will never be a result like 4.5, therefore there's no need to worry about rules of rounding when the last digit is a 5: it will always be clearly closer to one integer, or another.


问:
Parse a 1D language
Given a string containing only 0's 1's, 2's and brackets, output the grammar tree of the string.

A 2 requires 2 arguments - one to the left and one to the right

A 1 requires a single argument - to either the left or right

A 0 doesn't require any arguments and is the base case

A pair of brackets counts as one argument and the contents of the brackets are evaluated separately from the rest of the string. Nested brackets are possible

A input string will always be a complete tree with no characters falling off. The string will also only have a single correct solution. Note that the functions are commutative and any arrangement of arguments for 2 will be acceptable. You will not have to handle input that doesn't conform to these requirements.

The output grammar format will be in the form function(arguments) recursively

Test cases

```<code>0 --> 0
01 --> 1(0)
020 --> 2(0,0)
101 --> 1(1(0))
0120 --> 2(1(0),0)
0120210 --> 2(1(0),2(0,1(0)))
01210 --> 2(1(0),1(0))
(020)210 --> 2(2(0,0),1(0))
((020)20)1 --> 1(2(0,2(0,0)))
</code>```

答:
Python 3.6 (pre-release), 199

Saved 6 bytes thanks to Morgan Thrapp

```<code>import re
def f(s):s=s.strip('()');i,j=[m.start()if m else-1for m in(re.search(c+'(?![^(]*\))',s)for c in'21')];return i>0and f'2({f(s[:i])},{f(s[i+1:])})'or j>=0and f'1({f(s[:j])or f(s[j+1:])})'or s
</code>```

Explanation & ungolfed version:

```<code>import re

def f(s):
    s=s.strip('()')
    # Search for '2' and '1' outside of brackets
    i, j = [m.start() if m else -1
            for m in (re.search(c + '(?![^(]*\))', s) for c in '21')]

    if i > 0:
        # Call `f(s[:i])` and `f(s[i+1:])`, concatenate the results
        return f'2({f(s[:i])},{f(s[i+1:])})'
    elif j>=0:
        # Call `f(s[:j])` and `f(s[j+1:])`, choose the non-empty result
        return f'1({f(s[:j]) or f(s[j+1:])})'
    else:
        return s
</code>```

Title: Parse a 1D language

Body:
Python 3.6 (pre-release), 199

Saved 6 bytes thanks to Morgan Thrapp

import re
def f(s):s=s.strip('()');i,j=[m.start()if m else-1for m in(re.search(c+'(?![^(]*\))',s)for c in'21')];return i>0and f'2({f(s[:i])},{f(s[i+1:])})'or j>=0and f'1({f(s[:j])or f(s[j+1:])})'or s

Explanation & ungolfed version:

import re

def f(s):
    s=s.strip('()')
    # Search for '2' and '1' outside of brackets
    i, j = [m.start() if m else -1
            for m in (re.search(c + '(?![^(]*\))', s) for c in '21')]

    if i > 0:
        # Call `f(s[:i])` and `f(s[i+1:])`, concatenate the results
        return f'2({f(s[:i])},{f(s[i+1:])})'
    elif j>=0:
        # Call `f(s[:j])` and `f(s[j+1:])`, choose the non-empty result
        return f'1({f(s[:j]) or f(s[j+1:])})'
    else:
        return s


答:
Clojure, <s>132</s> 131 bytes

```<code>(fn [n](loop[N 1 M[0]F[1]](if(< N n)(let[M(conj M(- N(F(peek M))))F(conj F(- N(M(peek F))))](recur(inc N)M F))(do(prn F)(prn M)))))
</code>```

Simply builds the sequences iteratively up from zero to n.

Ungolfed version

```<code>(fn [n]
  (loop [N 1 M [0] F [1]]
    (if (< N n)
      (let [M (conj M (- N (F (peek M))))
            F (conj F (- N (M (peek F))))]
        (recur (inc N) M F))
      (do
        (prn F)
        (prn M)))))
</code>```

Title: Female and Male Sequences

Body:
Clojure, <s>132</s> 131 bytes

(fn [n](loop[N 1 M[0]F[1]](if(< N n)(let[M(conj M(- N(F(peek M))))F(conj F(- N(M(peek F))))](recur(inc N)M F))(do(prn F)(prn M)))))

Simply builds the sequences iteratively up from zero to n.

Ungolfed version

(fn [n]
  (loop [N 1 M [0] F [1]]
    (if (< N n)
      (let [M (conj M (- N (F (peek M))))
            F (conj F (- N (M (peek F))))]
        (recur (inc N) M F))
      (do
        (prn F)
        (prn M)))))


答:
GNU Sed, 28

Score includes +1 for -r option to sed.

```<code>:
s/([^0-9])([0-9])/\2\1/
t
</code>```

Repeatedly switches one non-number character followed by one number character until no more substitutions are made.

Sadly sed regexes don't have \d or \D, so these have to be written out longhand.

Ideone.

Title: Separate alphabets and numbers

Body:
GNU Sed, 28

Score includes +1 for -r option to sed.

:
s/([^0-9])([0-9])/\2\1/
t

Repeatedly switches one non-number character followed by one number character until no more substitutions are made.

Sadly sed regexes don't have \d or \D, so these have to be written out longhand.

Ideone.


答:
Pyth - 11 bytes

Don't like my grouping test. Takes input as list of lines, tell me if that's not ok.

```<code>jms_.g}k`MT
</code>```

Try it online here.

Title: Separate alphabets and numbers

Body:
Pyth - 11 bytes

Don't like my grouping test. Takes input as list of lines, tell me if that's not ok.

jms_.g}k`MT

Try it online here.


答:
Jolf, 10 bytes

```<code>/uΜr0xdlBH
</code>```

Try it here!

Explanation

```<code>/uΜr0xdlBH
  Μr0x      map range 0..x
      dlBH  over lengths of binary elements
/u          divide sum of this
            by implicit input (x)
</code>```

Title: Mean bits: an average challenge

Body:
Jolf, 10 bytes

/uΜr0xdlBH

Try it here!

Explanation

/uΜr0xdlBH
  Μr0x      map range 0..x
      dlBH  over lengths of binary elements
/u          divide sum of this
            by implicit input (x)


问:
Goldbach's conjecture
Write a program that prompts the user for an even integer greater than 2.

Given Goldbach’s conjecture that every even integer greater than 2 can
be expressed as the sum of two primes, print out two prime numbers which, when
added together, provide the requested even number.
Edit: the program only has to print A PAIR of primes, not all.
For example:

4 : 2 + 2

6: 3 + 3

8: 3 + 5

10: 5 + 5 or 3 + 7

答:
Python 3, 107 bytes

```<code>b=lambda x:all(x%y for y in range(2,x))
g=lambda x,i=2:((i,x-i)if b(i)&b(x-i)else g(x,i+1))if(i<x)else 0
</code>```

b(x) is a primality test for x, and g(x) recurses through numbers to find two primes that fit.

Title: Goldbach's conjecture

Body:
Python 3, 107 bytes

b=lambda x:all(x%y for y in range(2,x))
g=lambda x,i=2:((i,x-i)if b(i)&b(x-i)else g(x,i+1))if(i<x)else 0

b(x) is a primality test for x, and g(x) recurses through numbers to find two primes that fit.


答:
Clojure, 113 bytes

```<code>(fn[s](map(fn[x](println(apply str(sort-by #(when-not(Character/isDigit %)1)x))))(clojure.string/split-lines s)))
</code>```

Sorts digits to the beginning of the line.

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:
Clojure, 113 bytes

(fn[s](map(fn[x](println(apply str(sort-by #(when-not(Character/isDigit %)1)x))))(clojure.string/split-lines s)))

Sorts digits to the beginning of the line.


答:
C# (LINQ), 110 bytes

```<code>s=>string.join("",s.Where(c=>"0123456789".Contains(c).Concat(s.SelectMany(c=>new[]{c}.Except("0123456789"))));
</code>```

Not the shortest solution, by far, but I thought this would be a good use of LINQ.

Title: Separate alphabets and numbers

Body:
C# (LINQ), 110 bytes

s=>string.join("",s.Where(c=>"0123456789".Contains(c).Concat(s.SelectMany(c=>new[]{c}.Except("0123456789"))));

Not the shortest solution, by far, but I thought this would be a good use of LINQ.


答:
Matlab(189)

```<code>  function u=f(n),if(~n|n==1)u=n;else,u=n;y=factor(n);z=y(y~=2);if ~isempty(z),t=y(y~=max(y));if isempty(t),u=y(end)*2^(nnz(y)-1);else,g=max(t);e=primes(g*2);u=n/g*e(find(e==g)+1);end,end,end
</code>```

The function:

Maps any integer according to its prime factors, if the number is nil or factorised into 2 or 1, the number is mapped to itself, otherwise we pick the biggest prime factor of this number, then we increment the remaining different prime factors by the closest bigger prime factor until we reach the number biggest_prime^n where n is the sum of all exponents of all factors, once we reach that amount, we turn to max_prime*2^(n-1) and we reproduce the same cycle again.

Title: Every Possible Cycle Length

Body:
A function (or program) which takes inputs and provides outputs can be said to have a cycle if calling the function on its own output repeatedly eventually reaches the original number. For instance, take the following function:

```<code>Input:  n    1 2 3 4 5 6
Output: f(n) 5 7 1 3 4 9
</code>```

If we start with n=1, f(n)=5, f(f(n))=f(5)=4, f(f(f(n)))=f(4)=3, f(f(f(f(n))))=f(3)=1.

This is written (1 5 4 3). Since there are 4 unique numbers in this loop, this is a cycle of length 4.

Your challenge is to write a program or function which has cycles of every possible length. That is, there must be a cycle of length 1, of length 2, and so on.

In addition, your function/program must be from the positive integers to positive integers, and it must be bijective, meaning that there must be a exactly one input value for every possible output value, over all positive integers. To put it another way, the function/program must compute a permutaion of the positive integers.

Details: Any standard input/output system is allowed, including STDIN, STDOUT, function argument, return, etc. Standard loopholes prohibited.

You do not need to worry about the limitations of your data types - the above properties need only hold under the assumption that an int or float can hold any value, for instance.

There are no restrictions on the behavior of the function on inputs which are not positive integers, and those inputs/outputs will be ignored.

Scoring is code golf in bytes, shortest code wins.

Body:
Matlab(189)

  function u=f(n),if(~n|n==1)u=n;else,u=n;y=factor(n);z=y(y~=2);if ~isempty(z),t=y(y~=max(y));if isempty(t),u=y(end)*2^(nnz(y)-1);else,g=max(t);e=primes(g*2);u=n/g*e(find(e==g)+1);end,end,end

The function:

Maps any integer according to its prime factors, if the number is nil or factorised into 2 or 1, the number is mapped to itself, otherwise we pick the biggest prime factor of this number, then we increment the remaining different prime factors by the closest bigger prime factor until we reach the number biggest_prime^n where n is the sum of all exponents of all factors, once we reach that amount, we turn to max_prime*2^(n-1) and we reproduce the same cycle again.


答:
#import instead of #include gives you one more byte.

Also, the space character between #import and header is not necessarily:

```<code>#include <map>
// vs
#import<map>
</code>```

And if you need something from stdlib header, you may import any header with STL container (preferable set or map) instead of cstdlib.

Title: Tips for golfing in C++

Body:
What general tips do you have for golfing in C++?

I'm looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to C++ (e.g. "remove comments" is not an answer). Please post one tip per answer.

(Tips that apply to C as well can be found in Tips for golfing in C - but note that some C tips don't work in C++.  For example, C++ does require function prototypes and return values.)

Body:
#import instead of #include gives you one more byte.

Also, the space character between #import and header is not necessarily:

#include <map>
// vs
#import<map>

And if you need something from stdlib header, you may import any header with STL container (preferable set or map) instead of cstdlib.


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

—taken nearly verbatim from marcog's question.

答:
Use Boolean logic in place of if-counters in a loop

Suppose you're adding all even numbers from 1 to 10 ... 2+4+6+8+10=30

```<code>1..10|%{if($_%2-eq0){$o+=$_}};$o
</code>```

You could use Boolean negation to shorten it to

```<code>1..10|%{if(!($_%2)){$o+=$_}};$o
</code>```

to save a byte, but how about instead use implicit casting of Booleans to ints, and roll the conditional into the accumulator

```<code>1..10|%{$o+=$_*!($_%2)};$o
</code>```

Saves 6 bytes in this example.

Title: Tips for golfing in PowerShell

Body:
Use Boolean logic in place of if-counters in a loop

Suppose you're adding all even numbers from 1 to 10 ... 2+4+6+8+10=30

1..10|%{if($_%2-eq0){$o+=$_}};$o

You could use Boolean negation to shorten it to

1..10|%{if(!($_%2)){$o+=$_}};$o

to save a byte, but how about instead use implicit casting of Booleans to ints, and roll the conditional into the accumulator

1..10|%{$o+=$_*!($_%2)};$o

Saves 6 bytes in this example.


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

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

The Rules

Each submission must be a full program.

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

The program must not write anything to STDERR.

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

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

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

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

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

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

For inspiration, check the Hello World Collection.

The Catalogue

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

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

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

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

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

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

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

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

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

/* Configuration */

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

/* App */

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

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

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

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

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

getAnswers();

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

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

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

function process() {
  var valid = [];

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

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

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

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

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

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

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

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

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

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

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

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

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

table thead {
  font-weight: bold;
}

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

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

Shortest Solution by Language

Language	User	Score

Leaderboard

	Author	Language	Size

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

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

```

答:
64-bit Windows NT executable, 261591 bytes

Because why not?

Anyway, here's a 89,890-byte ZIP archive containing this executable: http://pastebin.com/raw/pJ6CeNuG (encoded in Base64)

------EDIT------

we don't allow link-only answers for off-site code

Okay. The C code I compiled the executable from is the classic Hello World program:

```<code>#include "stdio.h" // Use <cstdio> on C++
int main(){
    printf("Hello, World!");
}
</code>```

The compiler is GCC without optimizations. Maybe other compilers (such as Intel C(++) Compiler or Clang) can generate smaller executables.

Title: "Hello, World!"

Body:
64-bit Windows NT executable, 261591 bytes

Because why not?

Anyway, here's a 89,890-byte ZIP archive containing this executable: http://pastebin.com/raw/pJ6CeNuG (encoded in Base64)

------EDIT------

we don't allow link-only answers for off-site code

Okay. The C code I compiled the executable from is the classic Hello World program:

#include "stdio.h" // Use <cstdio> on C++
int main(){
    printf("Hello, World!");
}

The compiler is GCC without optimizations. Maybe other compilers (such as Intel C(++) Compiler or Clang) can generate smaller executables.


答:
Matlab(137)

```<code>  function u=h(n),if(~n|n==1)u=n;else,u=n;y=factor(n);z=y(y~=2);if~isempty(z),e=nnz(y);f=nnz(z);if(~mod(e,f)&e-f)u=n/2^(e-f);else,u=u*2;end
</code>```

A slightly similar approach, multiplying gradually any number not equal to {0,1,2^n} by 2 until we stumble upon an exponent of 2 which is divisible by sum of exponents of other prime factors. then we move to the beginning of the cycle dividing by 2^(sum of exponents of other primes). the other numbes are mapped to themselves.

Title: Every Possible Cycle Length

Body:
Matlab(137)

  function u=h(n),if(~n|n==1)u=n;else,u=n;y=factor(n);z=y(y~=2);if~isempty(z),e=nnz(y);f=nnz(z);if(~mod(e,f)&e-f)u=n/2^(e-f);else,u=u*2;end

A slightly similar approach, multiplying gradually any number not equal to {0,1,2^n} by 2 until we stumble upon an exponent of 2 which is divisible by sum of exponents of other prime factors. then we move to the beginning of the cycle dividing by 2^(sum of exponents of other primes). the other numbes are mapped to themselves.


答:
Jelly, 8 bytes

Not shorter, but interesting algorithm, and my first Jelly submission:

```<code>Rl2Ċ»1S÷

R         1 to n
 l2       log2
   Ċ      ceiling
    »1    max of 1 and...
      S   sum
       ÷  divided by n
</code>```

Title: Mean bits: an average challenge

Body:
Given an integer N >= 1, output the mean number of bits in an integer from 0 to N - 1

Specification

The output can be calculated as the sum of the number of bits in the binary representation of each integer from 0 to N-1, divided by N.

The binary representation of an integer has no leading zeroes in this context, with the exception of zero, which is represented as 0 in binary.

The output should be accurate to at least 7 significant figures.

Example

N = 6

```<code>0: 0   : 1 bit
1: 1   : 1 bit
2: 10  : 2 bits
3: 11  : 2 bits
4: 100 : 3 bits
5: 101 : 3 bits
</code>```

Mean number of bits = (1 + 1 + 2 + 2 + 3 + 3) / 6 = 2

Test cases

Input => output

```<code>1 => 1
2 => 1
3 => 1.3333333
4 => 1.5
5 => 1.8
6 => 2
7 => 2.1428571
</code>```

Leaderboard Snippet

(from here)

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

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

```

Note that the sum (before dividing to find the mean) is a sequence on OEIS.

Body:
Jelly, 8 bytes

Not shorter, but interesting algorithm, and my first Jelly submission:

Rl2Ċ»1S÷

R         1 to n
 l2       log2
   Ċ      ceiling
    »1    max of 1 and...
      S   sum
       ÷  divided by n


答:
Dyalog APL, 14 bytes

```<code>(+/1⌈(⌈2⍟⍳))÷⊢

range ← ⍳
log   ← ⍟
log2  ← 2 log range
ceil  ← ⌈
bits  ← ceil log2
max   ← ⌈
fix0  ← 1 max bits
sum   ← +/
total ← sum fix0
self  ← ⊢
div   ← ÷
mean  ← sum div self
</code>```

Title: Mean bits: an average challenge

Body:
Dyalog APL, 14 bytes

(+/1⌈(⌈2⍟⍳))÷⊢

range ← ⍳
log   ← ⍟
log2  ← 2 log range
ceil  ← ⌈
bits  ← ceil log2
max   ← ⌈
fix0  ← 1 max bits
sum   ← +/
total ← sum fix0
self  ← ⊢
div   ← ÷
mean  ← sum div self