答:
PowerShell v4+, <s>453</s> <s>455</s> <s>435</s> <s>427</s> 417 bytes

```<code>param([char[]]$a,$b)if(!$b){0;0;0;'','';exit}$a|%{$b=$b-split$_};$c=@{};if($z=($b|group|?{$_.count-eq1}).Name){$z|%{$m+=$c[$_]=$_.length}}if($l=$c.count){$c=$c.GetEnumerator()|sort v}else{$l=2}$m/$l;if($l%2){$c[[math]::Floor($l/2)].Value}else{($c[$l/2].value+$c[$l/2-1].value)/2}if($x=($c|group value|sort c -des)|%{if($_.count-ge$i){$i=$_.count;$_.name}}){$m=$b|?{$_.length-in$x}}else{$m=@()}$x;($b|?{$_-notin$m}),$m
</code>```

(Saved 7 bytes by eliminating $d and reusing $c instead. Saved <s>13</s> <s>21</s> 31 bytes thanks to @Joey)

What a mess. Below is a slightly more readable version, broken down into sections. I also included -join on the two potentially-array outputs to make the output more clear visually, as well as surrounding the last one in distinct delimiters #-> and <-# to indicate the sub-arrays. I did this since PowerShell's Write-Output for multiple array return values can get a little confusing when just looking at them on the console.

```<code>param([char[]]$a,$b)if(!$b){0;0;0;'','';exit}$a|%{$b=$b-split$_}
$c=@{}
if($z=($b|group|?{$_.count-eq1}).Name){$z|%{$m+=$c[$_]=$_.length}}
if($l=$c.count){$c=$c.GetEnumerator()|sort v}else{$l=2}
$m/$l
if($l%2){$c[[math]::Floor($l/2)].Value}else{($c[$l/2].value+$c[$l/2-1].value)/2}
if($x=($c|group value|sort c -des)|%{if($_.count-ge$i){$i=$_.count;$_.name}}){$m=$b|?{$_.length-in$x}}else{$m=@()}
$x-join','
"#->" + ((($b|?{$_-notin$m})-join','),($m-join',')-join'<-# #->') + "<-#"
</code>```

Takes input $a and $b (separators and string), and explicitly casts $a right away as a char-array. The if(!$b) clause handles the special case where $b is an empty string - it dumps zeros and empty strings onto the pipeline and exits. Otherwise we loop through $a with $a|%{...}, each loop -splitting $b by the current character and re-saving into $b.

The next line sets $c as an empty hashtable. This is used as the temporary storage location for the non-duplicated values in $b and their corresponding lengths.

That's the next line. We take $b, pump it through Group-Object to put like words together, pipe that to Where-Object to select only those where the .count is -equal to 1. We then take the .Name of those (here's where the v4+ requirement comes into play), and store those .Names (i.e., the words) into $z. We then take the .count of that, and that number forms our if clause -- so long as it's non-zero (i.e., we have at least one unique word), we pump those words through a loop. Each iteration we accumulate $m by, and also store into $c, the corresponding word's .length.

Next line sorts $c on lengths (that's the |sort value in the middle) and stores that back to $c, but we need to have some logic to account for cases where $z was empty (i.e., every word is a duplicate). If that's the situation, $c is already an empty hashtable, but we set $l equal to 2 to handle the mean calculation later.

Now, we're to our outputs. The first $m/$l just calculates the average length. The next line calculates the median based on either taking the exact middle value of $c, or taking the two above and below the middle and splitting the difference.

The next line is very complicated, and was where the longest troubleshooting was. It's calculating the mode. We start by Grouping $c based on value (i.e., the word lengths), then Sort-Object them by their count in -descending order (i.e., the most-common lengths will be first). That list is fed into a loop. Each iteration, if the current item's $_.count is greater-than-or-equal-to $i (which initializes to $null or 0, here), meaning that we've got a length that's the most-common, set $i equal to how many of that length there are, and add the length ($_.name) to the pipeline. That resulting array of most-common lengths is stored into $x.

Provided that we have at least one most-common length, the if triggers and we pipe $b through another Where-Object. This time, we're selecting all of the words where the .length is -in $x (i.e., all of the words that have a length that's in the mode), and store them into $m (yes, I reused a variable name). Else, we don't have a most-common length, so the strings of the mode is empty.

The next line $x-join',' outputs the lengths of the mode. Then, the words in $b that aren't in $m and the words in $m, as two sub-arrays.

Test suite

```<code>PS C:\Tools\Scripts\golfing> @(@(',;/','hello,hello;there;my/yes/my/dear,blue,world'),@('+|',''),@('','ppcg.se.com'),@(',;',',math,,math;'),@(',;','new,math,math;!;'))|%{"Testing: '"+$_[0]+"' '"+$_[1]+"'";.\fun-with-strings.ps1 $_[0] $_[1];"---------------------------------------------------------------------------------------"}
Testing: ',;/' 'hello,hello;there;my/yes/my/dear,blue,world'
4.2
5
4,5
#->my,yes,my<-# #->hello,hello,there,dear,blue,world<-#
---------------------------------------------------------------------------------------
Testing: '+|' ''
0
0
0

---------------------------------------------------------------------------------------
Testing: '' 'ppcg.se.com'
11
11
11
#-><-# #->ppcg.se.com<-#
---------------------------------------------------------------------------------------
Testing: ',;' ',math,,math;'
0
0

#->,math,,math,<-# #-><-#
---------------------------------------------------------------------------------------
Testing: ',;' 'new,math,math;!;'
1.33333333333333
1
3,1,0
#->math,math<-# #->new,!,<-#
---------------------------------------------------------------------------------------
</code>```

Title: Fun with strings and string lengths

Body:
Introduction

Inspired by Dyalog Ltd.'s 2016 student competition. The challenge there is to write good APL code, but this is a code-golf and it is open to all languages. Derived from this closed challenge.

The real challenge here is to combine the various (quite trivial) parts of the problem in a byte-efficient way by reusing values and/or algorithms.

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

Task

Take two strings (of any 7-bit ASCII characters) by any means and order (but please include input format in your answer). You may take them as separate arguments/inputs or as a single list of strings. One string contains the delimiters in the other. E.g. given ',;/' and 'hello,hello;there;my/yes/my/dear,blue,world', the sub-strings are ['hello', 'hello', 'there', 'my', 'yes', 'my', 'dear', 'blue', and 'world'].

You will do some statistics and ordering based on the lengths of those sub-strings that are not duplicated in the input. (You may chose to consider casing or not.) In the example given, those are ['there', 'yes', 'dear', 'blue', 'world'].

Give (by any means) a list of four elements in the overall structure [Number_1, Number_2, [List_3], [[List_4_1], [List_4_2]]]:

The mean of the lengths of the non-duplicated strings. In our example, that is 4.2

The median of the lengths of the non-duplicated strings. In our example, that is 4.

The mode(s) of the lengths of the non-duplicated strings. In our example, that is [4, 5].

The original sub-strings (including duplicates), divided into two lists; the first are those that are not one of the above mode lengths, and the second are those that are. In our example: [['my', 'my', 'yes'], ['dear', 'blue', 'hello', 'hello', 'there', 'world']]

The combined final answer of our example case is: [4.2, 4, [4, 5], [['my', 'my', 'yes'], ['dear', 'blue', 'hello', 'hello', 'there', 'world']]]

Considerations

Don't forget to reuse code and values. E.g. the median is the average of the 1 or 2 middle elements, and you'll need the mode(s) to reorder the original list.

Watch out for division by zero; an empty input means one string with length zero, so the mean length is zero. If there are no non-unique sub-strings, return zero for both mean and median, an empty list for modes, and put all original sub-strings onto the non-mode list.

The list of modes, and the sub-lists of non-mode-length strings, and mode-length strings, do not need to be sorted in any way.

If all non-duplicated sub-strings have different lengths, then all the lengths are considered modes.

Wherever the term list is used, you may use any collection of multiple data pieces that your language supports, e.g. tuples, arrays, dictionaries, etc.

The numeric values only need to be within 1% of the actual value.

Example cases

Example A

',;/' 'hello,hello;there;my/yes/my/dear,blue,world'

gives

[4.2, 4, [4, 5], [['my', 'my', 'yes'], ['dear', 'blue', 'hello', 'hello', 'there', 'world']]

Example B

'+|' ''

gives

[0, 0, [0], [[], ['']]]

Note: while there are two delimiter characters, none of them occur in the data string, so this is just one empty string. Mean, median, and mode are therefore zero There are no strings in the non-mode list and just the single empty string in the mode list.

Example C

'' 'ppcg.se.com'

gives

[11, 11, [11], [[], ['ppcg.se.com']]]

Note: no delimiters, so the entire input is one string.

Example D

',;' ',math,,math;'

gives

[0, 0, [], [['', 'math', '', 'math', ''], []]]

Note: there are three empty sub-strings, and since all sub-strings have at least one duplicate, the mean and median default to zero, as per Considerations, above.

Example E

',;' 'new,math,math;!;'

gives

[1.333, 1, [0,1,3], [['math', 'math'], ['new', '!', '']]]

Note: there is only one of each length among the non-duplicated sub-strings, so all three lengths are modes.

You can verify my explicit permission to post this challenge here by contacting the author of the original competition.

Body:
PowerShell v4+, <s>453</s> <s>455</s> <s>435</s> <s>427</s> 417 bytes

param([char[]]$a,$b)if(!$b){0;0;0;'','';exit}$a|%{$b=$b-split$_};$c=@{};if($z=($b|group|?{$_.count-eq1}).Name){$z|%{$m+=$c[$_]=$_.length}}if($l=$c.count){$c=$c.GetEnumerator()|sort v}else{$l=2}$m/$l;if($l%2){$c[[math]::Floor($l/2)].Value}else{($c[$l/2].value+$c[$l/2-1].value)/2}if($x=($c|group value|sort c -des)|%{if($_.count-ge$i){$i=$_.count;$_.name}}){$m=$b|?{$_.length-in$x}}else{$m=@()}$x;($b|?{$_-notin$m}),$m

(Saved 7 bytes by eliminating $d and reusing $c instead. Saved <s>13</s> <s>21</s> 31 bytes thanks to @Joey)

What a mess. Below is a slightly more readable version, broken down into sections. I also included -join on the two potentially-array outputs to make the output more clear visually, as well as surrounding the last one in distinct delimiters #-> and <-# to indicate the sub-arrays. I did this since PowerShell's Write-Output for multiple array return values can get a little confusing when just looking at them on the console.

param([char[]]$a,$b)if(!$b){0;0;0;'','';exit}$a|%{$b=$b-split$_}
$c=@{}
if($z=($b|group|?{$_.count-eq1}).Name){$z|%{$m+=$c[$_]=$_.length}}
if($l=$c.count){$c=$c.GetEnumerator()|sort v}else{$l=2}
$m/$l
if($l%2){$c[[math]::Floor($l/2)].Value}else{($c[$l/2].value+$c[$l/2-1].value)/2}
if($x=($c|group value|sort c -des)|%{if($_.count-ge$i){$i=$_.count;$_.name}}){$m=$b|?{$_.length-in$x}}else{$m=@()}
$x-join','
"#->" + ((($b|?{$_-notin$m})-join','),($m-join',')-join'<-# #->') + "<-#"

Takes input $a and $b (separators and string), and explicitly casts $a right away as a char-array. The if(!$b) clause handles the special case where $b is an empty string - it dumps zeros and empty strings onto the pipeline and exits. Otherwise we loop through $a with $a|%{...}, each loop -splitting $b by the current character and re-saving into $b.

The next line sets $c as an empty hashtable. This is used as the temporary storage location for the non-duplicated values in $b and their corresponding lengths.

That's the next line. We take $b, pump it through Group-Object to put like words together, pipe that to Where-Object to select only those where the .count is -equal to 1. We then take the .Name of those (here's where the v4+ requirement comes into play), and store those .Names (i.e., the words) into $z. We then take the .count of that, and that number forms our if clause -- so long as it's non-zero (i.e., we have at least one unique word), we pump those words through a loop. Each iteration we accumulate $m by, and also store into $c, the corresponding word's .length.

Next line sorts $c on lengths (that's the |sort value in the middle) and stores that back to $c, but we need to have some logic to account for cases where $z was empty (i.e., every word is a duplicate). If that's the situation, $c is already an empty hashtable, but we set $l equal to 2 to handle the mean calculation later.

Now, we're to our outputs. The first $m/$l just calculates the average length. The next line calculates the median based on either taking the exact middle value of $c, or taking the two above and below the middle and splitting the difference.

The next line is very complicated, and was where the longest troubleshooting was. It's calculating the mode. We start by Grouping $c based on value (i.e., the word lengths), then Sort-Object them by their count in -descending order (i.e., the most-common lengths will be first). That list is fed into a loop. Each iteration, if the current item's $_.count is greater-than-or-equal-to $i (which initializes to $null or 0, here), meaning that we've got a length that's the most-common, set $i equal to how many of that length there are, and add the length ($_.name) to the pipeline. That resulting array of most-common lengths is stored into $x.

Provided that we have at least one most-common length, the if triggers and we pipe $b through another Where-Object. This time, we're selecting all of the words where the .length is -in $x (i.e., all of the words that have a length that's in the mode), and store them into $m (yes, I reused a variable name). Else, we don't have a most-common length, so the strings of the mode is empty.

The next line $x-join',' outputs the lengths of the mode. Then, the words in $b that aren't in $m and the words in $m, as two sub-arrays.

Test suite

PS C:\Tools\Scripts\golfing> @(@(',;/','hello,hello;there;my/yes/my/dear,blue,world'),@('+|',''),@('','ppcg.se.com'),@(',;',',math,,math;'),@(',;','new,math,math;!;'))|%{"Testing: '"+$_[0]+"' '"+$_[1]+"'";.\fun-with-strings.ps1 $_[0] $_[1];"---------------------------------------------------------------------------------------"}
Testing: ',;/' 'hello,hello;there;my/yes/my/dear,blue,world'
4.2
5
4,5
#->my,yes,my<-# #->hello,hello,there,dear,blue,world<-#
---------------------------------------------------------------------------------------
Testing: '+|' ''
0
0
0

---------------------------------------------------------------------------------------
Testing: '' 'ppcg.se.com'
11
11
11
#-><-# #->ppcg.se.com<-#
---------------------------------------------------------------------------------------
Testing: ',;' ',math,,math;'
0
0

#->,math,,math,<-# #-><-#
---------------------------------------------------------------------------------------
Testing: ',;' 'new,math,math;!;'
1.33333333333333
1
3,1,0
#->math,math<-# #->new,!,<-#
---------------------------------------------------------------------------------------


问:
List of possible birth years of living humans
The Challenge

Output a list of years that starts with the current year and ends 120 years ago. The birth year of every living human would be included in this list.

Details

The list should be in descending order.

Every built-in function to manipulate arrays and/or lists is allowed.

Shortest code in bytes wins.

When run this year 2016, the output would be

2016, 2015, ..., 1897, 1896

When run next year 2017, the output would be

2017, 2016, ..., 1898, 1897

Etc.

Update

Some have asked about the format of the list. As most have guessed, it doesn't matter. Insert any separator between the numbers. Intuitively most inserted a comma or space or both, newline or output an array.

Quasi superhumans like Jeanne Calment are an exception to the rule stated in my question.

答:
MATLAB, 18 bytes

Assuming the output format doesn't matter (aside form descending order), the following program prints the last 121 years starting with the current one.

```<code>year(date)-(0:120)
</code>```

It requires MATLAB version r2014a or higher. Earlier versions didn't include the year function.

ContentLicense: CC BY-SA 4.0

Body:
MATLAB, 18 bytes

Assuming the output format doesn't matter (aside form descending order), the following program prints the last 121 years starting with the current one.

year(date)-(0:120)

It requires MATLAB version r2014a or higher. Earlier versions didn't include the year function.

ContentLicense: CC BY-SA 3.0


问:
Sort the months of the year
Write a function or program that takes string inputs, fully-spelled, English month names in title case: January, February, March, etc. (null/CR/LF terminated OK, delimited with some non-alpha character if you so choose) and either

compares two inputs, returning a Truthy value if the second input is greater (in month order) than the first. Equal values result in a Falsey value

or sorts an arbitrary sequence (list, delimited string, etc.) of them in chronological order

(The crux of the challenge is defining a method/expression that gives the correct lexicographical sort. Some languages might have a shorter answer with one or the other)

You cannot use any internal time parsing methods (e.g. strptime) to translate the month name into a number or a pre-canned mapping of month names. Use properties of the strings themselves, a parsimonious look-up table you define, or something clever.

Example

Functioning examples, though the first is prohibited by the rules...

```<code>import datetime
def is_later_month(a, b):
    '''
    Example of prohibited code because it relies on language
    features about how to parse month names
    '''
    return datetime.strptime(a, '%B') < datetime.strptime(b, '%B')
</code>```

The below versions are OK though, because we code that info

```<code>months = {
    'January':  1, 'February':  2, 'March':      3,
    'April':    4, 'May':       5, 'June':       6,
    'July':     7, 'August':    8, 'September':  9,
    'October': 10, 'November': 11, 'December':  12,
}
def is_later_month(a, b):
    """
    Returns True/False when comparing two months.
    """
    return months[a] < months[b]
</code>```

Or you could do a sorting function

```<code>months = {'as above...'}
def sort_months(l):
    """
    Sorts list and returns it. Different input and output than the above,
    but equally valid. Sorting versus comparing might be shorter in your
    favorite language.
    """
    return sorted(l, key=lambda x: months[x])
</code>```

Example tests

```<code>assert is_later_month('January', 'February')
assert is_later_month('January', 'December')
assert is_later_month('November', 'December')
assert not is_later_month('July', 'July')
assert not is_later_month('October', 'September')
</code>```

答:
Java, <s>133</s> 123

Golfed:

boolean f(String a,String b){return h(a)<h(b);}int h(String s){return"anebarprayunulugepctovec".indexOf(s.substring(1,3));}
```

<p>I was searching for a clever technique like in the assembler answer, but it was taking too long to figure out so I went with the same technique everyone else used.</p>

<p>Ungolfed:</p>

<pre class="lang-java prettyprint-override"><code>import java.util.Random;

public class SortTheMonthsOfTheYear {

  public static void main(String[] args) {
    // @formatter:off
    String[] MONTHS = new String[] {
        "January", "February", "March",
        "April",   "May",      "June",
        "July",    "August",   "September",
        "October", "November", "December"
    };
    // @formatter:on

    Random r = new Random();
    for (int i = 0; i < 100; ++i) {
      int m1 = r.nextInt(MONTHS.length);
      int m2 = r.nextInt(MONTHS.length);
      System.out.println("Input: " + MONTHS[m1] + " < " + MONTHS[m2]);
      System.out.println("Expected: " + (m1 < m2));
      System.out.println("Actual:   " + new SortTheMonthsOfTheYear().f(MONTHS[m1], MONTHS[m2]));
      System.out.println();
    }
  }

  // Begin golf
  boolean f(String a, String b) {
    return h(a) < h(b);
  }

  int h(String s) {
    return "anebarprayunulugepctovec".indexOf(s.substring(1, 3));
  }
  // End golf

}
</code>```

Title: Sort the months of the year

Body:
Java, <s>133</s> 123

Golfed:

boolean f(String a,String b){return h(a)<h(b);}int h(String s){return"anebarprayunulugepctovec".indexOf(s.substring(1,3));}

I was searching for a clever technique like in the assembler answer, but it was taking too long to figure out so I went with the same technique everyone else used.

Ungolfed:

import java.util.Random;

public class SortTheMonthsOfTheYear {

  public static void main(String[] args) {
    // @formatter:off
    String[] MONTHS = new String[] {
        "January", "February", "March",
        "April",   "May",      "June",
        "July",    "August",   "September",
        "October", "November", "December"
    };
    // @formatter:on

    Random r = new Random();
    for (int i = 0; i < 100; ++i) {
      int m1 = r.nextInt(MONTHS.length);
      int m2 = r.nextInt(MONTHS.length);
      System.out.println("Input: " + MONTHS[m1] + " < " + MONTHS[m2]);
      System.out.println("Expected: " + (m1 < m2));
      System.out.println("Actual:   " + new SortTheMonthsOfTheYear().f(MONTHS[m1], MONTHS[m2]));
      System.out.println();
    }
  }

  // Begin golf
  boolean f(String a, String b) {
    return h(a) < h(b);
  }

  int h(String s) {
    return "anebarprayunulugepctovec".indexOf(s.substring(1, 3));
  }
  // End golf

}


问:
Is it a Proth number?
A Proth number, named after François Proth, is a number that can be expressed as

$$N = k \times 2^n + 1$$

Where \$k\$ is an odd positive integer and \$n\$ is a positive integer such that \$2^n > k\$. Let's use a more concrete example. Take 3. 3 is a Proth number because it can be written as

$$ 3 = (1 \times 2^1) + 1 $$

and \$2^1 > 1\$ is satisfied. 5 Is also a Proth number because it can be written as

$$ 5 = (1 \times 2^2) + 1 $$

and \$2^2 > 1\$ is satisfied. However, 7 is not a Proth number because the only way to write it in the form \$N = k \times 2^n + 1\$ is

$$ 7 = (3 \times 2^1) + 1 $$

and \$2^1 > 3\$ is not satisfied.

Your challenge is fairly simple: you must write a program or function that, given a positive integer, determines if it is a Proth number or not. You may take input in any reasonable format, and should output a truthy value if it is a Proth number and a falsy value if it is not. If your language has any "Proth-number detecting" functions, you may use them.

Test IO

Here are the first 46 Proth numbers up to 1000. (A080075)

```<code>3, 5, 9, 13, 17, 25, 33, 41, 49, 57, 65, 81, 97, 113, 129, 145, 161, 177, 193, 209, 225, 241, 257, 289, 321, 353, 385, 417, 449, 481, 513, 545, 577, 609, 641, 673, 705, 737, 769, 801, 833, 865, 897, 929, 961, 993
</code>```

Every other valid input should give a falsy value.

As usual, this is code-golf, so standard loopholes apply, and the shortest answer in bytes wins!

Number theory fun-fact side-note:

The largest known prime that is not a Mersenne Prime is \$19249 \times 2^{13018586} + 1\$, which just so happens to also be a Proth number!

答:
C (137 bytes)

int P(int N){int x=1,n=0,k=1,e=1,P=0;for(;e;n++){for(x=1,k=1;x&&x<N;k+=2){x=2<<n;x=x>k?x*k+1:0;if(x>N&&k==1)e=0;}if(x==N)P=1;}return P;}
```

Only came to read the answers after I tried it.

Considering N=k*2^n+1 with the conditional of k<2^n (k=1,3,5.. and n=1,2,3..

With n=1 we have one k available to test. As we increase n we get a few more k's to test like so:

n=1 ; k=1

n=2 ; k=1 k=3

n=3 ; k=1 k=3 k=5 k=7

...

Iterating through those possibilities we can be sure N is not a Prouth number if for a given n the k=1 number obtained is larger than N and no other iteration was a match.

So my code basically "brute-forces" its way into finding N.

After reading the other answers and realizing you can factor N-1 with 2 to find n and then make the conditional of k<2^n, I think my code could be smaller and more efficient using this method.

It was worth a try!

Tested all numbers given and a few "non-Prouth" numbers. Function returns 1 if the number is a Prouth number and 0 if it's not.

Title: Is it a Proth number?

Body:
C (137 bytes)

int P(int N){int x=1,n=0,k=1,e=1,P=0;for(;e;n++){for(x=1,k=1;x&&x<N;k+=2){x=2<<n;x=x>k?x*k+1:0;if(x>N&&k==1)e=0;}if(x==N)P=1;}return P;}

Only came to read the answers after I tried it.

Considering N=k*2^n+1 with the conditional of k<2^n (k=1,3,5.. and n=1,2,3..

With n=1 we have one k available to test. As we increase n we get a few more k's to test like so:

n=1 ; k=1

n=2 ; k=1 k=3

n=3 ; k=1 k=3 k=5 k=7

...

Iterating through those possibilities we can be sure N is not a Prouth number if for a given n the k=1 number obtained is larger than N and no other iteration was a match.

So my code basically "brute-forces" its way into finding N.

After reading the other answers and realizing you can factor N-1 with 2 to find n and then make the conditional of k<2^n, I think my code could be smaller and more efficient using this method.

It was worth a try!

Tested all numbers given and a few "non-Prouth" numbers. Function returns 1 if the number is a Prouth number and 0 if it's not.


答:
ListSharp, 71 bytes

```<code>NUMB a=<c#DateTime.Now.Yearc#>
[FOREACH NUMB IN a TO a-120 AS y]
SHOW=y
</code>```

Uses embedded c# code, new feature!!

Title: List of possible birth years of living humans

Body:
The Challenge

Output a list of years that starts with the current year and ends 120 years ago. The birth year of every living human would be included in this list.

Details

The list should be in descending order.

Every built-in function to manipulate arrays and/or lists is allowed.

Shortest code in bytes wins.

When run this year 2016, the output would be

2016, 2015, ..., 1897, 1896

When run next year 2017, the output would be

2017, 2016, ..., 1898, 1897

Etc.

Update

Some have asked about the format of the list. As most have guessed, it doesn't matter. Insert any separator between the numbers. Intuitively most inserted a comma or space or both, newline or output an array.

Quasi superhumans like Jeanne Calment are an exception to the rule stated in my question.

Body:
ListSharp, 71 bytes

NUMB a=<c#DateTime.Now.Yearc#>
[FOREACH NUMB IN a TO a-120 AS y]
SHOW=y

Uses embedded c# code, new feature!!


答:
PostgreSQL, 57 bytes

Who needs a FROM :-).  Probably shouldn't work, but it does, try it at sqlfiddle

```<code>select date_part('y',current_date)-generate_series(0,120)
</code>```

Body:
PostgreSQL, 57 bytes

Who needs a FROM :-).  Probably shouldn't work, but it does, try it at sqlfiddle

select date_part('y',current_date)-generate_series(0,120)


答:
Fourier, 17 bytes

```<code>121(5d-io10ai^~i)
</code>```

Since no output format is specified, each year is separated by a newline:

Try it online

Body:
Fourier, 17 bytes

121(5d-io10ai^~i)

Since no output format is specified, each year is separated by a newline:

Try it online


答:
Nim, 60 bytes

import times
for a in 0..120:echo getTime().getGmTime.year-a
```

Outputs each year on a new line. We use the getTime to get the current UNIX time, then convert it to UTC with getGmTime, get the year minus the counter variable, and echo it.

Body:
Nim, 60 bytes

import times
for a in 0..120:echo getTime().getGmTime.year-a

Outputs each year on a new line. We use the getTime to get the current UNIX time, then convert it to UTC with getGmTime, get the year minus the counter variable, and echo it.


问:
Input ∩ Source Code

Intro

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

Let I be the input set

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

Let S be the source code set

{"b","f"}

Then the intersection is what they share

I ∩ S = {"b"}

Input

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

Output

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

Output is flexible:

Could be any data structure (string or otherwise)

Could unordered

Could have a trailing \n

Should be distinct

Restriction

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

Examples

#1

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

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

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

#2

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

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

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

#3

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

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

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

Test Cases

```<code>Albert Einstein

\__( O__O)_/

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

1234567890-=[]\;',./

(ノಠ益ಠ)ノ彡┻━┻

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

┬──┬ ノ( ゜-゜ノ)

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

Update

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

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

答:
ListSharp, 222 bytes

```<code>STRG S=READ[<here>+"\\S.txt"]
ROWS T=ROWSPLIT S BY [""]
ROWS R=ROWSPLIT "STRG =EAD[<her>+\".tx]OWPLIBYCFMHVNc#isn()oay\r\n" BY [""]
ROWS R=SELECT FROM T WHERE[EVERY STRG IS ANY STRG IN R]
SHOW=<c#R.Distinct().ToArray()c#>
</code>```

ridiculous but im entertained

Title: Input ∩ Source Code

Body:
ListSharp, 222 bytes

STRG S=READ[<here>+"\\S.txt"]
ROWS T=ROWSPLIT S BY [""]
ROWS R=ROWSPLIT "STRG =EAD[<her>+\".tx]OWPLIBYCFMHVNc#isn()oay\r\n" BY [""]
ROWS R=SELECT FROM T WHERE[EVERY STRG IS ANY STRG IN R]
SHOW=<c#R.Distinct().ToArray()c#>

ridiculous but im entertained


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

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

I/O

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

Restrictions on web use

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

Scoring

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

Test Cases

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

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

Tip

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

答:
ListSharp, 266 bytes

```<code>STRG a=READ[<here>+"\\a.txt"]
ROWS x=ROWSPLIT a BY [","]
STRG a=GETRANGE x[0] FROM [2] TO [a LENGTH]
NUMB y=<c#int.Parse(x[1])c#>
STRG a=DOWNLOAD["http://oeis.org/b"+a+".txt"]
ROWS x=ROWSPLIT a BY [<newline>]
STRG a=GETLINE x [y]
ROWS x=ROWSPLIT a BY [" "]
SHOW=x[1]
</code>```

Its sad when a language made for web scraping needs so many lines because nesting statements in ListSharp is taboo

Title: Automate the OEIS

Body:
ListSharp, 266 bytes

STRG a=READ[<here>+"\\a.txt"]
ROWS x=ROWSPLIT a BY [","]
STRG a=GETRANGE x[0] FROM [2] TO [a LENGTH]
NUMB y=<c#int.Parse(x[1])c#>
STRG a=DOWNLOAD["http://oeis.org/b"+a+".txt"]
ROWS x=ROWSPLIT a BY [<newline>]
STRG a=GETLINE x [y]
ROWS x=ROWSPLIT a BY [" "]
SHOW=x[1]

Its sad when a language made for web scraping needs so many lines because nesting statements in ListSharp is taboo


问:
Print a 10 by 10 grid of asterisks

Background

This is a standard textbook example to demonstrate for loops.

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

Task

You are to print this exact text:

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

Specs

You may have extra trailing newlines.

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

Scoring

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

答:
MSM, 19 bytes

```<code>.;;.;...;.;;.;..␍**
</code>```

where ␍ is a newline.

. concatenates the two rightmost characters and ; appends a copy of the rightmost element to the end, so the first commands .;;.;... create one line **********␍ and the next commands ;.;;.;.. make 10 lines out of it.

Title: Print a 10 by 10 grid of asterisks

Body:
MSM, 19 bytes

.;;.;...;.;;.;..␍**

where ␍ is a newline.

. concatenates the two rightmost characters and ; appends a copy of the rightmost element to the end, so the first commands .;;.;... create one line **********␍ and the next commands ;.;;.;.. make 10 lines out of it.


Body:
Batch, 67 bytes

@set/ay=%date:~-4%,z=y-120
@for /l %%i in (%y%,-1,%z%)do @echo %%i


答:
C# <s>110</s> <s>109</s> <s>107</s> <s>103</s> <s>101</s> 94 Bytes

```<code>using i=System.Numerics.BigInteger;i f(i n){i a=0,b=1,x=1;for(;n-->0;)x*=a=(b+=a)-a;return x;}
</code>```

Explanation

```<code>//Aliasing BigInteger saves a few bytes
using i=System.Numerics.BigInteger;

//Since BigInteger has an implicit from int we can also change the input
//and save two more bytes.
i f(i n)
{
    //using an alternative iterative algorithm (link to source below) to cut out the temp variable
    //b is next iteration, a is current iteration, and x is the running product
    i a = 0, b = 1, x = 1;

    //post decrement n down to zero instead of creating a loop variable
    for (; n-- > 0;)

        //The bracket portion sets the next iteration
        //get the current iteration and update our running product
        x *= a = (b += a) - a;

    return x;
}
</code>```

Iterative Fib algorithm

Title: Fibonacci-orial

Body:
Definition

Fibonacci sequence F(n), on the positive integers, are defined as such:

```<code>1. F(1) = 1
2. F(2) = 1
3. F(n) = F(n-1) + F(n-2), where n is an integer and n > 2
</code>```

The Fibonacci-orial of a positive integer is the product of [F(1), F(2), ..., F(n)].

Task

Given positive integer n, find the Fibonacci-orial of n.

Specs

The fibonacci-orial of 100 must compute in under 5 seconds on a reasonable computer.

Testcases

```<code>n   Fibonacci-orial of n
1   1
2   1
3   2
4   6
5   30
6   240
7   3120
8   65520
9   2227680
10  122522400
11  10904493600
12  1570247078400
13  365867569267200
14  137932073613734400
15  84138564904377984000
16  83044763560621070208000
17  132622487406311849122176000
18  342696507457909818131702784000
19  1432814097681520949608649339904000
20  9692987370815489224102512784450560000
100 3371601853146468125386964065447576689828006172937411310662486977801540671138589868616500834190029067583665182291701553172011082574587431382310099030394306877775647395167143332483560925112960024644459715300507481235056111434293619038347456390454209587101225261757371666449068625033999573552165524529725467628060170886602001077137613803027158648329335507728698605769992818756765633305318529965186184043999696650407246193257877568825245646129366994079739720698147440310773871269639752334356493678913424390564535389212240038895626811627949132978086070255082668392290037141141291484839596694182152062726390364094447642643912371532491388089634845995941928089653751672688740718152064107169357399466473375804972260594768969952507346694189050233823596316467570584434128052398891223730335019092974935617029638919358286124350711360361279157416837428904150054292406756317837582840596331363581207781793070936765786629772999832857257349696094416616259974304208756997835360702840912518532683324936435856348020736000000000000000000000000
</code>```

References

Obligatory OEIS A003266

OEIS A000045 - Fibonacci sequence

Body:
C# <s>110</s> <s>109</s> <s>107</s> <s>103</s> <s>101</s> 94 Bytes

using i=System.Numerics.BigInteger;i f(i n){i a=0,b=1,x=1;for(;n-->0;)x*=a=(b+=a)-a;return x;}

Explanation

//Aliasing BigInteger saves a few bytes
using i=System.Numerics.BigInteger;

//Since BigInteger has an implicit from int we can also change the input
//and save two more bytes.
i f(i n)
{
    //using an alternative iterative algorithm (link to source below) to cut out the temp variable
    //b is next iteration, a is current iteration, and x is the running product
    i a = 0, b = 1, x = 1;

    //post decrement n down to zero instead of creating a loop variable
    for (; n-- > 0;)

        //The bracket portion sets the next iteration
        //get the current iteration and update our running product
        x *= a = (b += a) - a;

    return x;
}

Iterative Fib algorithm


问:
Compiled quine variant
Thinking about various quine puzzles here, I got an idea for another one:

Compose a program that outputs its own compiled code to a file (or multiple files, if the compiled code is). (This means that only compiled languages are eligible.)

Rules

Standard quine rules - no cheating allowed. In particular:

The program cannot read the compiled code from disk, cannot store it somewhere etc. It must compute it somehow without external help.

If the program is compiled to several files (i.e. several Java .class files), it must output them all.

You can use any existing libraries available for your language. However:

The libraries you use cannot be something created just for this task. (For example in order to keep some information away from what's considered to be the program.)

Any libraries you use must be older than your program. You cannot just create a program that loads a piece of data from an external library, compile the program, and copy the compiled code into the library - that'd be cheating.

You cannot embed a compiler of your language in any form. In particular, you cannot just take a standard quine and hook it up with a compiler to produce the compiled output.

As mentioned, only compiled languages are eligible. You can use a scripting language as long as it can be compiled to a bytecode that's reasonably different from the source form (if you're not sure, better ask).

Notes

Most likely, this puzzle can be solved reasonably only in languages that compile to some sort of bytecode that can be manipulated. For example, Java and compiled bytecode seems good for the task. (But if you find a genuine solution in some other compiled language, that's fine too, as long as it isn't some sort of cheating.)

Submission

Don't submit the compiled program (as this could be potentially dangerous). Instead post your sources and a description what to do to create the final program.

Evaluation

Let voters decide the best solution. Personally I'd appreciate solution that are elegant, short (in their source form) and didactic - that explain what's going on.

Bonuses

Bonus points for

Let the program output a compressed file containing its compiled code. This has the additional benefit that if the program is compiled into more files, the output will be a single packed file. For example, in Java try to create an executable JAR file that outputs the JAR itself.

Outputting the MD5 sum of the compiled file(s) - so the program would write its compiled code and its MD5 sum.

答:
Assembly (DOS .com file)

```<code>start:

%rep 2
    call $+3

    mov ah, 9
    mov dx, 100h + (end - start) / 2
    int 21h

    mov ah, 2
    mov dl, "$" - 1
    inc dx
    int 21h

    ret
    db "$"

%endrep

end:
</code>```

Assemble with nasm quine.asm -o quine.com. Try with dosbox quine.com.

Proof of correctness (you can also verify by the smilies here):

Title: Compiled quine variant

Body:
Assembly (DOS .com file)

start:

%rep 2
    call $+3

    mov ah, 9
    mov dx, 100h + (end - start) / 2
    int 21h

    mov ah, 2
    mov dl, "$" - 1
    inc dx
    int 21h

    ret
    db "$"

%endrep

end:

Assemble with nasm quine.asm -o quine.com. Try with dosbox quine.com.

Proof of correctness (you can also verify by the smilies here):


问:
Make a (somewhat) self-referential string
You want to make a string where the (1-indexed) character at index n is n. When n is less than 10, this is easy: "123456789". When n is 12, for example, it becomes impossible, since numbers greater than 9 (in base 10) take up more than one character. We can compromise by dividing the string into two-character substrings: "020406081012". Now the index of the end of each substring n is n.

This can be generalized for any d-digit number. Here's an explanation for the "0991021" part of the string for a three-digit number:

```<code>Index:     ... * 97  98  99*100 101 102*103 ...
               *           *           *
               *---+---+---*---+---+---*---+
Character: ... * 0 | 9 | 9 * 1 | 0 | 2 * 1 | ...
               *---+---+---*---+---+---*---+
</code>```

If you haven't figured it out yet, you are to write a program/function that takes a string or integer and output its self-referential string as specified above. You can also output an array of single-digit numbers, chars, or single-character strings.

The given integer will always be positive and divisible by its length (e.g. 126 is divisible by 3; 4928 is divisible by 4). Your program should theoretically work for an arbitrarily large input, but you can assume it is smaller than your language's maximum integer and/or string length.

Some observations if you still don't get it: The length of the output will always be the input itself, and the numbers that appear in the output will be divisible by the number of digits in the input.

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

Test cases

```<code>1    => 1
9    => 123456789
10   => 0204060810
105  => 003006009012015018021024027030033036039042045048051054057060063066069072075078081084087090093096099102105
1004 => 00040008001200160020002400280032003600400044004800520056006000640068007200760080008400880092009601000104010801120116012001240128013201360140014401480152015601600164016801720176018001840188019201960200020402080212021602200224022802320236024002440248025202560260026402680272027602800284028802920296030003040308031203160320032403280332033603400344034803520356036003640368037203760380038403880392039604000404040804120416042004240428043204360440044404480452045604600464046804720476048004840488049204960500050405080512051605200524052805320536054005440548055205560560056405680572057605800584058805920596060006040608061206160620062406280632063606400644064806520656066006640668067206760680068406880692069607000704070807120716072007240728073207360740074407480752075607600764076807720776078007840788079207960800080408080812081608200824082808320836084008440848085208560860086408680872087608800884088808920896090009040908091209160920092409280932093609400944094809520956096009640968097209760980098409880992099610001004
</code>```

答:
05AB1E, 15 bytes

Code:

```<code>LD¹gÖÏvy0¹g×0ñ?
</code>```

Explanation:

```<code>L                # Get the array [1, ..., input].
 D               # Duplicate this array.
  ¹g             # Get the length of the first input.
    Ö            # Check if it's divisible by input length.
     Ï           # Keep those elements.
      vy         # For each...
         ¹g      # Get the length of the first input.
        0  ×     # String multiply that with "0".
            0ñ   # Merge with the number.
              ?  # Pop and print without a newline.
</code>```

The merging is done like this:

From these:

```<code>000
 12
</code>```

It results into this:

```<code>012
</code>```

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

Body:
05AB1E, 15 bytes

Code:

LD¹gÖÏvy0¹g×0ñ?

Explanation:

L                # Get the array [1, ..., input].
 D               # Duplicate this array.
  ¹g             # Get the length of the first input.
    Ö            # Check if it's divisible by input length.
     Ï           # Keep those elements.
      vy         # For each...
         ¹g      # Get the length of the first input.
        0  ×     # String multiply that with "0".
            0ñ   # Merge with the number.
              ?  # Pop and print without a newline.

The merging is done like this:

From these:

000
 12

It results into this:

012

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


答:
Mathematica + OEIS.m, 31

```<code>(OEISFunction@ToString@#;#@#2)&
</code>```

example usage: %[A172141,36]

Mathematica, 85

```<code>#2/.Rule@@@Import["http://oeis.org/b"<>#~StringDrop~1<>".txt","Data"]~DeleteCases~{}&
</code>```

example usage: %["A002206",-1]

Title: Automate the OEIS

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

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

I/O

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

Restrictions on web use

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

Scoring

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

Test Cases

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

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

Tip

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

Body:
Mathematica + OEIS.m, 31

(OEISFunction@ToString@#;#@#2)&

example usage: %[A172141,36]

Mathematica, 85

#2/.Rule@@@Import["http://oeis.org/b"<>#~StringDrop~1<>".txt","Data"]~DeleteCases~{}&

example usage: %["A002206",-1]


答:
MATL, <s>15</s> 14 bytes

```<code>VntG3$:10YA!1e
</code>```

Try it online!

```<code>V        % Implicitly input number, n. Convert to string
n        % Length of that string, s
t        % Duplicate s
G        % Push n again
3$:      % 3-input range (s,s,n): generates [s, 2*s, ... ] up to <=n
10YA     % Convert each number to base 10. This gives a 2D array of char, with each
         % number on a row, left-padded with zeros if needed
!1e      % Reshape into a string, reading in row-major order. Implicitly display
</code>```

Title: Make a (somewhat) self-referential string

Body:
You want to make a string where the (1-indexed) character at index n is n. When n is less than 10, this is easy: "123456789". When n is 12, for example, it becomes impossible, since numbers greater than 9 (in base 10) take up more than one character. We can compromise by dividing the string into two-character substrings: "020406081012". Now the index of the end of each substring n is n.

This can be generalized for any d-digit number. Here's an explanation for the "0991021" part of the string for a three-digit number:

```<code>Index:     ... * 97  98  99*100 101 102*103 ...
               *           *           *
               *---+---+---*---+---+---*---+
Character: ... * 0 | 9 | 9 * 1 | 0 | 2 * 1 | ...
               *---+---+---*---+---+---*---+
</code>```

If you haven't figured it out yet, you are to write a program/function that takes a string or integer and output its self-referential string as specified above. You can also output an array of single-digit numbers, chars, or single-character strings.

The given integer will always be positive and divisible by its length (e.g. 126 is divisible by 3; 4928 is divisible by 4). Your program should theoretically work for an arbitrarily large input, but you can assume it is smaller than your language's maximum integer and/or string length.

Some observations if you still don't get it: The length of the output will always be the input itself, and the numbers that appear in the output will be divisible by the number of digits in the input.

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

Test cases

```<code>1    => 1
9    => 123456789
10   => 0204060810
105  => 003006009012015018021024027030033036039042045048051054057060063066069072075078081084087090093096099102105
1004 => 00040008001200160020002400280032003600400044004800520056006000640068007200760080008400880092009601000104010801120116012001240128013201360140014401480152015601600164016801720176018001840188019201960200020402080212021602200224022802320236024002440248025202560260026402680272027602800284028802920296030003040308031203160320032403280332033603400344034803520356036003640368037203760380038403880392039604000404040804120416042004240428043204360440044404480452045604600464046804720476048004840488049204960500050405080512051605200524052805320536054005440548055205560560056405680572057605800584058805920596060006040608061206160620062406280632063606400644064806520656066006640668067206760680068406880692069607000704070807120716072007240728073207360740074407480752075607600764076807720776078007840788079207960800080408080812081608200824082808320836084008440848085208560860086408680872087608800884088808920896090009040908091209160920092409280932093609400944094809520956096009640968097209760980098409880992099610001004
</code>```

Body:
MATL, <s>15</s> 14 bytes

VntG3$:10YA!1e

Try it online!

V        % Implicitly input number, n. Convert to string
n        % Length of that string, s
t        % Duplicate s
G        % Push n again
3$:      % 3-input range (s,s,n): generates [s, 2*s, ... ] up to <=n
10YA     % Convert each number to base 10. This gives a 2D array of char, with each
         % number on a row, left-padded with zeros if needed
!1e      % Reshape into a string, reading in row-major order. Implicitly display


答:
sed, 47 characters

```<code>:s;st[^])(*\1.s2t:[;^]tt;st\(.\)\(.*\1\)t\2t;ts
</code>```

I'm a little disappointed at how long this came out to be, especially the bit to remove repeated characters.

Title: Input ∩ Source Code

Body:
Intro

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

Let I be the input set

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

Let S be the source code set

{"b","f"}

Then the intersection is what they share

I ∩ S = {"b"}

Input

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

Output

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

Output is flexible:

Could be any data structure (string or otherwise)

Could unordered

Could have a trailing \n

Should be distinct

Restriction

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

Examples

#1

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

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

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

#2

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

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

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

#3

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

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

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

Test Cases

```<code>Albert Einstein

\__( O__O)_/

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

1234567890-=[]\;',./

(ノಠ益ಠ)ノ彡┻━┻

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

┬──┬ ノ( ゜-゜ノ)

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

Update

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

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

Body:
sed, 47 characters

:s;st[^])(*\1.s2t:[;^]tt;st\(.\)\(.*\1\)t\2t;ts

I'm a little disappointed at how long this came out to be, especially the bit to remove repeated characters.


答:
2sable, 13 bytes

Code:

```<code>g©÷F®N>*0®×0ñ
</code>```

Uses the CP-1252 encoding.

Body:
2sable, 13 bytes

Code:

g©÷F®N>*0®×0ñ

Uses the CP-1252 encoding.


答:
JavaScript (ES6), 83 bytes

```<code>n=>[...Array(n/(l=`${n}`.length))].map((_,i)=>`${+`1e${l}`+l*++i}`.slice(1)).join``
</code>```

Yes, that's a nested template string. 79 bytes in ES7:

```<code>n=>[...Array(n/(l=`${n}`.length))].map((_,i)=>`${10**l+l*++i}`.slice(1)).join``
</code>```

Body:
JavaScript (ES6), 83 bytes

n=>[...Array(n/(l=`${n}`.length))].map((_,i)=>`${+`1e${l}`+l*++i}`.slice(1)).join``

Yes, that's a nested template string. 79 bytes in ES7:

n=>[...Array(n/(l=`${n}`.length))].map((_,i)=>`${10**l+l*++i}`.slice(1)).join``


答:
C, 64 bytes

```<code>l,i;main(n){for(scanf("%d%n",&n,&l);i<n;)printf("%0*d",l,i+=l);}
</code>```

Takes a single integer as input on stdin.

Body:
C, 64 bytes

l,i;main(n){for(scanf("%d%n",&n,&l);i<n;)printf("%0*d",l,i+=l);}

Takes a single integer as input on stdin.


答:
Python 2, <s>78</s> <s>70</s> <s>68</s> <s>64</s> 63 bytes

Actually basing on the idea of Destructible Watermelon makes it even smaller (using input is even better)(filling the string backward saves 4 bytes)(no () at while):

n,s=input(),''
l=len(`n`)
while n:s=`n`.zfill(l)+s;n-=l
print s
```

<p>Here is the old 70 byte approach (Saving 8 bytes by using backquotes instead of <code>str</code> and dropping the square brackets around generator thanks to Dennis):</p>

<pre class="lang-python prettyprint-override"><code>def f(n):l=len(`n`);print"".join(`x`.zfill(l)for x in range(l,n+l,l))
</code>```

Body:
Python 2, <s>78</s> <s>70</s> <s>68</s> <s>64</s> 63 bytes

Actually basing on the idea of Destructible Watermelon makes it even smaller (using input is even better)(filling the string backward saves 4 bytes)(no () at while):

n,s=input(),''
l=len(`n`)
while n:s=`n`.zfill(l)+s;n-=l
print s

Here is the old 70 byte approach (Saving 8 bytes by using backquotes instead of str and dropping the square brackets around generator thanks to Dennis):

def f(n):l=len(`n`);print"".join(`x`.zfill(l)for x in range(l,n+l,l))


答:
Python <s>3</s> 2, <s>79</s> <s>74</s> <s>69</s> <s>65</s> <s>68</s> 67 bytes

Thanks Dennis!

```<code>def f(n):i=l=len(`n`);s='';exec n/l*"s+=`i`.zfill(l);i+=l;";print s
</code>```

byte count increase from bad output method

Body:
Python <s>3</s> 2, <s>79</s> <s>74</s> <s>69</s> <s>65</s> <s>68</s> 67 bytes

Thanks Dennis!

def f(n):i=l=len(`n`);s='';exec n/l*"s+=`i`.zfill(l);i+=l;";print s

byte count increase from bad output method


答:
Bash on OS X, 23

jot 121 `date +%Y` - -1
```

This will also work on Linux if you have BSD jot installed (e.g. sudo apt-get install athena-jot.

Body:
The Challenge

Output a list of years that starts with the current year and ends 120 years ago. The birth year of every living human would be included in this list.

Details

The list should be in descending order.

Every built-in function to manipulate arrays and/or lists is allowed.

Shortest code in bytes wins.

When run this year 2016, the output would be

2016, 2015, ..., 1897, 1896

When run next year 2017, the output would be

2017, 2016, ..., 1898, 1897

Etc.

Update

Some have asked about the format of the list. As most have guessed, it doesn't matter. Insert any separator between the numbers. Intuitively most inserted a comma or space or both, newline or output an array.

Quasi superhumans like Jeanne Calment are an exception to the rule stated in my question.

Body:
Bash on OS X, 23

jot 121 `date +%Y` - -1

This will also work on Linux if you have BSD jot installed (e.g. sudo apt-get install athena-jot.


答:
Bash, <s>31</s> 22 bytes

seq -ws '' ${#1}{,} $1
```

Test it on Ideone.

Thanks to @izabera for golfing off 6 bytes!

Body:
Bash, <s>31</s> 22 bytes

seq -ws '' ${#1}{,} $1

Test it on Ideone.

Thanks to @izabera for golfing off 6 bytes!


问:
Lemon-Limify a String
Write a program or function that takes in a nonempty single-line string. You may assume it only contains printable ASCII excluding space.

Print or return an ASCII art lozenge shape similar to a lemon or lime made from the prefixes of the string.

Suppose the input string is n letters long. Then, such a shape consists of 2n − 1 columns of ASCII art stitched together, each consisting of 2n − 1 lines. Counting from 1, the k-th column is f(k) = min(k, 2n − k) characters wide, and contains f(k) copies of the first f(k) characters of input, centered vertically, with single blank lines separating the copies.

For example, if the input is Lemon, the output should be:

```<code>          Lemon
      Lemo     Lemo
   Lem    Lemon    Lem
 Le   Lemo     Lemo   Le
L  Lem    Lemon    Lem  L
 Le   Lemo     Lemo   Le
   Lem    Lemon    Lem
      Lemo     Lemo
          Lemon
</code>```

If the input is lime the output should be:

```<code>      lime
   lim    lim
 li   lime   li
l  lim    lim  l
 li   lime   li
   lim    lim
      lime
</code>```

And the same pattern is followed for other inputs:

```<code>a

a

Be

 Be
B  B
 Be

/\

 /\
/  /
 /\

cat

   cat
 ca   ca
c  cat  c
 ca   ca
   cat

|||

   |||
 ||   ||
|  |||  |
 ||   ||
   |||

.__.

      .__.
   .__    .__
 ._   .__.   ._
.  .__    .__  .
 ._   .__.   ._
   .__    .__
      .__.

$tring

               $tring
          $trin      $trin
      $tri     $tring     $tri
   $tr    $trin      $trin    $tr
 $t   $tri     $tring     $tri   $t
$  $tr    $trin      $trin    $tr  $
 $t   $tri     $tring     $tri   $t
   $tr    $trin      $trin    $tr
      $tri     $tring     $tri
          $trin      $trin
               $tring
</code>```

Lines in the output may have trailing spaces and there may be one optional trailing newline.

The shortest code in bytes wins.

Title: Lemon-Limify a String

Body:
Haskell, 109 bytes

f s|n<-length s,r<-[1..n]++[n-1,n-2..1]=unlines[do x<-r;min(" ~"!!mod((x+y+n)*min(n-x-y)0)2)<$>take x s|y<-r]


答:
Python 2, 63 bytes

def f(n):l=len(`n`);print'%%0%dd'%l*(n/l)%tuple(range(l,n+1,l))
```

Test it on Ideone.

Body:
Python 2, 63 bytes

def f(n):l=len(`n`);print'%%0%dd'%l*(n/l)%tuple(range(l,n+1,l))

Test it on Ideone.


答:
Javascript - 76

```<code>n=>eval('c="";for(a=b=(""+n).length;a<=n;a+=b)c+=`${+`1e${b}`+a}`.slice(1)')
</code>```

or 71 if allowing for string arguments:

```<code>n=>eval('c="";for(a=b=n.length;a<=n;a+=b)c+=`${+`1e${b}`+a}`.slice(1)')
</code>```

Thanks to @user81655!

Ungolfed:

```<code>function x(n)
{
   c = "", a = b = (""+n).length;
   while(a<=n)
   {
       c=c+"0".repeat(b-(""+a).length)+a
       a+=b;
   }
   return c;
}
</code>```

much place for improvement, but i'm tired right now

Body:
Javascript - 76

n=>eval('c="";for(a=b=(""+n).length;a<=n;a+=b)c+=`${+`1e${b}`+a}`.slice(1)')

or 71 if allowing for string arguments:

n=>eval('c="";for(a=b=n.length;a<=n;a+=b)c+=`${+`1e${b}`+a}`.slice(1)')

Thanks to @user81655!

Ungolfed:

function x(n)
{
   c = "", a = b = (""+n).length;
   while(a<=n)
   {
       c=c+"0".repeat(b-(""+a).length)+a
       a+=b;
   }
   return c;
}

much place for improvement, but i'm tired right now


答:
Maple, 100 bytes (including spaces)

```<code>IsProth:=proc(X)local n:=0;local x:=X-1;while x mod 2<>1 do x:=x/2;n:=n+1;end do;is(2^n>x);end proc:
</code>```

Nicely spaced for readbility:

```<code>IsProth := proc( X )
    local n := 0;
    local x := X - 1;
    while x mod 2 <> 1 do
        x := x / 2;
        n := n + 1;
    end do;
    is( 2^n > x );
end proc:
</code>```

Same idea as several others; divide X by 2 until X is no longer evenly divisible by 2, then check the criteria 2^n > x.

Title: Is it a Proth number?

Body:
A Proth number, named after François Proth, is a number that can be expressed as

$$N = k \times 2^n + 1$$

Where \$k\$ is an odd positive integer and \$n\$ is a positive integer such that \$2^n > k\$. Let's use a more concrete example. Take 3. 3 is a Proth number because it can be written as

$$ 3 = (1 \times 2^1) + 1 $$

and \$2^1 > 1\$ is satisfied. 5 Is also a Proth number because it can be written as

$$ 5 = (1 \times 2^2) + 1 $$

and \$2^2 > 1\$ is satisfied. However, 7 is not a Proth number because the only way to write it in the form \$N = k \times 2^n + 1\$ is

$$ 7 = (3 \times 2^1) + 1 $$

and \$2^1 > 3\$ is not satisfied.

Your challenge is fairly simple: you must write a program or function that, given a positive integer, determines if it is a Proth number or not. You may take input in any reasonable format, and should output a truthy value if it is a Proth number and a falsy value if it is not. If your language has any "Proth-number detecting" functions, you may use them.

Test IO

Here are the first 46 Proth numbers up to 1000. (A080075)

```<code>3, 5, 9, 13, 17, 25, 33, 41, 49, 57, 65, 81, 97, 113, 129, 145, 161, 177, 193, 209, 225, 241, 257, 289, 321, 353, 385, 417, 449, 481, 513, 545, 577, 609, 641, 673, 705, 737, 769, 801, 833, 865, 897, 929, 961, 993
</code>```

Every other valid input should give a falsy value.

As usual, this is code-golf, so standard loopholes apply, and the shortest answer in bytes wins!

Number theory fun-fact side-note:

The largest known prime that is not a Mersenne Prime is \$19249 \times 2^{13018586} + 1\$, which just so happens to also be a Proth number!

Body:
Maple, 100 bytes (including spaces)

IsProth:=proc(X)local n:=0;local x:=X-1;while x mod 2<>1 do x:=x/2;n:=n+1;end do;is(2^n>x);end proc:

Nicely spaced for readbility:

IsProth := proc( X )
    local n := 0;
    local x := X - 1;
    while x mod 2 <> 1 do
        x := x / 2;
        n := n + 1;
    end do;
    is( 2^n > x );
end proc:

Same idea as several others; divide X by 2 until X is no longer evenly divisible by 2, then check the criteria 2^n > x.


答:
Jelly, 12 bytes

```<code>VRUmLDUz0ZFU
</code>```

I/O is in form of digit arrays. Try it online! or verify all test cases.

How it works

```<code>VRUmLDUz0ZFU  Main link. Argument: A (digit array)

V             Eval; turn the digits in A into an integer n.
 R            Range; yield [1, ..., n].
  U           Upend; reverse to yield [n, ..., 1].
    L         Yield the length (l) of A.
   m          Modular; keep every l-th integer in A.
     D        Decimal; convert each kept integer into the array of its digits.
      U       Upend; reverse the digits of each integer.
       z0     Zip/transpose with fill value 0.
         Z    Zip again.
              This right-pads all digit arrays with zeroes.
          F   Flatten the resulting 2D array.
           U  Upend/reverse it.
</code>```

Body:
You want to make a string where the (1-indexed) character at index n is n. When n is less than 10, this is easy: "123456789". When n is 12, for example, it becomes impossible, since numbers greater than 9 (in base 10) take up more than one character. We can compromise by dividing the string into two-character substrings: "020406081012". Now the index of the end of each substring n is n.

This can be generalized for any d-digit number. Here's an explanation for the "0991021" part of the string for a three-digit number:

```<code>Index:     ... * 97  98  99*100 101 102*103 ...
               *           *           *
               *---+---+---*---+---+---*---+
Character: ... * 0 | 9 | 9 * 1 | 0 | 2 * 1 | ...
               *---+---+---*---+---+---*---+
</code>```

If you haven't figured it out yet, you are to write a program/function that takes a string or integer and output its self-referential string as specified above. You can also output an array of single-digit numbers, chars, or single-character strings.

The given integer will always be positive and divisible by its length (e.g. 126 is divisible by 3; 4928 is divisible by 4). Your program should theoretically work for an arbitrarily large input, but you can assume it is smaller than your language's maximum integer and/or string length.

Some observations if you still don't get it: The length of the output will always be the input itself, and the numbers that appear in the output will be divisible by the number of digits in the input.

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

Test cases

```<code>1    => 1
9    => 123456789
10   => 0204060810
105  => 003006009012015018021024027030033036039042045048051054057060063066069072075078081084087090093096099102105
1004 => 00040008001200160020002400280032003600400044004800520056006000640068007200760080008400880092009601000104010801120116012001240128013201360140014401480152015601600164016801720176018001840188019201960200020402080212021602200224022802320236024002440248025202560260026402680272027602800284028802920296030003040308031203160320032403280332033603400344034803520356036003640368037203760380038403880392039604000404040804120416042004240428043204360440044404480452045604600464046804720476048004840488049204960500050405080512051605200524052805320536054005440548055205560560056405680572057605800584058805920596060006040608061206160620062406280632063606400644064806520656066006640668067206760680068406880692069607000704070807120716072007240728073207360740074407480752075607600764076807720776078007840788079207960800080408080812081608200824082808320836084008440848085208560860086408680872087608800884088808920896090009040908091209160920092409280932093609400944094809520956096009640968097209760980098409880992099610001004
</code>```

Body:
Jelly, 12 bytes

VRUmLDUz0ZFU

I/O is in form of digit arrays. Try it online! or verify all test cases.

How it works

VRUmLDUz0ZFU  Main link. Argument: A (digit array)

V             Eval; turn the digits in A into an integer n.
 R            Range; yield [1, ..., n].
  U           Upend; reverse to yield [n, ..., 1].
    L         Yield the length (l) of A.
   m          Modular; keep every l-th integer in A.
     D        Decimal; convert each kept integer into the array of its digits.
      U       Upend; reverse the digits of each integer.
       z0     Zip/transpose with fill value 0.
         Z    Zip again.
              This right-pads all digit arrays with zeroes.
          F   Flatten the resulting 2D array.
           U  Upend/reverse it.


问:
Swap 2 objects, without using a temporary variable
There are two objects:

```<code>Object1, Object2
</code>```

You can easily swap them by:

```<code>Object3 = Object1
Object1 = Object2
Object2 = Object3
</code>```

However, you must solve this problem by using no temporary object and Object1 should be changed to Object 2. (and vice versa)

答:
Perl

```<code>($object1, $object2) = ($object2, $object1);
</code>```

Using Perl's list assertions feels like cheating, but it's a pretty common feature.

Body:
Perl

($object1, $object2) = ($object2, $object1);

Using Perl's list assertions feels like cheating, but it's a pretty common feature.


Body:
Brachylog, <s>53</s> <s>45</s> <s>42</s> <s>37</s> 28 bytes

<s>lB,?ybeN:B%0,N:ef:{,"0":"9"y:?m.}acAl:Br-:"0"rjb:Acw\</s>
<s>lB,?ybeN:B%0,10:B^:N+:ef:{,"0":"9"y:?m.}acbw\</s>
<s>lB,?ybeN:B%0,10:B^:N+:ef:{:16+:@Prm.}acbw\</s>
<s>lB,?ybeN:B%0,10:B^:N+:efbe:16+:@Prmw\</s>
lB,?ybeN:B%0,10:B^:N+:efbew\

Try it online!


答:
ARM machine language on Linux <s>44</s> 40 bytes

```<code>e28fc001     add ip, pc, #1
e12fff1c     bx ip
6803         ldr r3, [r0, #0]
6808         ldr r0, [r1, #0]
4a05         ldr r2, [pc, #20]
f08303dd     eor.w r3, r3, #221
f08000dd     eor.w r0, r0, #221
4353         muls r3, r2
4350         muls r0, r2
4283         cmp r3, r0
bfac         ite ge
2000         movge r0, #0
2001         movlt r0, #1
4770         bx lr
2f68f24c
</code>```

I used a different hash function than anatolyg's solution and tried to use thumb instructions to save a few bytes (though I blew 8 bytes entering thumb mode).

You can try this out on a Raspberry Pi or Android device with GNURoot.

```<code>int main(int argc,char**argv){
return ((int(*)(char*,char*))"\
\1\xc0\x8f\xe2\
\x1c\xff\x2f\xe1\
\3\x68\x8\x68\
\5\x4a\x83\xf0\
\xdd\3\x80\xf0\
\xdd\x43\x53\x43\
\x50\x4a\x83\x42\
\xac\bf\0\x20\
\1\x20\x70\x47\
\x4c\xf2\x68\x2f\
")(argv[1],argv[2]);}
</code>```

To run enter something like

```<code>$ ./foo January February; echo $?
</code>```

The current version now handles the equality case (and others) correctly.

Title: Sort the months of the year

Body:
Write a function or program that takes string inputs, fully-spelled, English month names in title case: January, February, March, etc. (null/CR/LF terminated OK, delimited with some non-alpha character if you so choose) and either

compares two inputs, returning a Truthy value if the second input is greater (in month order) than the first. Equal values result in a Falsey value

or sorts an arbitrary sequence (list, delimited string, etc.) of them in chronological order

(The crux of the challenge is defining a method/expression that gives the correct lexicographical sort. Some languages might have a shorter answer with one or the other)

You cannot use any internal time parsing methods (e.g. strptime) to translate the month name into a number or a pre-canned mapping of month names. Use properties of the strings themselves, a parsimonious look-up table you define, or something clever.

Example

Functioning examples, though the first is prohibited by the rules...

```<code>import datetime
def is_later_month(a, b):
    '''
    Example of prohibited code because it relies on language
    features about how to parse month names
    '''
    return datetime.strptime(a, '%B') < datetime.strptime(b, '%B')
</code>```

The below versions are OK though, because we code that info

```<code>months = {
    'January':  1, 'February':  2, 'March':      3,
    'April':    4, 'May':       5, 'June':       6,
    'July':     7, 'August':    8, 'September':  9,
    'October': 10, 'November': 11, 'December':  12,
}
def is_later_month(a, b):
    """
    Returns True/False when comparing two months.
    """
    return months[a] < months[b]
</code>```

Or you could do a sorting function

```<code>months = {'as above...'}
def sort_months(l):
    """
    Sorts list and returns it. Different input and output than the above,
    but equally valid. Sorting versus comparing might be shorter in your
    favorite language.
    """
    return sorted(l, key=lambda x: months[x])
</code>```

Example tests

```<code>assert is_later_month('January', 'February')
assert is_later_month('January', 'December')
assert is_later_month('November', 'December')
assert not is_later_month('July', 'July')
assert not is_later_month('October', 'September')
</code>```

Body:
ARM machine language on Linux <s>44</s> 40 bytes

e28fc001     add ip, pc, #1
e12fff1c     bx ip
6803         ldr r3, [r0, #0]
6808         ldr r0, [r1, #0]
4a05         ldr r2, [pc, #20]
f08303dd     eor.w r3, r3, #221
f08000dd     eor.w r0, r0, #221
4353         muls r3, r2
4350         muls r0, r2
4283         cmp r3, r0
bfac         ite ge
2000         movge r0, #0
2001         movlt r0, #1
4770         bx lr
2f68f24c

I used a different hash function than anatolyg's solution and tried to use thumb instructions to save a few bytes (though I blew 8 bytes entering thumb mode).

You can try this out on a Raspberry Pi or Android device with GNURoot.

int main(int argc,char**argv){
return ((int(*)(char*,char*))"\
\1\xc0\x8f\xe2\
\x1c\xff\x2f\xe1\
\3\x68\x8\x68\
\5\x4a\x83\xf0\
\xdd\3\x80\xf0\
\xdd\x43\x53\x43\
\x50\x4a\x83\x42\
\xac\bf\0\x20\
\1\x20\x70\x47\
\x4c\xf2\x68\x2f\
")(argv[1],argv[2]);}

To run enter something like

$ ./foo January February; echo $?

The current version now handles the equality case (and others) correctly.


问:
Fix my IPv4 address's missing periods
Sometimes when I'm typing out an IPv4 address, I get all the numbers right, but I forget to type one or more periods. I'd like to have a program (or function) that takes my broken IPv4 address and outputs all possible valid placements of the missing periods.

Input

The input will always be a string that is a transformation of a valid IPv4 address (see particulars below). It will always have been transformed solely by the elimination of one or more period characters.

You submission does not need to handle inputs outside of this format.

Output

A collection or list, in no particular order or format, of strings representing all valid IPv4 addresses that can be created from the input by the insertion of period characters into the input.

The output may be a language-native list or other ordered or unordered collection type.

Alternatively, it may be a string sequence of IPv4 address delimited in some clear way.

If you use a single-character delimiter to delimit your string, periods and digits are not allowed as that single-character delimiter. I realize that, unlike numbers, periods as delimiters are not ambiguous (since every fourth period would necessarily be a delimiter) but for the sake of readability, I am disallowing it.

IPv4 address format

While IPv4 addresses are really just a sequence of four binary octets, this challenge uses a restricted dotted decimal format.

An IPv4 address is a four decimal values separated by three periods.

Each of the four values are in the range 0 to 255, inclusive.

Leading zeros are not allowed in any number value. (Standalone one-character 0 is allowed; any other number beginning with a zero is not: 052, 00, etc.)

Test Cases

Input is on the first line, output on second line (here, structured as a comma-separated list of quoted strings, separated by commas, surrounded by [ ], but you may use any reasonable format or structure, as specified above). Some examples have notes on a third line to highlight the application of a particular rule.

```<code>192.168.1234
["192.168.1.234", "192.168.12.34", "192.168.123.4"]

192.1681234
["192.16.81.234", "192.168.1.234", "192.168.12.34", "192.168.123.4"]
(Note: 192.1681.2.34 (etc.) is illegal because 1681 is greater than 255)

1921681.234
["19.216.81.234", "192.16.81.234", "192.168.1.234"]

1921681234
["19.216.81.234", "192.16.81.234", "192.168.1.234", "192.168.12.34", "192.168.123.4"]

192.168.1204
["192.168.1.204", "192.168.120.4"]
(Note: 192.168.12.04 is illegal because of leading zero)

192.168.123
["1.92.168.123", "19.2.168.123", "192.1.68.123", "192.16.8.123", "192.168.1.23", "192.168.12.3"]

192.168.256
["192.168.2.56", "192.168.25.6"]
(Note: Any combination that would leave 256 intact is illegal)

120345
["1.20.3.45", "1.20.34.5", "1.203.4.5", "12.0.3.45", "12.0.34.5", "120.3.4.5"]
(Note: 12.03.4.5 (etc.) is illegal due to leading zero.)

012345
["0.1.23.45", "0.1.234.5", "0.12.3.45", "0.12.34.5", "0.123.4.5"]
(Note: the first segment must be 0, because `01` or `012` would be illegal.)

000123
["0.0.0.123"]
</code>```

(I made these examples by hand, so please alert me to any mistakes you may find.)

答:
Perl 5, 91 bytes

```<code><>=~/^(([1-9]?|1\d|2[0-4])\d|25[0-5])\.?((?1))\.?((?1))\.?((?1))$(?{print"$1.$3.$4.$5 "})^/
</code>```

The program expects a single line of a single input and outputs space-delimited list of candidates.

Explanation

The program exploits the backtracking feature of regex to loop over all possibilities of forming a valid IPv4 address from the input string.

```<code>^(([1-9]?|1\d|2[0-4])\d|25[0-5])\.?((?1))\.?((?1))\.?((?1))$
</code>```

The IPv4 regex with optional ., nothing of note here.

```<code>(?{print"$1.$3.$4.$5 "})
</code>```

A code evaluation expression which prints out the content of the capturing groups.

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

Make the match fails and force backtracking.

Example run

```<code>$ echo "012345" | perl G89503.pl
0.12.34.5 0.12.3.45 0.1.23.45 0.1.234.5 0.123.4.5
</code>```

Title: Fix my IPv4 address's missing periods

Body:
Perl 5, 91 bytes

<>=~/^(([1-9]?|1\d|2[0-4])\d|25[0-5])\.?((?1))\.?((?1))\.?((?1))$(?{print"$1.$3.$4.$5 "})^/

The program expects a single line of a single input and outputs space-delimited list of candidates.

Explanation

The program exploits the backtracking feature of regex to loop over all possibilities of forming a valid IPv4 address from the input string.

^(([1-9]?|1\d|2[0-4])\d|25[0-5])\.?((?1))\.?((?1))\.?((?1))$

The IPv4 regex with optional ., nothing of note here.

(?{print"$1.$3.$4.$5 "})

A code evaluation expression which prints out the content of the capturing groups.

^

Make the match fails and force backtracking.

Example run

$ echo "012345" | perl G89503.pl
0.12.34.5 0.12.3.45 0.1.23.45 0.1.234.5 0.123.4.5


答:
SQF, <s>71</s> <s>69</s> 64 bytes

Using the file-as-a-function format:

```<code>i="-_h ;""=()sSplitrng"splitString"";i-(i-(_this splitString""))
</code>```

Call as "STRING" call NAME_OF_COMPILED_FUNCTION

Title: Input ∩ Source Code

Body:
Intro

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

Let I be the input set

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

Let S be the source code set

{"b","f"}

Then the intersection is what they share

I ∩ S = {"b"}

Input

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

Output

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

Output is flexible:

Could be any data structure (string or otherwise)

Could unordered

Could have a trailing \n

Should be distinct

Restriction

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

Examples

#1

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

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

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

#2

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

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

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

#3

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

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

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

Test Cases

```<code>Albert Einstein

\__( O__O)_/

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

1234567890-=[]\;',./

(ノಠ益ಠ)ノ彡┻━┻

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

┬──┬ ノ( ゜-゜ノ)

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

Update

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

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

Body:
SQF, <s>71</s> <s>69</s> 64 bytes

Using the file-as-a-function format:

i="-_h ;""=()sSplitrng"splitString"";i-(i-(_this splitString""))

Call as "STRING" call NAME_OF_COMPILED_FUNCTION


答:
zsh, 28 bytes

```<code>printf %0$#1d {$#1..$1..$#1}
</code>```

zsh + seq, <s>21</s>20 bytes

This is pretty much the same answer as Dennis but in 20 bytes because zsh

```<code>seq -ws '' $#1{,} $1
</code>```

Body:
zsh, 28 bytes

printf %0$#1d {$#1..$1..$#1}

zsh + seq, <s>21</s>20 bytes

This is pretty much the same answer as Dennis but in 20 bytes because zsh

seq -ws '' $#1{,} $1


答:
Fortran, <s>68</s> <s>51</s> 49 bytes

Skimmed off 17 bytes, because who needs indents and spaces?

-2 bytes thanks to @Joffan

As a tribute to senior and the fact there was no Fortran answer yet. Well, now I know why: this is a pretty hard language to golf! <s>Just one or two indents already take up more bytes than the shortest answer here :))</s>.

```<code>program T
do i=0,9
print*,('*',j=0,9)
end do
end
</code>```

Try it! (ideone)

I tried golfing it down by introducing a nested 'implied' do loop, but the newline character wasn't available until Fortran 2003. Also, it's insanely verbose...

Title: Print a 10 by 10 grid of asterisks

Body:
Background

This is a standard textbook example to demonstrate for loops.

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

Task

You are to print this exact text:

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

Specs

You may have extra trailing newlines.

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

Scoring

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

Body:
Fortran, <s>68</s> <s>51</s> 49 bytes

Skimmed off 17 bytes, because who needs indents and spaces?

-2 bytes thanks to @Joffan

As a tribute to senior and the fact there was no Fortran answer yet. Well, now I know why: this is a pretty hard language to golf! <s>Just one or two indents already take up more bytes than the shortest answer here :))</s>.

program T
do i=0,9
print*,('*',j=0,9)
end do
end

Try it! (ideone)

I tried golfing it down by introducing a nested 'implied' do loop, but the newline character wasn't available until Fortran 2003. Also, it's insanely verbose...


答:
SQF - 164

Using the function-as-a-file format:

```<code>#define Q String""
l=(ceil log _this)+1;s='';for[{a=l},{a<=_this},{a=a+l}]do{c=([a]joinQ)splitQ;reverse c;c=(c+['0'])select[0,l];reverse c;s=format[s+'%1',c joinQ]}
</code>```

Call as INTEGER call NAME_OF_COMPILED_FUNCTION

Body:
SQF - 164

Using the function-as-a-file format:

#define Q String""
l=(ceil log _this)+1;s='';for[{a=l},{a<=_this},{a=a+l}]do{c=([a]joinQ)splitQ;reverse c;c=(c+['0'])select[0,l];reverse c;s=format[s+'%1',c joinQ]}

Call as INTEGER call NAME_OF_COMPILED_FUNCTION


答:
Haskell 125 bytes

The imports take up a large part of the byte count

```<code>import Data.Time.Clock
import Data.Time.Calendar
main=fmap((\(x,_,_)->[x-120..x]).toGregorian.utctDay)getCurrentTime>>=print
</code>```

Body:
The Challenge

Output a list of years that starts with the current year and ends 120 years ago. The birth year of every living human would be included in this list.

Details

The list should be in descending order.

Every built-in function to manipulate arrays and/or lists is allowed.

Shortest code in bytes wins.

When run this year 2016, the output would be

2016, 2015, ..., 1897, 1896

When run next year 2017, the output would be

2017, 2016, ..., 1898, 1897

Etc.

Update

Some have asked about the format of the list. As most have guessed, it doesn't matter. Insert any separator between the numbers. Intuitively most inserted a comma or space or both, newline or output an array.

Quasi superhumans like Jeanne Calment are an exception to the rule stated in my question.

Body:
Haskell 125 bytes

The imports take up a large part of the byte count

import Data.Time.Clock
import Data.Time.Calendar
main=fmap((\(x,_,_)->[x-120..x]).toGregorian.utctDay)getCurrentTime>>=print


问:
Implement glob Matcher
Implement a function of pattern and string to be matched, return true if the pattern matches the WHOLE string, otherwise false.

Our glob pattern syntax is:

? matches any one character

+ matches one or more characters

* matches zero or more characters

\ escapes

Rules:

No eval, no converting into regular expression, no calling a system glob function.

I/O are not required: you can just write a function

Shortest wins

Examples:

```<code>glob('abc', 'abc') => true
glob('abc', 'abcdef') => false IMPORTANT!
glob('a??', 'aww') => true
glob('a*b', 'ab') => true
glob('a*b', 'agwijgwbgioeb') => true
glob('a*?', 'a') => false
glob('?*', 'def') => true
glob('5+', '5ggggg') => true
glob('+', '') => false
glob('a\*b', 'a*b') => true
</code>```

Here is a tip to get started: http://en.wikipedia.org/wiki/Backtracking

ContentLicense: CC BY-SA 2.5

Title: Implement glob Matcher

Body:
Ruby - <s>199</s> 171

g=->p,s{x=(b=->a{a[1..-1]})[p];y=s[0];w=b[s];v=p[0];_=->p,s{p[0]==y&&g[x,w]}
v==??? g[x,y&&w||s]:v==?+? y&&g[?*+x,w]:v==?*?
y&&g[p,w]||g[x,s]:v==?\\? _[x,s]:v ? _[p,s]:!y}

Ungolfed:

def glob(pattern, subject)
        b=->a{a[1..-1]}
        _=->p,s{ p[0]==s[0] && glob(b[p],b[s]) }
        ({
                ??=>->p,s { glob(b[p], s[0] ? b[s] : s) },
                ?+=>->p,s { s[0] && glob(?*+b[p], b[s]) },
                ?*=>->p,s { s[0] && glob(p,b[s]) || glob(b[p],s) },
                ?\\=>->p,s{ _[b[p],s] },
                nil=>->p,s{ !subject[0] }
        }[pattern[0]] || _)[pattern, subject]
end

Tests:

p glob('abc', 'abc')
p glob('abc', 'abcdef')
p glob('a??', 'aww')
p glob('a*b', 'ab')
p glob('a*b', 'agwijgwbgioeb')
p glob('a*?', 'a')
p glob('?*', 'def')
p glob('5+', '5ggggg')
p glob('+', '')

Inspired by roobs' answer


答:
If you have access to the memory address of these objects, you can swap them by xor-ing their addresses.

```<code>// return 0 for success, 1 for error
int swap(void *object1, void *object2, int size)
{
    for (int i = 0; i < size; i++)
    {
        char *x = (char *)(object1 + i);
        char *y = (char *)(object2 + i);
        if (x == y)
            return 1;
        *x ^= *y;
        *y ^= *x;
        *x ^= *y;
    }
    return 0;
}
</code>```

per dmckee suggestion for clarity

Title: Swap 2 objects, without using a temporary variable

Body:
There are two objects:

```<code>Object1, Object2
</code>```

You can easily swap them by:

```<code>Object3 = Object1
Object1 = Object2
Object2 = Object3
</code>```

However, you must solve this problem by using no temporary object and Object1 should be changed to Object 2. (and vice versa)

Body:
If you have access to the memory address of these objects, you can swap them by xor-ing their addresses.

// return 0 for success, 1 for error
int swap(void *object1, void *object2, int size)
{
    for (int i = 0; i < size; i++)
    {
        char *x = (char *)(object1 + i);
        char *y = (char *)(object2 + i);
        if (x == y)
            return 1;
        *x ^= *y;
        *y ^= *x;
        *x ^= *y;
    }
    return 0;
}

per dmckee suggestion for clarity


答:
SQLite, 82 80 bytes

```<code>with b(y)as(select strftime('%Y')union select y-1 from b limit 121)select*from b
</code>```

SQLFiddle

(For ANSI SQL, replace the strftime() with extract(year from current_date).)

(2 bytes saved thanks to @MickyT)

Body:
SQLite, 82 80 bytes

with b(y)as(select strftime('%Y')union select y-1 from b limit 121)select*from b

SQLFiddle

(For ANSI SQL, replace the strftime() with extract(year from current_date).)

(2 bytes saved thanks to @MickyT)


答:
Python 2, 113 bytes

```<code>import datetime
theYear = datetime.datetime.now()
for i in range(theYear.year, theYear.year-121, -1):
   print i,','
</code>```

Body:
Python 2, 113 bytes

import datetime
theYear = datetime.datetime.now()
for i in range(theYear.year, theYear.year-121, -1):
   print i,','


答:
C# - DotNet core - 133 bytes

Golfed

```<code>class Program{static void Main(){int x=0,y=System.DateTime.Now.Year;while(x<121){System.Console.Write($"{y-x++}"+(x<121?", ":""));}}}
</code>```

Ungolfed

```<code>class Program
{
    static void Main()
    {
        int x=0, y=System.DateTime.Now.Year;

        while(x<121)
        {
            System.Console.Write($"{y-x++}" + (x < 121 ? ", " : ""));
        }
    }
}
</code>```

Output:

I'm sure this can be improved. I don't particularly like the if statement to display or hide the trailing comma.

Body:
C# - DotNet core - 133 bytes

Golfed

class Program{static void Main(){int x=0,y=System.DateTime.Now.Year;while(x<121){System.Console.Write($"{y-x++}"+(x<121?", ":""));}}}

Ungolfed

class Program
{
    static void Main()
    {
        int x=0, y=System.DateTime.Now.Year;

        while(x<121)
        {
            System.Console.Write($"{y-x++}" + (x < 121 ? ", " : ""));
        }
    }
}

Output:

I'm sure this can be improved. I don't particularly like the if statement to display or hide the trailing comma.


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

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

Specs

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

You may print one extra trailing linefeed.

Scoring

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

答:
Vitsy, 29 bytes

So, instead of doing the typical thing, I used my two-dimensional stacking to generate the alphabets and then offset them by one from each other, alternating back and forth between them.

```<code>9a*d5*Hd\[:{:}]Y?y\[y\[O?]aO]

9a*d5*H                        Push an alphabet to the stack.
9a*                                 Push 90 to the stack (character code 'Z')
   d5*                              Push 65 to the stack (character code 'A')
      H                             Pop a, b, push range (a, b)

       d\[:{:}]                Establish the other stacks, while alternating.
       d\[    ]                     Do the bracketed code 13 times.
          : :                       Clone the stack.
           {                        Put the top item of the stack on the bottom.
             }                      Put the bottom item of the stack on the top.
               Y                    Discard a stack. (13*2+1-1 = 26)
                ?                   Rotate right a stack (we start on 'A' now)
                 y\[y\[O?]aO]  Output.
                 y\[        ]       Repeat the code in brackets number of stacks times (26).
                    y\[  ]          Repeat the code in brackets number of stack times (26).
                       O            Pop a, print a as a character.
                        ?           Go right a stack.
                          aO        Output a newline.
</code>```

Try it online!

Title: Print an alphabet wave

Body:
Vitsy, 29 bytes

So, instead of doing the typical thing, I used my two-dimensional stacking to generate the alphabets and then offset them by one from each other, alternating back and forth between them.

9a*d5*Hd\[:{:}]Y?y\[y\[O?]aO]

9a*d5*H                        Push an alphabet to the stack.
9a*                                 Push 90 to the stack (character code 'Z')
   d5*                              Push 65 to the stack (character code 'A')
      H                             Pop a, b, push range (a, b)

       d\[:{:}]                Establish the other stacks, while alternating.
       d\[    ]                     Do the bracketed code 13 times.
          : :                       Clone the stack.
           {                        Put the top item of the stack on the bottom.
             }                      Put the bottom item of the stack on the top.
               Y                    Discard a stack. (13*2+1-1 = 26)
                ?                   Rotate right a stack (we start on 'A' now)
                 y\[y\[O?]aO]  Output.
                 y\[        ]       Repeat the code in brackets number of stacks times (26).
                    y\[  ]          Repeat the code in brackets number of stack times (26).
                       O            Pop a, print a as a character.
                        ?           Go right a stack.
                          aO        Output a newline.

Try it online!


Body:
You want to make a string where the (1-indexed) character at index n is n. When n is less than 10, this is easy: "123456789". When n is 12, for example, it becomes impossible, since numbers greater than 9 (in base 10) take up more than one character. We can compromise by dividing the string into two-character substrings: "020406081012". Now the index of the end of each substring n is n.

This can be generalized for any d-digit number. Here's an explanation for the "0991021" part of the string for a three-digit number:

```<code>Index:     ... * 97  98  99*100 101 102*103 ...
               *           *           *
               *---+---+---*---+---+---*---+
Character: ... * 0 | 9 | 9 * 1 | 0 | 2 * 1 | ...
               *---+---+---*---+---+---*---+
</code>```

If you haven't figured it out yet, you are to write a program/function that takes a string or integer and output its self-referential string as specified above. You can also output an array of single-digit numbers, chars, or single-character strings.

The given integer will always be positive and divisible by its length (e.g. 126 is divisible by 3; 4928 is divisible by 4). Your program should theoretically work for an arbitrarily large input, but you can assume it is smaller than your language's maximum integer and/or string length.

Some observations if you still don't get it: The length of the output will always be the input itself, and the numbers that appear in the output will be divisible by the number of digits in the input.

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

Test cases

```<code>1    => 1
9    => 123456789
10   => 0204060810
105  => 003006009012015018021024027030033036039042045048051054057060063066069072075078081084087090093096099102105
1004 => 00040008001200160020002400280032003600400044004800520056006000640068007200760080008400880092009601000104010801120116012001240128013201360140014401480152015601600164016801720176018001840188019201960200020402080212021602200224022802320236024002440248025202560260026402680272027602800284028802920296030003040308031203160320032403280332033603400344034803520356036003640368037203760380038403880392039604000404040804120416042004240428043204360440044404480452045604600464046804720476048004840488049204960500050405080512051605200524052805320536054005440548055205560560056405680572057605800584058805920596060006040608061206160620062406280632063606400644064806520656066006640668067206760680068406880692069607000704070807120716072007240728073207360740074407480752075607600764076807720776078007840788079207960800080408080812081608200824082808320836084008440848085208560860086408680872087608800884088808920896090009040908091209160920092409280932093609400944094809520956096009640968097209760980098409880992099610001004
</code>```

Body:
Ruby, <s>52</s> 48 + n flag = 49 bytes

((l= ~/$/)..$_.to_i).step(l){|j|$><<"%0#{l}d"%j}


答:
Javascript: <s>68</s> <s>82</s> 59 bytes

i=121;while(i--){x[i]=Date().substr(11,4)-i;}console.log(x)


答:
Oracle SQL 11.2, 44 bytes

SELECT'**********'FROM v$bh WHERE rownum<11;
```

Title: Print a 10 by 10 grid of asterisks