问:
Drilling For Oil

Congratulations!

You have just been hired by a Fortune 499 company specializing in oil drilling.
Your job is to write a program to determine the optimum placement of OilRUs' drill (represented by a single alphabetical character of your choice, I use a capital "O" in the examples), given a length of piping, and a two-dimensional Ground Composition Analysis(Henceforth, "GCA") of the area.

However, due to the limited amounts of fossil fuels in the region, copious amounts of bureaucracy, and a recent influx of environmentalists, you must write your program in the fewest bytes possible.

Your program is expected to return the GCA with an Oil drill and piping in the optimal position, as defined below.

Rules:

Input will be composed of an integer, followed by a new-line-separated GCA.

The GCA will be composed exclusively of the following characters, representing the surface, dirt, and oil respectively:

=

.

~

The first line of the GCA will always contain exclusively surface tiles, and all layers below that will contain a mixture exclusively of dirt and oil.

The GCA will be at least 4 lines of 3 characters, but will not exceed 64 lines of 256 characters each. Every input will contain at least one oil tile.

Multiple, adjacent oil tiles on the same row create a 'pool', where all tiles are collected if a pipe tile replaces any of them.

Every GCA will have at least one valid solution. See Clarification section for examples.

For GCAs with multiple equivalent solutions, the solution closest to the surface wins.

For GCAs with multiple equivalent solutions at the same depth, the one closest to the left-hand side wins.

A single, larger pool with the same volume as multiple smaller ones are viewed as equivalent. For example, two pools of four tiles are equivalent to a single pool of eight tiles.

Volume of oil retrieved outweighs the above three points. If a superior solution exists at a deeper level, or further rightward, that solution is to be the one returned by the program.

You may not use any purpose-created built-ins for finding oil reserves, whether they're supplied by OilRUs, WeDrill4U, or any third parties.

Your program must complete its execution within a reasonable time frame (~30 minutes or less).

Standard Loopholes apply.

Clarification:

The integer portion of the input represents the maximum number of pipes available. They do not all need to be used.

Optimum position is defined in this challenge as the first valid place the drill can be set that intersects the largest amount of oil tiles/pools.

Oil tiles replaced by pipe tiles are still collected, even though they don't show up in the output.

Rule 6 Examples:

```<code>   Equal (assuming you were given 3+ pipes)
=====  =====
..~..  .....
..~..  .....
..~..  ..~~~
</code>```

But:

```<code>Loses  Wins
=====  =====
.....  .....
.....  .~~~. ** Solution closer to the surface. (Rule 6.1)
.~...  .....
.~...  .....
.~...  .....
</code>```

Also:

```<code> Wins     Loses
=====     =====
.....     .....
..~~.     ...~~ ** Solutions are at the same depth,
..~~.     ...~~ ** but one is further left. (Rule 6.2)
.....     .....
</code>```

Test Cases

Note: The text shown (denoted by the preceding two asterisks and continuing to the end of that line) in some of the test case outputs below is there for illustrative purposes only. Your program is not expected to print anything apart from OilRUs' drill, pipe, and the GCA.

Input:

```<code>4
===============================
..~~....~~.....................
~~........~~~...~~~~~~.........
.....~~~~.....~~~..~~..........
..............~~~...~...~~~..~.
..~~~..~~...~~.....~~....~~~...
.........~~..~...~~..........~.
.......~~...~......~~~.........
..~..........~...........~.....
.........~~.............~......
...~.........~~~~.........~....
...........~..........~........
</code>```

Output:

```<code>================O==============
..~~....~~......|..............
~~........~~~...|~~~~~.........
.....~~~~.....~~|..~~..........
..............~~|...~...~~~..~.
..~~~..~~...~~.....~~....~~~...
.........~~..~...~~..........~.
.......~~...~......~~~.........
..~..........~...........~.....
.........~~.............~......
...~.........~~~~.........~....
...........~..........~........
</code>```

Input:

```<code>2
===============
..~~~.~~.......
..~.....~~~~~~.
.~~~.....~~~...
..~~~..~~..~~~.
.~~...~~~....~.
</code>```

Output:

```<code>========O======
..~~~.~~|......
..~.....|~~~~~.
.~~~.....~~~... ** Leftmost tile in pool (Rule 6.2)
..~~~..~~..~~~.
.~~...~~~....~.
</code>```

Input:

```<code>5
===
~.~
...
~.~
</code>```

Output:

```<code>O==
|.~
|.. ** Leftmost solution wins (Rule 6.2)
|.~
</code>```

Input:

```<code>55
============
............
............
...~.~~..~..
..~~......~.
.....~~~....
..~~~...~~..
...~~~~~~~..
</code>```

Output:

```<code>===O========
...|........
...|........
...|.~~..~..
..~|......~.
...|.~~~....
..~|~...~~..
...|~~~~~~..
</code>```

Input:

```<code>6
============
............
............
..~~........
...~..~~~~..
............
...~........
</code>```

Output:

```<code>======O=====
......|.....
......|.....
..~~..|.....
...~..|~~~.. ** Even though there is a solution closer to the left,
............ ** the solution highlighted here takes priority because it is
...~........ ** closer to the surface. (Rule 6.1)
</code>```

Title: Drilling For Oil

Body:
Java, 287 bytes

void a(int d,char[][]a){int b=a.length-1,c=0,e=d=b>d?d:b,f=0,i=0,j,k,g,h,l,m=a[0].length;for(;i<m;i++){g=0;h=0;for(j=1;j<=d;j++){l=0;for(k=0;k<m;k++)if(a[j][k]!=46)l++;else if(k<i)l=0;else break;g+=k==i?0:l;h=l>0?j:h;}if(g>c||g==c&&h<e){c=g;e=h;f=i;}}for(j=0;j<=e;a[j][f]=j++>0?'|':79);}

Ungolfed

void gcaAnalysis(int pipes, char[][] soil) {
    int soilDepth = soil.length - 1, bestCount = 0, bestDepth = pipes = soilDepth > pipes ? pipes : soilDepth, bestX = 0, x = 0, y, k, curCount, curDepth, curLayerCount, width = soil[0].length;
    for (; x < width; x++) {
        curCount = 0;
        curDepth = 0;
        for (y = 1; y <= pipes; y++) {
            curLayerCount = 0;
            for (k = 0; k < width; k++)
                if (soil[y][k] != 46) curLayerCount++;
                else if (k < x) curLayerCount = 0;
                else break;
            curCount += k == x ? 0 : curLayerCount;
            curDepth = curLayerCount > 0 ? y : curDepth;
        }
        if (curCount > bestCount || curCount == bestCount && curDepth < bestDepth) {
            bestCount = curCount;
            bestDepth = curDepth;
            bestX = x;
        }
    }
    for (y = 0; y <= bestDepth; soil[y][bestX] = y++ > 0 ? '|' : 79);
}

Note

Well... this took half an alphabet of variable names, but it works i guess...

Results are written back into a (aka soil in the ungolfed code).

Output

================O==============
..~~....~~......|..............
~~........~~~...|~~~~~.........
.....~~~~.....~~|..~~..........
..............~~|...~...~~~..~.
..~~~..~~...~~.....~~....~~~...
.........~~..~...~~..........~.
.......~~...~......~~~.........
..~..........~...........~.....
.........~~.............~......
...~.........~~~~.........~....
...........~..........~........

========O======
..~~~.~~|......
..~.....|~~~~~.
.~~~.....~~~...
..~~~..~~..~~~.
.~~...~~~....~.

O==
|.~
|..
|.~

===O========
...|........
...|........
...|.~~..~..
..~|......~.
...|.~~~....
..~|~...~~..
...|~~~~~~..

======O=====
......|.....
......|.....
..~~..|.....
...~..|~~~..
............
...~........


问:
Draw a phi triangle
Clarification: Basically, you need to make this

Euler's totient function has the name phi.

Let's try to calculate phi(8)

First, list all numbers 8 and under backwards, not including 0 or under

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

Now find which numbers don't share a factor with 8 (1 doesn't count), and place a # in their place.

```<code>8
#
6
#
4
#
2
#
</code>```

Remove the numbers.

```<code>#

#

#

#
                                                 -
</code>```

Now do this, but string the outputs together in a triangle

```<code>        9
       88
      777
     6666
    55555
   444444
  3333333
 22222222
111111111
---------
123456789
</code>```

# out non-factor sharing numbers

```<code>        9
       8#
      7##
     6#66
    5####
   4#4#4#
  3##3##3
 2#2#2#2#
#########
</code>```

Remove numbers:

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

This would be the output for input 9 (since 9 columns.)

Leading + trailing newlines allowed.

答:
Java, <s>162</s> 158 bytes

int g(int a,int b){return a<1?b:g(b%a,a);}
String d(int n){String r="";for(int i=0;i<n;i++){for(int j=1;j<=n;)r+=i+j<n|g(n-i,j++)>1?" ":"#";r+="\n";}return r;}
```
<p>Full program (not updated)</p>
<pre class="lang-java prettyprint-override"><code>import java.util.Scanner;

public class Q79082 {
    int gcd_ungolfed(int a,int b){
        if(a==0) return b;
        return gcd_ungolfed(b%a,a);
    }
    void draw_ungolfed(int n){
        for(int i=1;i<=n;i++){
            for(int j=1;j<=n;j++){
                if(i+j<=n || gcd_ungolfed(n+1-i,j)!=1){
                    System.out.print(" ");
                }else{
                    System.out.print("#");
                }
            }
            System.out.println();
        }
    }
    int g(int a,int b){return a<1?b:g(b%a,a);}
    String d(int n){String r="";for(int i=0;i<n;i++){for(int j=1;j<=n;j++)r+=(i+j<n||g(n-i,j)>1)?" ":"#";r+="\n";}return r;}
    public static void main(String args[]){
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        sc.close();
        new Q79082().draw_ungolfed(n);
        System.out.println(new Q79082().d(n));
    }
}
</code>```

Input/output:

9

        #
       ##
      #
     ####
    # # #
   ## ##
  # # # #
#########

        #
       ##
      #
     ####
    # # #
   ## ##
  # # # #
#########
```

ContentLicense: CC BY-SA 3.0

Title: Draw a phi triangle

Body:
Java, <s>162</s> 158 bytes

int g(int a,int b){return a<1?b:g(b%a,a);}
String d(int n){String r="";for(int i=0;i<n;i++){for(int j=1;j<=n;)r+=i+j<n|g(n-i,j++)>1?" ":"#";r+="\n";}return r;}

Full program (not updated)

import java.util.Scanner;

public class Q79082 {
    int gcd_ungolfed(int a,int b){
        if(a==0) return b;
        return gcd_ungolfed(b%a,a);
    }
    void draw_ungolfed(int n){
        for(int i=1;i<=n;i++){
            for(int j=1;j<=n;j++){
                if(i+j<=n || gcd_ungolfed(n+1-i,j)!=1){
                    System.out.print(" ");
                }else{
                    System.out.print("#");
                }
            }
            System.out.println();
        }
    }
    int g(int a,int b){return a<1?b:g(b%a,a);}
    String d(int n){String r="";for(int i=0;i<n;i++){for(int j=1;j<=n;j++)r+=(i+j<n||g(n-i,j)>1)?" ":"#";r+="\n";}return r;}
    public static void main(String args[]){
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        sc.close();
        new Q79082().draw_ungolfed(n);
        System.out.println(new Q79082().d(n));
    }
}

Input/output:

9

        #
       ##
      #
     ####
    # # #
   ## ##
  # # # #
#########

        #
       ##
      #
     ####
    # # #
   ## ##
  # # # #
#########


问:
Are my eyes open or closed?
You are trying to guess my emotion.

I will give you an adjective, as the input to the function/program.

Your task is to output the state of my eyes, either O_O for open, or ._. for closed.

Details

For these adjectives, you must output open eyes O_O

```<code>animated
breezy
brisk
driving
enterprising
fresh
indefatigable
industrious
snappy
spirited
sprightly
spry
stalwart
strenuous
strong
sturdy
unflagging
untiring
</code>```

For these adjectives, you must output closed eyes ._.

```<code>beat
bored
collapsing
consumed
distressed
empty
fagged
faint
fatigued
finished
jaded
wasted
worn
</code>```

Other adjectives are undefined. You may output whatever you want for other adjectives.

Specs

All in lowercase. All matches regex ^[a-z]+$.

Scoring

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

Tips

There is a trick. The adjectives that correspond to closed eyes are all related to "tired". The adjectives that correspond to open eyes are all related to "active".

Title: Are my eyes open or closed?

Body:
MATL, <s>22</s> 16 bytes

2)2\?'._.'}'O_O'

Try it online

22 byte version, 2)'ntpr'=a?'O_O'}'._.'.


问:
Is it a prefix code?
In information theory, a "prefix code" is a dictionary where none of the keys are a prefix of another. In other words, this means that none of the strings starts with any of the other.

For example, {"9", "55"} is a prefix code, but {"5", "9", "55"} is not.

The biggest advantage of this, is that the encoded text can be written down with no separator between them, and it will still be uniquely decipherable. This shows up in compression algorithms such as Huffman coding, which always generates the optimal prefix code.

Your task is simple: Given a list of strings, determine whether or not it is a valid prefix code.

Your input:

Will be a list of strings in any reasonable format.

Will only contain printable ASCII strings.

Will not contain any empty strings.

Your output will be a truthy/falsey value: Truthy if it's a valid prefix code, and falsey if it isn't.

Here are some true test cases:

```<code>["Hello", "World"]
["Code", "Golf", "Is", "Cool"]
["1", "2", "3", "4", "5"]
["This", "test", "case", "is", "true"]

["111", "010", "000", "1101", "1010", "1000", "0111", "0010", "1011",
 "0110", "11001", "00110", "10011", "11000", "00111", "10010"]
</code>```

Here are some false test cases:

```<code>["4", "42"]
["1", "2", "3", "34"]
["This", "test", "case", "is", "false", "t"]
["He", "said", "Hello"]
["0", "00", "00001"]
["Duplicate", "Duplicate", "Keys", "Keys"]
</code>```

This is code-golf, so standard loopholes apply, and shortest answer in bytes wins.

答:
Pyth - <s>13</s> 12 bytes

```<code>!ssmm}d._k-Q
</code>```

Try it online here.

Title: Is it a prefix code?


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

```<code>:Gq:!Zd1=RP35*c
</code>```

Try it online!

If a leading newline is acceptable: 13 bytes:

```<code>:t!Zd1=RP35*c
</code>```

Explanation

```<code>:     % Take input N. Generate row vector [1 2 ... N]
Gq:   % Row vector [1 2 ... N-1].
      % (In the 13-byte version this is replaced by function `t`, which duplicates
      % the array [1 2 ... N])
!     % Transpose into column vector
Zd    % GCD, element-wise with broadcast. Gives (N-1)×N matrix
1=    % True for entries that equal 1, corresponding to relatively prime pairs.
      % The rest of entries are set to false, i.e. 0.
R     % Upper triangular part: set values below diagonal to 0
P     % Flip matrix vertically
35*   % Multiply each entry by 35 (ASCII for '#')
c     % Convert to char. 0 will be displayed as a space. Implicitly display
</code>```

Title: Draw a phi triangle

Body:
Clarification: Basically, you need to make this

Euler's totient function has the name phi.

Let's try to calculate phi(8)

First, list all numbers 8 and under backwards, not including 0 or under

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

Now find which numbers don't share a factor with 8 (1 doesn't count), and place a # in their place.

```<code>8
#
6
#
4
#
2
#
</code>```

Remove the numbers.

```<code>#

#

#

#
                                                 -
</code>```

Now do this, but string the outputs together in a triangle

```<code>        9
       88
      777
     6666
    55555
   444444
  3333333
 22222222
111111111
---------
123456789
</code>```

# out non-factor sharing numbers

```<code>        9
       8#
      7##
     6#66
    5####
   4#4#4#
  3##3##3
 2#2#2#2#
#########
</code>```

Remove numbers:

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

This would be the output for input 9 (since 9 columns.)

Leading + trailing newlines allowed.

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

:Gq:!Zd1=RP35*c

Try it online!

If a leading newline is acceptable: 13 bytes:

:t!Zd1=RP35*c

Explanation

:     % Take input N. Generate row vector [1 2 ... N]
Gq:   % Row vector [1 2 ... N-1].
      % (In the 13-byte version this is replaced by function `t`, which duplicates
      % the array [1 2 ... N])
!     % Transpose into column vector
Zd    % GCD, element-wise with broadcast. Gives (N-1)×N matrix
1=    % True for entries that equal 1, corresponding to relatively prime pairs.
      % The rest of entries are set to false, i.e. 0.
R     % Upper triangular part: set values below diagonal to 0
P     % Flip matrix vertically
35*   % Multiply each entry by 35 (ASCII for '#')
c     % Convert to char. 0 will be displayed as a space. Implicitly display


答:
Pyth, 8 bytes

```<code>.AxM.PQ2
</code>```

Test suite

Take all 2 element permutations of the input, map each to the index of one string in the other (0 for a prefix) and return whether all results are truthy (non-zero).

Title: Is it a prefix code?

Body:
In information theory, a "prefix code" is a dictionary where none of the keys are a prefix of another. In other words, this means that none of the strings starts with any of the other.

For example, {"9", "55"} is a prefix code, but {"5", "9", "55"} is not.

The biggest advantage of this, is that the encoded text can be written down with no separator between them, and it will still be uniquely decipherable. This shows up in compression algorithms such as Huffman coding, which always generates the optimal prefix code.

Your task is simple: Given a list of strings, determine whether or not it is a valid prefix code.

Your input:

Will be a list of strings in any reasonable format.

Will only contain printable ASCII strings.

Will not contain any empty strings.

Your output will be a truthy/falsey value: Truthy if it's a valid prefix code, and falsey if it isn't.

Here are some true test cases:

```<code>["Hello", "World"]
["Code", "Golf", "Is", "Cool"]
["1", "2", "3", "4", "5"]
["This", "test", "case", "is", "true"]

["111", "010", "000", "1101", "1010", "1000", "0111", "0010", "1011",
 "0110", "11001", "00110", "10011", "11000", "00111", "10010"]
</code>```

Here are some false test cases:

```<code>["4", "42"]
["1", "2", "3", "34"]
["This", "test", "case", "is", "false", "t"]
["He", "said", "Hello"]
["0", "00", "00001"]
["Duplicate", "Duplicate", "Keys", "Keys"]
</code>```

This is code-golf, so standard loopholes apply, and shortest answer in bytes wins.

Body:
Pyth, 8 bytes

.AxM.PQ2

<a href="https://pyth.herokuapp.com/?code=.AxM.PQ2&test_suite=1&test_suite_input=%5B%22Hello%22%2C+%22World%22%5D++++++++++++++++++++++%0A%5B%22Code%22%2C+%22Golf%22%2C+%22Is%22%2C+%22Cool%22%5D%0A%5B%221%22%2C+%222%22%2C+%223%22%2C+%224%22%2C+%225%22%5D%0A%5B%22This%22%2C+%22test%22%2C+%22case%22%2C+%22is%22%2C+%22true%22%5D++++++++++%0A%5B%22111%22%2C+%22010%22%2C+%22000%22%2C+%221101%22%2C+%221010%22%2C+%221000%22%2C+%220111%22%2C+%220010%22%2C+%221011%22%2C+%220110%22%2C+%2211001%22%2C+%2200110%22%2C+%2210011%22%2C+%2211000%22%2C+%2200111%22%2C+%2210010%22%5D%0A%5B%224%22%2C+%2242%22%5D+++++++++++++++++++++++++++++%0A%5B%221%22%2C+%222%22%2C+%223%22%2C+%2234%22%5D+++++++++++++++++++%0A%5B%22This%22%2C+%22test%22%2C+%22case%22%2C+%22is%22%2C+%22false%22%2C+%22t%22%5D%0A%5B%22He%22%2C+%22said%22%2C+%22Hello%22%5D%0A%5B%220%22%2C+%2200%22%2C+%2200001%22%5D%0A%5B%22Duplicate%22%2C+%22Duplicate%22%2C+%22Keys%22%2C+%22Keys%22%5D&debug=0">Test suite

Take all 2 element permutations of the input, map each to the index of one string in the other (0 for a prefix) and return whether all results are truthy (non-zero).


答:
Java, 128 127 126 125 124 121 bytes

(Thanks @Kenny Lau, @Maltysen, @Patrick Roberts, @Joba)

```<code>Object a(String[]a){for(int i=0,j,l=a.length;i<l;i++)for(j=0;j<l;)if(i!=j&a[j++].startsWith(a[i]))return 1<0;return 1>0;}
</code>```

Ungolfed

```<code>Object a(String[] a) {
    for (int i = 0, j, l = a.length; i < l; i++)
        for (j = 0; j < l;)
            if (i != j & a[j++].startsWith(a[i])) return 1<0;
    return 1>0;
}
</code>```

Output

```<code>[Hello, World]
true

[Code, Golf, Is, Cool]
true

[1, 2, 3, 4, 5]
true

[This, test, case, is, true]
true

[111, 010, 000, 1101, 1010, 1000, 0111, 0010, 1011, 0110, 11001, 00110, 10011, 11000, 00111, 10010]
true

[4, 42]
false

[1, 2, 3, 34]
false

[This, test, case, is, false, t]
false

[He, said, Hello]
false

[0, 00, 00001]
false

[Duplicate, Duplicate, Keys, Keys]
false
</code>```

Title: Is it a prefix code?

Body:
Java, 128 127 126 125 124 121 bytes

(Thanks @Kenny Lau, @Maltysen, @Patrick Roberts, @Joba)

Object a(String[]a){for(int i=0,j,l=a.length;i<l;i++)for(j=0;j<l;)if(i!=j&a[j++].startsWith(a[i]))return 1<0;return 1>0;}

Ungolfed

Object a(String[] a) {
    for (int i = 0, j, l = a.length; i < l; i++)
        for (j = 0; j < l;)
            if (i != j & a[j++].startsWith(a[i])) return 1<0;
    return 1>0;
}

Output

[Hello, World]
true

[Code, Golf, Is, Cool]
true

[1, 2, 3, 4, 5]
true

[This, test, case, is, true]
true

[111, 010, 000, 1101, 1010, 1000, 0111, 0010, 1011, 0110, 11001, 00110, 10011, 11000, 00111, 10010]
true

[4, 42]
false

[1, 2, 3, 34]
false

[This, test, case, is, false, t]
false

[He, said, Hello]
false

[0, 00, 00001]
false

[Duplicate, Duplicate, Keys, Keys]
false


答:
Racket, 70 bytes

(λ(l)(andmap(λ(e)(not(ormap(curryr string-prefix? e)(remv e l))))l))
```

Title: Is it a prefix code?


问:
Calculate ISBN-13 check digit
Write a function which, given the first 12 digits of an ISBN-13 code, will calculate the entire ISBN via calculating and appending an appropriate check digit.

Your function's input is a string containing the first 12 digits of the ISBN. Its output is a string containing all 13 digits.

Formal specification

Write a function which, when given a string s consisting entirely of exactly 12 decimal digits (and no other characters), returns a string t with the following properties:

t consists of exactly 13 decimal digits (and no other characters);

s is a prefix of t;

the sum of all digits in odd positions in t (i.e. the first, third, fifth, etc.), plus three times the sum of all digits in even positions in t (i.e. the second, fourth, sixth, etc), is a multiple of 10.

Example / test case

Input

978030640615

Output

9780306406157

Victory condition

As a code-golf challenge, the shortest answer wins.

Title: Calculate ISBN-13 check digit

Body:
Windows PowerShell, 57

filter i{$_+(990-($_-replace'(.)(.)','+$1+3*$2'|iex))%10}


问:
Compute CRC32 Hash

Credits

This challenge originated from @miles.

Create a function that computes the CRC32 hash of an input string. The input will be an ASCII string of any length. The output will be the CRC32 hash of that input string.

Explanation

The algorithm of CRC32 and other CRC are essentially the same, so only CRC3 will be demonstrated here.

Firstly, you have the generator polynomial, which is actually a 4-bit [n+1] integer (would be 33-bit in CRC32).

In this example, the generator polynomial is 1101.

Then, you will have the string to be hashed, which in this example would be 00010010111100101011001101.

```<code>00010010111100101011001101|000 (1)    append three [n] "0"s
   1101                        (2)    align with highest bit
00001000111100101011001101|000 (3)    XOR (1) and (2)
    1101                       (4)    align with highest bit
00000101111100101011001101|000 (5)    XOR (3) and (4)
     1101                      (6)    align with highest bit
00000011011100101011001101|000 (7)    XOR (5) and (6)
      1101                     (8)    align with highest bit
00000000001100101011001101|000 (9)    XOR (7) and (8)
          1101                 (10)   align with highest bit
00000000000001101011001101|000 (11)   XOR (9) and (10)
             1101              (12)   align with highest bit
00000000000000000011001101|000 (13)   XOR (11) and (12)
                  1101         (14)   align with highest bit
00000000000000000000011101|000 (15)   XOR (13) and (14)
                     1101      (16)   align with highest bit
00000000000000000000000111|000 (17)   XOR (15) and (16)
                       110 1   (18)   align with highest bit
00000000000000000000000001|100 (19)   XOR (17) and (18)
                         1 101 (20)   align with highest bit
00000000000000000000000000|001 (21)   XOR (19) and (20)
^--------REGION 1--------^ ^2^
</code>```

The remainder obtained at (21), when region 1 is zero, which is 001, would be the result of the CRC3 hash.

Specs

The generator polynomial is 0x104C11DB7, or 0b100000100110000010001110110110111, or 4374732215.

Input can be a string or a list of integers, or any other reasonable format.

Output be a hex string or just an integer, or any other reasonable format.

Built-ins that compute the CRC32 hash are not allowed.

Goal

Standard rules for code-golf apply.

The shortest code wins.

Test cases

```<code>input         output      (hex)
"code-golf"   147743960   08CE64D8
"jelly"       1699969158  65537886
""            0           00000000
</code>```

答:
Intel x86, <s>34</s> <s>30</s> <s>29</s> 27 bytes

Takes the address of the zero-terminated string in ESI, and returns the CRC in EBX:

```<code>31 db ac c1 e0 18 74 01 31 c3 6a 08 59 01 db 73
06 81 f3 b7 1d c1 04 e2 f4 eb e7
</code>```

Disassembly (AT&T syntax):

```<code>00000000    xorl    %ebx, %ebx
00000002    lodsb   (%esi), %al
00000003    shll    $24, %eax
00000006    je      0x9
00000008    xorl    %eax, %ebx
0000000a    pushl   $8
0000000c    popl    %ecx
0000000d    addl    %ebx, %ebx
0000000f    jae     0x17
00000011    xorl    $0x4c11db7, %ebx
00000017    loop    0xd
00000019    jmp     0x2
0000001b
</code>```

Incorporating suggestions from Peter Cordes to save four more bytes. This assumes a calling convention where the direction flag for string instructions is cleared on entry.

Incorporating suggestion of Peter Ferrie to use push literal and pop to load a constant, saving one byte.

Incorporating suggestion of Peter Ferrie to jump to the second byte of an xorl %eax, %ebx instruction which is a retl instruction, combined with changing the interface of the routine to take a zero-terminated string instead of length, saving two bytes in total.

Title: Compute CRC32 Hash

Body:
Intel x86, <s>34</s> <s>30</s> <s>29</s> 27 bytes

Takes the address of the zero-terminated string in ESI, and returns the CRC in EBX:

31 db ac c1 e0 18 74 01 31 c3 6a 08 59 01 db 73
06 81 f3 b7 1d c1 04 e2 f4 eb e7

Disassembly (AT&T syntax):

00000000    xorl    %ebx, %ebx
00000002    lodsb   (%esi), %al
00000003    shll    $24, %eax
00000006    je      0x9
00000008    xorl    %eax, %ebx
0000000a    pushl   $8
0000000c    popl    %ecx
0000000d    addl    %ebx, %ebx
0000000f    jae     0x17
00000011    xorl    $0x4c11db7, %ebx
00000017    loop    0xd
00000019    jmp     0x2
0000001b

Incorporating suggestions from Peter Cordes to save four more bytes. This assumes a calling convention where the direction flag for string instructions is cleared on entry.

Incorporating suggestion of Peter Ferrie to use push literal and pop to load a constant, saving one byte.

Incorporating suggestion of Peter Ferrie to jump to the second byte of an xorl %eax, %ebx instruction which is a retl instruction, combined with changing the interface of the routine to take a zero-terminated string instead of length, saving two bytes in total.


问:
Draw a simple cube
We don't have a single challenge about drawing a real 3 dimensional cube, so here it goes:

Challenge

Your task is to draw a rotated, cube with perspective. It can be in a separate window or as an image.

Input

Your input is 3 separate numbers between 0 and 359.99... These represent the rotation around the x, y and z axis in degrees.

```<code>0 0 0
30 0 40
95 320 12
</code>```

Output

You can either display it in a separate window or save an image. You can use any type of display (vector based, rasterized, etc.).

Edit: ASCII is allowed too, to allow golfing languages with only textual output.

The output for rasterized or ASCII graphics must be at least 50*50 (pixels for rasterization, characters for ASCII)

Additional information

The positive z axis points out from the window, the x axis is horizontal, and the y axis is vertical. Basically the OpenGL standard.

Rotations are counter-clockwise if you look at the cube in the negative direction of a specific axis, e.g looking down for the y axis.

The camera should be on the z axis at a reasonable distance from the cube in the negative z direction, the cube should be at (0;0;0). The. cube also needs to be fully visible, and take up at least 50% of the drawing frame. The camera should look in the positive z direction at the cube.

The rotations of the cube get applied in the x->y->z order.

The cube is rotated around it's center, it doesn't move.

To project a cube in 2d space, you need to divide the x and y coordinates of the cube with the distance parallel to the z-axis between the point and the camera.

Rules

Rendering libraries are allowed, but the vertices need to be defined in the code. No 3d cube model class.

Test cases

答:
Shoes (Ruby) <s>235</s> 231

Everything computed from scratch.

```<code>Shoes.app{p,a,b,c=ARGV.map{|j|j.to_f/90}
k=1+i="i".to_c
p=(0..3).map{|j|y,z=(k*i**(j+a)).rect
x,z=(((-1)**j+z*i)*i**b).rect
q=(x+y*i)*i**c
[90*(k+q/(z-4)),90*(k+q/(4+z))]}
4.upto(15){|j|line *(p[j%4][0].rect+p[(j+j/4)%4][1].rect)}}
</code>```

Call from commandline eg shoes cube3d.rb 0 30 0

The idea is to simultaneously generate / rotate the four vertices of a tetrahedron in 3d. Then, as these are reduced to 2d, we generate the four vertices of the inverse tetrahedron (the total 8 vertices being those of the cube.) This gives 4 pairs of vertices corresponding to the 4 body diagonals. Finally the 2d vertices are connected by lines: each vertex of the original tetrahedron must be connected to each vertex of the inverse tetrahedron forming the 12 edges and 4 body diagonals of the cube. The ordering ensures the body diagonals are not plotted.

Test cases output

Note that, to be consistent with the last two test cases, rotation about the z axis is clockwise from the POV of the viewer. This seems to be in contradiction with the spec however. Rotation direction can be reversed by modifying *i**c -> /i**c

ungolfed

```<code>Shoes.app{
  p,a,b,c=ARGV.map{|j|j.to_f/90}   #Throw away first argument (script name) and translate next three to fractions of a right angle.
  k=1+i="i".to_c                   #set up constants i=sqrt(-1) and k=1+i

  p=(0..3).map{|j|                 #build an array p of 4 elements (each element wil be a 2-element array containing the ends of a body diagonal in complex number format)
    y,z=(k*i**(j+a)).rect          #generate 4 sides of square: 1+i,i-1,-1-i,-i+1, rotate about x axis by a, and store in y and z as reals
    x,z=(((-1)**j+z*i)*i**b).rect  #generate x axis displacements 1,-1,1,-1, rotate x and z about y axis by b, store in x and z as reals
    q=(x+y*i)*i**c                 #rotate x and y about z axis, store result in q as complex number
  [90*(k+q/(z-4)),90*(k+q/(4+z))]} #generate "far" vertex q/(4+z) and "near" vertex q/-(4-z) opposite ends of body diagonal in 2d format.

  4.upto(15){|j|                   #iterate through 12 edges, use rect and + to convert the two complex numbers into a 4 element array for line method
    line *(p[j%4][0].rect+         #cycle through 4 vertices of the "normal" tetrahedron
     p[(j+j/4)%4][1].rect)         #draw to three vertices of the "inverted" tetrahedron. j/4=1,2,3, never 0
  }                                #so the three edges are drawn but the body diagonal is not.
}
</code>```

Note that for historical reasons a scale factor of 90 is applied in line 9 (chosen to be the same as 90 degrees in line 2 for golfing) but in the end there was no golfing advantage in using this particular value, so it has become an arbitrary choice.

Title: Draw a simple cube

Body:
Shoes (Ruby) <s>235</s> 231

Everything computed from scratch.

Shoes.app{p,a,b,c=ARGV.map{|j|j.to_f/90}
k=1+i="i".to_c
p=(0..3).map{|j|y,z=(k*i**(j+a)).rect
x,z=(((-1)**j+z*i)*i**b).rect
q=(x+y*i)*i**c
[90*(k+q/(z-4)),90*(k+q/(4+z))]}
4.upto(15){|j|line *(p[j%4][0].rect+p[(j+j/4)%4][1].rect)}}

Call from commandline eg shoes cube3d.rb 0 30 0

The idea is to simultaneously generate / rotate the four vertices of a tetrahedron in 3d. Then, as these are reduced to 2d, we generate the four vertices of the inverse tetrahedron (the total 8 vertices being those of the cube.) This gives 4 pairs of vertices corresponding to the 4 body diagonals. Finally the 2d vertices are connected by lines: each vertex of the original tetrahedron must be connected to each vertex of the inverse tetrahedron forming the 12 edges and 4 body diagonals of the cube. The ordering ensures the body diagonals are not plotted.

Test cases output

Note that, to be consistent with the last two test cases, rotation about the z axis is clockwise from the POV of the viewer. This seems to be in contradiction with the spec however. Rotation direction can be reversed by modifying *i**c -> /i**c

ungolfed

Shoes.app{
  p,a,b,c=ARGV.map{|j|j.to_f/90}   #Throw away first argument (script name) and translate next three to fractions of a right angle.
  k=1+i="i".to_c                   #set up constants i=sqrt(-1) and k=1+i

  p=(0..3).map{|j|                 #build an array p of 4 elements (each element wil be a 2-element array containing the ends of a body diagonal in complex number format)
    y,z=(k*i**(j+a)).rect          #generate 4 sides of square: 1+i,i-1,-1-i,-i+1, rotate about x axis by a, and store in y and z as reals
    x,z=(((-1)**j+z*i)*i**b).rect  #generate x axis displacements 1,-1,1,-1, rotate x and z about y axis by b, store in x and z as reals
    q=(x+y*i)*i**c                 #rotate x and y about z axis, store result in q as complex number
  [90*(k+q/(z-4)),90*(k+q/(4+z))]} #generate "far" vertex q/(4+z) and "near" vertex q/-(4-z) opposite ends of body diagonal in 2d format.

  4.upto(15){|j|                   #iterate through 12 edges, use rect and + to convert the two complex numbers into a 4 element array for line method
    line *(p[j%4][0].rect+         #cycle through 4 vertices of the "normal" tetrahedron
     p[(j+j/4)%4][1].rect)         #draw to three vertices of the "inverted" tetrahedron. j/4=1,2,3, never 0
  }                                #so the three edges are drawn but the body diagonal is not.
}

Note that for historical reasons a scale factor of 90 is applied in line 9 (chosen to be the same as 90 degrees in line 2 for golfing) but in the end there was no golfing advantage in using this particular value, so it has become an arbitrary choice.


问:
Find the positive divisors!

Definition

A number is positive if it is greater than zero.

A number (A) is the divisor of another number (B) if A can divide B with no remainder.

For example, 2 is a divisor of 6 because 2 can divide 6 with no remainder.

Goal

Your task is to write a program/function that takes a positive number and then find all of its divisors.

Restriction

You may not use any built-in related to prime or factorization.

The complexity of your algorithm must not exceed O(sqrt(n)).

Freedom

The output list may contain duplicates.

The output list does not need to be sorted.

Scoring

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

Testcases

```<code>input    output
1        1
2        1,2
6        1,2,3,6
9        1,3,9
</code>```

答:
Python 2, 64 bytes

lambda n:sum([[x,n/x]for x in range(1,int(n**.5+1))if n%x<1],[])
```

This anonymous function outputs a list of divisors. The divisors are computed by trial division of integers in the range [1, ceil(sqrt(n))], which is O(sqrt(n)). If n % x == 0 (equivalent to n%x<1), then both x and n/x are divisors of n.

Try it online

Title: Find the positive divisors!

Body:
Python 2, 64 bytes

lambda n:sum([[x,n/x]for x in range(1,int(n**.5+1))if n%x<1],[])

This anonymous function outputs a list of divisors. The divisors are computed by trial division of integers in the range [1, ceil(sqrt(n))], which is O(sqrt(n)). If n % x == 0 (equivalent to n%x<1), then both x and n/x are divisors of n.

Try it online


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

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

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

Trailing newline can be either \nor \r\n

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

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

Example

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

Leaderboard

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

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

```

答:
LispyScript, 196 bytes

```<code>(->(require"http")(.createServer(function(q r)(r.end((str(-> (r.socket.remoteAddress)(.split".")(.map parseFloat)(.reduce (function(x y)(+ x y)))))'\n')(.listen(get 2 process.argv)"127.0.0.1"))))
</code>```

If it looks like one of the Node submissions above, that's because it's pretty much just Node with  a prettier face.

Ungolfed:

```<code>(->
  (require "http")
  (.createServer
    (function (request response)
      (response.writeHead 200 {'Content-Type': 'text/plain'})
      (response.end
        (str (-> (request.socket.remoteAddress)
             (.split ".")
             (.map parseFloat)
             (.reduce (function (x y) (+ x y)))))
          '\n')
  (.listen (|| (get 2 process.argv) 1337) "127.0.0.1"))))
</code>```

Two functions, two method chains.

Title: A simple TCP server

Body:
LispyScript, 196 bytes

(->(require"http")(.createServer(function(q r)(r.end((str(-> (r.socket.remoteAddress)(.split".")(.map parseFloat)(.reduce (function(x y)(+ x y)))))'\n')(.listen(get 2 process.argv)"127.0.0.1"))))

If it looks like one of the Node submissions above, that's because it's pretty much just Node with  a prettier face.

Ungolfed:

(->
  (require "http")
  (.createServer
    (function (request response)
      (response.writeHead 200 {'Content-Type': 'text/plain'})
      (response.end
        (str (-> (request.socket.remoteAddress)
             (.split ".")
             (.map parseFloat)
             (.reduce (function (x y) (+ x y)))))
          '\n')
  (.listen (|| (get 2 process.argv) 1337) "127.0.0.1"))))

Two functions, two method chains.


问:
Decompose a number!
Your task is to decompose a number using the format below.

This is similar to base conversion, except that instead of listing the digits in the base, you list the values, such that the list adds up to the input.

If the given base is \$n\$, then each number in the list must be in the form of \$k\times n^m\$, where \$0\le k<n\$ and \$m\$ is unique throughout the list.

Specs

Any reasonable input/output format. Your program/function takes 2 inputs and outputs a list.

Output list can be in any order.

0 can be excluded or included.

Leading 0s are allowed.

Built-ins are allowed.

Testcases

```<code>number base   converted list
input1 input2 output
123456 10     [100000,20000,3000,400,50,6] or [6,50,400,3000,20000,100000]
11     2      [8,2,1] or [0,0,0,0,8,0,2,1]
727    20     [400,320,7]
101    10     [100,1] or [100,0,1]
</code>```

Scoring

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

答:
Jelly, 7 bytes

```<code>lr0⁹*×b
</code>```

Try it online! or verify all test cases.

How it works

```<code>lr0⁹*×b  Main link. Arguments: x (integer), n (base)

l        Compute the logarithm of x to base n.
 r0      Range; yield all non-negative integers less than the logarithm, in
         decreasing order.
   ⁹*    Elevate n to all integers in that range.
      b  Yield the list of base-n digits of x.
     ×   Multiply each digit by the corresponding power of n.
</code>```

ContentLicense: CC BY-SA 4.0

Title: Decompose a number!

Body:
Jelly, 7 bytes

lr0⁹*×b

Try it online! or verify all test cases.

How it works

lr0⁹*×b  Main link. Arguments: x (integer), n (base)

l        Compute the logarithm of x to base n.
 r0      Range; yield all non-negative integers less than the logarithm, in
         decreasing order.
   ⁹*    Elevate n to all integers in that range.
      b  Yield the list of base-n digits of x.
     ×   Multiply each digit by the corresponding power of n.


答:
Ruby, 48 bytes

Uses arguments as input and stdout as output.

```<code>p !$*.map{a,*b=$*.rotate!
a.start_with? *b}.any?
</code>```

Title: Is it a prefix code?

Body:
Ruby, 48 bytes

Uses arguments as input and stdout as output.

p !$*.map{a,*b=$*.rotate!
a.start_with? *b}.any?


答:
Jelly, 23 bytes

```<code>ḅ⁹Bµ4374732215B×ḢḊ^µL¡Ḅ
</code>```

Input is in form of a list of integers. Try it online! or verify all test cases.

How it works

While Jelly has bitwise XOR, padding the input with zeroes and aligning the polynomial with the most significant binary digit makes this approach, which uses lists of bits instead, a tad shorter.

```<code>ḅ⁹Bµ4374732215B×ḢḊ^µL¡Ḅ  Main link. Argument: A (list of bytes)

ḅ⁹                       Convert A from base 256 to integer.
  B                      Convert the result to binary, yielding a list.
   µ                     Begin a new, monadic chain. Argument: B (list of bits)
    4374732215B          Convert the integer to binary, yielding a list.
                Ḣ        Pop and yield the first, most significant bit of B.
               ×         Multiply each bit in the polynomial by the popped bit.
                 ^       Compute the element-wise XOR of both lists.
                         If one of the lists is shorter, the elements of the other
                         lists do not get modified, thus avoiding the necessity
                         of right-padding B with zeroes.
                  µ      Convert the previous chain into a link.
                   L¡    Execute the chain L times, where L is the number of bits
                         in the original bit list.
                     Ḅ   Convert from binary to integer.
</code>```

Title: Compute CRC32 Hash

Body:
Credits

This challenge originated from @miles.

Create a function that computes the CRC32 hash of an input string. The input will be an ASCII string of any length. The output will be the CRC32 hash of that input string.

Explanation

The algorithm of CRC32 and other CRC are essentially the same, so only CRC3 will be demonstrated here.

Firstly, you have the generator polynomial, which is actually a 4-bit [n+1] integer (would be 33-bit in CRC32).

In this example, the generator polynomial is 1101.

Then, you will have the string to be hashed, which in this example would be 00010010111100101011001101.

```<code>00010010111100101011001101|000 (1)    append three [n] "0"s
   1101                        (2)    align with highest bit
00001000111100101011001101|000 (3)    XOR (1) and (2)
    1101                       (4)    align with highest bit
00000101111100101011001101|000 (5)    XOR (3) and (4)
     1101                      (6)    align with highest bit
00000011011100101011001101|000 (7)    XOR (5) and (6)
      1101                     (8)    align with highest bit
00000000001100101011001101|000 (9)    XOR (7) and (8)
          1101                 (10)   align with highest bit
00000000000001101011001101|000 (11)   XOR (9) and (10)
             1101              (12)   align with highest bit
00000000000000000011001101|000 (13)   XOR (11) and (12)
                  1101         (14)   align with highest bit
00000000000000000000011101|000 (15)   XOR (13) and (14)
                     1101      (16)   align with highest bit
00000000000000000000000111|000 (17)   XOR (15) and (16)
                       110 1   (18)   align with highest bit
00000000000000000000000001|100 (19)   XOR (17) and (18)
                         1 101 (20)   align with highest bit
00000000000000000000000000|001 (21)   XOR (19) and (20)
^--------REGION 1--------^ ^2^
</code>```

The remainder obtained at (21), when region 1 is zero, which is 001, would be the result of the CRC3 hash.

Specs

The generator polynomial is 0x104C11DB7, or 0b100000100110000010001110110110111, or 4374732215.

Input can be a string or a list of integers, or any other reasonable format.

Output be a hex string or just an integer, or any other reasonable format.

Built-ins that compute the CRC32 hash are not allowed.

Goal

Standard rules for code-golf apply.

The shortest code wins.

Test cases

```<code>input         output      (hex)
"code-golf"   147743960   08CE64D8
"jelly"       1699969158  65537886
""            0           00000000
</code>```

Body:
Jelly, 23 bytes

ḅ⁹Bµ4374732215B×ḢḊ^µL¡Ḅ

Input is in form of a list of integers. Try it online! or verify all test cases.

How it works

While Jelly has bitwise XOR, padding the input with zeroes and aligning the polynomial with the most significant binary digit makes this approach, which uses lists of bits instead, a tad shorter.

ḅ⁹Bµ4374732215B×ḢḊ^µL¡Ḅ  Main link. Argument: A (list of bytes)

ḅ⁹                       Convert A from base 256 to integer.
  B                      Convert the result to binary, yielding a list.
   µ                     Begin a new, monadic chain. Argument: B (list of bits)
    4374732215B          Convert the integer to binary, yielding a list.
                Ḣ        Pop and yield the first, most significant bit of B.
               ×         Multiply each bit in the polynomial by the popped bit.
                 ^       Compute the element-wise XOR of both lists.
                         If one of the lists is shorter, the elements of the other
                         lists do not get modified, thus avoiding the necessity
                         of right-padding B with zeroes.
                  µ      Convert the previous chain into a link.
                   L¡    Execute the chain L times, where L is the number of bits
                         in the original bit list.
                     Ḅ   Convert from binary to integer.


答:
Jelly, 9 bytes

```<code>½Rḍ³Tµ³:;
</code>```

As the other answers, this is O(√n) if we make the (false) assumption that integer division is O(1).

How it works

```<code>½Rḍ³Tµ³:;  Main link. Argument: n

½          Compute the square root of n.
 R         Construct the range from 1 to the square root.
  ḍ³       Test each integer of that range for divisibility by n.
    T      Get the indices of truthy elements.
     µ     Begin a new, monadic chain. Argument: A (list of divisors)
      ³:   Divide n by each divisor.
        ;  Concatenate the quotients with A.
</code>```

Try it online!

Title: Find the positive divisors!

Body:
Definition

A number is positive if it is greater than zero.

A number (A) is the divisor of another number (B) if A can divide B with no remainder.

For example, 2 is a divisor of 6 because 2 can divide 6 with no remainder.

Goal

Your task is to write a program/function that takes a positive number and then find all of its divisors.

Restriction

You may not use any built-in related to prime or factorization.

The complexity of your algorithm must not exceed O(sqrt(n)).

Freedom

The output list may contain duplicates.

The output list does not need to be sorted.

Scoring

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

Testcases

```<code>input    output
1        1
2        1,2
6        1,2,3,6
9        1,3,9
</code>```

Body:
Jelly, 9 bytes

½Rḍ³Tµ³:;

As the other answers, this is O(√n) if we make the (false) assumption that integer division is O(1).

How it works

½Rḍ³Tµ³:;  Main link. Argument: n

½          Compute the square root of n.
 R         Construct the range from 1 to the square root.
  ḍ³       Test each integer of that range for divisibility by n.
    T      Get the indices of truthy elements.
     µ     Begin a new, monadic chain. Argument: A (list of divisors)
      ³:   Divide n by each divisor.
        ;  Concatenate the quotients with A.

Try it online!


问:
Counting triangles with integer perimeter
Mary has given John two sticks of lengths a and b respectively, where a and b are positive integers.

John is very curious.

He would like to know how many triangles with integer perimeter can be formed, by having one additional side.

Please help him find it out.

(This is my first time composing this kind of stupid stories in coding problems, so forgive me if it is too stupid.)

Specs

Given two integers a and b, find the number of triangles with integer perimeter that can be formed, by having one additional side.

Details

Congruent triangles are congruent.

Flat triangles are flat out uncounted.

Zero-sided triangles are counted zero times.

Scoring

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

Testcases

```<code>a b output
1 2 1
3 3 5
9 7 13
</code>```

答:
APL, 6 bytes

```<code>1-⍨2×⌊
</code>```

This is a dyadic function train that accepts integers on the right and left and returns an integer. It uses the 2 min(a, b) - 1 approach.

Try it here (includes all test cases)

Body:
APL, 6 bytes

1-⍨2×⌊

This is a dyadic function train that accepts integers on the right and left and returns an integer. It uses the 2 min(a, b) - 1 approach.

Try it here (includes all test cases)


答:
Haskell, 49 bytes

```<code>g x=[1|z<-map((and.).zipWith(==))x<*>x,z]==(1<$x)
</code>```

This has a couple parts:

```<code>-- Are two lists (or strings) equal for their first min(length_of_1,length_of_2) elements, i.e. is one the prefix of the other?
(and.).zipWith(==)

-- Check whether one element is the prefix of the other, for all pairs of elements (including equal pairs)
map((and.).zipWith(==))x<*>x

-- This is a list of 1's of length (number of elements that are the prefix of the other)
[1|z<-map((and.).zipWith(==))x<*>x,z]

-- This is the input list, with all the elements replaced with 1's
(1<$x)
</code>```

If the two lists are equal, then an element is only the prefix of itself, and it's valid.

Title: Is it a prefix code?

Body:
Haskell, 49 bytes

g x=[1|z<-map((and.).zipWith(==))x<*>x,z]==(1<$x)

This has a couple parts:

-- Are two lists (or strings) equal for their first min(length_of_1,length_of_2) elements, i.e. is one the prefix of the other?
(and.).zipWith(==)

-- Check whether one element is the prefix of the other, for all pairs of elements (including equal pairs)
map((and.).zipWith(==))x<*>x

-- This is a list of 1's of length (number of elements that are the prefix of the other)
[1|z<-map((and.).zipWith(==))x<*>x,z]

-- This is the input list, with all the elements replaced with 1's
(1<$x)

If the two lists are equal, then an element is only the prefix of itself, and it's valid.


问:
Find the n-th perfect power!
A perfect power is a number of the form \$a^b\$, where \$a>0\$ and \$b>1\$.

For example, \$125\$ is a perfect power because it can be expressed as \$5^3\$.

Goal

Your task is to write  a program/function that finds the \$n\$-th perfect power, given a positive integer \$n\$.

Specs

The first perfect power is \$1\$ (which is \$1^2\$).

Input/output in any reasonable format.

Built-ins are allowed.

Further information

OEIS A001597

Scoring

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

Testcases

```<code>input  output
1      1
2      4
3      8
4      9
5      16
6      25
7      27
8      32
9      36
10     49
</code>```

答:
Julia, <s>64</s> 32 bytes

```<code>n->sort(∪([1:n]'.^[2:n+1]))[n]
</code>```

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

The idea here is the same as in LegionMammal's Mathematica answer: We take the outer product of the integers 1 to n with 2 to n + 1, collapse the resulting matrix column-wise, take unique elements, sort, and get the nth element.

Try it online! (includes all test cases)

Title: Find the n-th perfect power!

Body:
Julia, <s>64</s> 32 bytes

n->sort(∪([1:n]'.^[2:n+1]))[n]

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

The idea here is the same as in LegionMammal's Mathematica answer: We take the outer product of the integers 1 to n with 2 to n + 1, collapse the resulting matrix column-wise, take unique elements, sort, and get the nth element.

Try it online! (includes all test cases)


问:
Scale up an image!
Your task is to write a program/function to scale up an image (list of strings) by a factor of n.

Specs

You will receive two inputs: an image, and a positive integer.

The image will only contain ASCII printable characters (U+0020-U+007F).

Scoring

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

Testcases

Testcase 1

```<code>abc
xyz

2

aabbcc
aabbcc
xxyyzz
xxyyzz
</code>```

Testcase 2

```<code>|_|

3

|||___|||
|||___|||
|||___|||
</code>```

答:
Actually, 23 bytes

```<code>╗'
@s`╜;)*(Zk♂ΣiΣn`M'
j
</code>```

Takes the string input (with newlines represented as \ns to make multi-line input work) as the first input and the integer as the second.

Try it online!

Explanation (newlines replaced with \n):

```<code>╗'\n@s`╜;)*(Zk♂ΣiΣn`M'\nj
╗                          push n to reg0
 '\n@s                     split s on newlines
      `╜;)*(Zk♂ΣiΣn`M      for each line:
       ╜;)*(Z                make n copies and zip them
             k♂ΣiΣ           join the strings ("abc" -> ["abc", "abc"] -> "aabbcc" with n = 2)
                  n          make n copies of the result line
                     '\nj  join on newline
</code>```

Title: Scale up an image!

Body:
Actually, 23 bytes

╗'
@s`╜;)*(Zk♂ΣiΣn`M'
j

Takes the string input (with newlines represented as \ns to make multi-line input work) as the first input and the integer as the second.

Try it online!

Explanation (newlines replaced with \n):

╗'\n@s`╜;)*(Zk♂ΣiΣn`M'\nj
╗                          push n to reg0
 '\n@s                     split s on newlines
      `╜;)*(Zk♂ΣiΣn`M      for each line:
       ╜;)*(Z                make n copies and zip them
             k♂ΣiΣ           join the strings ("abc" -> ["abc", "abc"] -> "aabbcc" with n = 2)
                  n          make n copies of the result line
                     '\nj  join on newline


Title: Counting triangles with integer perimeter

Body:
Mary has given John two sticks of lengths a and b respectively, where a and b are positive integers.

John is very curious.

He would like to know how many triangles with integer perimeter can be formed, by having one additional side.

Please help him find it out.

(This is my first time composing this kind of stupid stories in coding problems, so forgive me if it is too stupid.)

Specs

Given two integers a and b, find the number of triangles with integer perimeter that can be formed, by having one additional side.

Details

Congruent triangles are congruent.

Flat triangles are flat out uncounted.

Zero-sided triangles are counted zero times.

Scoring

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

Testcases

```<code>a b output
1 2 1
3 3 5
9 7 13
</code>```

Body:
C# 6.0 - 34 bytes

int a(int b,int c)=>(b<c?b:c)*2-1;


Title: Is it a prefix code?

Body:
In information theory, a "prefix code" is a dictionary where none of the keys are a prefix of another. In other words, this means that none of the strings starts with any of the other.

For example, {"9", "55"} is a prefix code, but {"5", "9", "55"} is not.

The biggest advantage of this, is that the encoded text can be written down with no separator between them, and it will still be uniquely decipherable. This shows up in compression algorithms such as Huffman coding, which always generates the optimal prefix code.

Your task is simple: Given a list of strings, determine whether or not it is a valid prefix code.

Your input:

Will be a list of strings in any reasonable format.

Will only contain printable ASCII strings.

Will not contain any empty strings.

Your output will be a truthy/falsey value: Truthy if it's a valid prefix code, and falsey if it isn't.

Here are some true test cases:

```<code>["Hello", "World"]
["Code", "Golf", "Is", "Cool"]
["1", "2", "3", "4", "5"]
["This", "test", "case", "is", "true"]

["111", "010", "000", "1101", "1010", "1000", "0111", "0010", "1011",
 "0110", "11001", "00110", "10011", "11000", "00111", "10010"]
</code>```

Here are some false test cases:

```<code>["4", "42"]
["1", "2", "3", "34"]
["This", "test", "case", "is", "false", "t"]
["He", "said", "Hello"]
["0", "00", "00001"]
["Duplicate", "Duplicate", "Keys", "Keys"]
</code>```

This is code-golf, so standard loopholes apply, and shortest answer in bytes wins.

Body:
JavaScript (ES6), 52 <s>54</s>

Edit 2 bytes saved thx @Neil

a=>!a.some((w,i)=>a.some((v,j)=>i-j&&!w.indexOf(v)))

Test

f=a=>!a.some((w,i)=>a.some((v,j)=>i-j&&!w.indexOf(v)))

O.textContent += 'OK: '+
[["Hello", "World"]
,["Code", "Golf", "Is", "Cool"]
,["1", "2", "3", "4", "5"]
,["This", "test", "case", "is", "true"]
,["111", "010", "000", "1101", "1010", "1000", "0111", "0010", "1011",
 "0110", "11001", "00110", "10011", "11000", "00111", "10010"]
].map(a=>f(a))

O.textContent += '\nKO: '+
[["4", "42"]
,["1", "2", "3", "34"]
,["This", "test", "case", "is", "false", "t"]
,["He", "said", "Hello"]
,["0", "00", "00001"]
,["Duplicate", "Duplicate", "Keys", "Keys"]
].map(a=>f(a))

<pre id=O></pre>


答:
05AB1E, 4 3 2 bytes

Crossed out 4 is still regular 4 ;(

Thanks to @Adnan for a byte.

```<code>žt
</code>```

Uses CP-1252 encoding.

Explanation:

```<code>žt - Push input. Pop a, push e to a places (up to 10000).
</code>```

Update:

Remove I, as žt takes input anyway if none is on the stack.

ContentLicense: CC BY-SA 2.5

Title: Compute the first N digits of e

Body:
Challenge

Write a program to compute the the first N (<= 10^3) digits of e.

Your program should take an integer N as input.

Input:

```<code>100
</code>```

Output:

```<code>2.718281828459045235360287471352662497757247093699959574966967627724076630353547594571382178525166427
</code>```

Input:

```<code>7
</code>```

Output:

```<code>2.718282
</code>```

Input:

```<code>1000
</code>```

Output:

```<code>2.718281828459045235360287471352662497757247093699959574966967627724076630353547594571382178525166427427466391932003059921817413596629043572900334295260595630738132328627943490763233829880753195251019011573834187930702154089149934884167509244761460668082264800168477411853742345442437107539077744992069551702761838606261331384583000752044933826560297606737113200709328709127443747047230696977209310141692836819025515108657463772111252389784425056953696770785449969967946864454905987931636889230098793127736178215424999229576351482208269895193668033182528869398496465105820939239829488793320362509443117301238197068416140397019837679320683282376464804295311802328782509819455815301756717361332069811250996181881593041690351598888519345807273866738589422879228499892086805825749279610484198444363463244968487560233624827041978623209002160990235304369941849146314093431738143640546253152096183690888707016768396424378140592714563549061303107208510383750510115747704171898610687396965521267154688957035035
</code>```

Shortest solution wins!

Body:
05AB1E, 4 3 2 bytes

Crossed out 4 is still regular 4 ;(

Thanks to @Adnan for a byte.

žt

Uses CP-1252 encoding.

Explanation:

žt - Push input. Pop a, push e to a places (up to 10000).

Update:

Remove I, as žt takes input anyway if none is on the stack.


问:
How can I shorten this python code analyzing a 3d grid?
My Python 3 function golf(...) should take a list of lists of lists of strings representing a solid cube and return whether there are any places in which two equal strings are directly next to each other on the x, y or z axis (not diagonally).

If there are no adjacent duplicates, True shall be returned, else False.

The input list and all of its sublists have the same length as they represent a cube, and their length is greater than 1 but lower than or equal to 5. The only possible values for the Strings inside the nested lists are "X" and "Z".

The maximum code length should be less than 200 bytes.

This is an example test case:

```<code>golf([[["X", "Z"],
       ["Z", "X"]],
      [["Z", "X"],
       ["X", "Z"]]]) == True
golf([[["X", "Z"],
       ["Z", "X"]],
      [["X", "Z"],
       ["Z", "X"]]]) == False
</code>```

My current solution has 234 bytes:

```<code>def golf(c):
 r=range(len(c));R=[(a,b)for a in r for b in r];j="".join
 return all("XX"not in l and"ZZ"not in l for l in[j(c[x][y][z]for x in r)for y,z in R]+[j(c[x][y][z]for y in r)for x,z in R]+[j(c[x][y][z]for z in r)for x,y in R])
</code>```

How can I golf this code any further to save another 35 bytes?

答:
Python 3, 60 bytes

golf=g=lambda l:all(g(a)*g(b)*(a!=b)for a,b in zip(l,l[1:]))
```

The function recursively decides whether an N-dimensional array is alternating by checking if:

Any two adjacent elements are unequal

Each element is alternating

This successfully bottoms out for the strings 'X' and 'Z' because their length is 1, so the all is taken of an empty list.

Body:
Python 3, 60 bytes

golf=g=lambda l:all(g(a)*g(b)*(a!=b)for a,b in zip(l,l[1:]))

The function recursively decides whether an N-dimensional array is alternating by checking if:

Any two adjacent elements are unequal

Each element is alternating

This successfully bottoms out for the strings 'X' and 'Z' because their length is 1, so the all is taken of an empty list.


答:
Actually, 3 bytes

```<code>mτD
</code>```

Try it online or verify all test cases at once

This uses the same 2*min(a,b)-1 approach that basically every other solutions uses. Each operation (minimum, double, decrement) is its own single-byte command.

Body:
Actually, 3 bytes

mτD

Try it online or verify all test cases at once

This uses the same 2*min(a,b)-1 approach that basically every other solutions uses. Each operation (minimum, double, decrement) is its own single-byte command.


答:
Python, <s>58</s> 55 bytes

lambda l:sum(0==a.find(b)for a in l for b in l)==len(l)
```

Title: Is it a prefix code?


答:
Retina, 19 bytes

Byte count assumes ISO 8859-1 encoding.

```<code>O`.+
Mm1`^(.+)¶\1
0
</code>```

The input should be linefeed-separated. Output is 0 for falsy and 1 for truthy.

Try it online! (Slightly modified to support multiple space-separated test cases instead.)

Explanation

```<code>O`.+
</code>```

Sort the lines in the input. If a prefix exists it will end up directly in front of a string which contains it.

```<code>Mm1`^(.+)¶\1
</code>```

Try to match (M) a complete line which is also found at the beginning of the next line. The m activates multiline mode such that ^ matches line beginnings and the 1 ensures that we only count at most one match such that the output is 0 or 1.

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

To swap 0 and 1 in the result, we count the number of 0s.

Title: Is it a prefix code?

Body:
Retina, 19 bytes

Byte count assumes ISO 8859-1 encoding.

O`.+
Mm1`^(.+)¶\1
0

The input should be linefeed-separated. Output is 0 for falsy and 1 for truthy.

Try it online! (Slightly modified to support multiple space-separated test cases instead.)

Explanation

O`.+

Sort the lines in the input. If a prefix exists it will end up directly in front of a string which contains it.

Mm1`^(.+)¶\1

Try to match (M) a complete line which is also found at the beginning of the next line. The m activates multiline mode such that ^ matches line beginnings and the 1 ensures that we only count at most one match such that the output is 0 or 1.

0

To swap 0 and 1 in the result, we count the number of 0s.


答:
JavaScript ES6, <s>65</s> <s>43</s> 40 bytes

```<code>a=>!/(.*)\1/.test(''+a.sort().join``)
      ^            ^               ^ embedded NUL characters
</code>```

My previous solution, which handled string arrays of all UTF-8 characters:

```<code>a=>!/[^\\]("([^"]*\\")*[^\\])",\1/.test(JSON.stringify(a.sort()))
</code>```

I was able to avoid JSON.stringify since the challenge specifies printable ASCII characters only.

Test

f=a=>!/(\0.*)\1/.test('\0'+a.sort().join`\0`) // since stackexchange removes embedded NUL characters

O.textContent += 'OK: '+
[["Hello", "World"]
,["Code", "Golf", "Is", "Cool"]
,["1", "2", "3", "4", "5"]
,["This", "test", "case", "is", "true"]
,["111", "010", "000", "1101", "1010", "1000", "0111", "0010", "1011",
 "0110", "11001", "00110", "10011", "11000", "00111", "10010"]
].map(a=>f(a))

O.textContent += '\nKO: '+
[["4", "42"]
,["1", "2", "3", "34"]
,["This", "test", "case", "is", "false", "t"]
,["He", "said", "Hello"]
,["0", "00", "00001"]
,["Duplicate", "Duplicate", "Keys", "Keys"]
].map(a=>f(a))```
<pre class="snippet-code-html lang-html prettyprint-override"><code><pre id=O>``````

Title: Is it a prefix code?

Body:
JavaScript ES6, <s>65</s> <s>43</s> 40 bytes

a=>!/(.*)\1/.test(''+a.sort().join``)
      ^            ^               ^ embedded NUL characters

My previous solution, which handled string arrays of all UTF-8 characters:

a=>!/[^\\]("([^"]*\\")*[^\\])",\1/.test(JSON.stringify(a.sort()))

I was able to avoid JSON.stringify since the challenge specifies printable ASCII characters only.

Test

f=a=>!/(\0.*)\1/.test('\0'+a.sort().join`\0`) // since stackexchange removes embedded NUL characters

O.textContent += 'OK: '+
[["Hello", "World"]
,["Code", "Golf", "Is", "Cool"]
,["1", "2", "3", "4", "5"]
,["This", "test", "case", "is", "true"]
,["111", "010", "000", "1101", "1010", "1000", "0111", "0010", "1011",
 "0110", "11001", "00110", "10011", "11000", "00111", "10010"]
].map(a=>f(a))

O.textContent += '\nKO: '+
[["4", "42"]
,["1", "2", "3", "34"]
,["This", "test", "case", "is", "false", "t"]
,["He", "said", "Hello"]
,["0", "00", "00001"]
,["Duplicate", "Duplicate", "Keys", "Keys"]
].map(a=>f(a))

<pre id=O></pre>


答:
CJam, 14 bytes

```<code>q~$W%2ew::#0&!
</code>```

Test suite.

Explanation

```<code>q~   e# Read and evaluate input.
$    e# Sort strings. If a prefix exists it will end up directly in front
     e# of a string which contains it.
W%   e# Reverse list.
2ew  e# Get all consecutive pairs of strings.
::#  e# For each pair, find the first occurrence of the second string in the first.
     e# If a prefix exists that will result in a 0, otherwise in something non-zero.
0&   e# Set intersection with 0, yielding [0] for falsy cases and [] for truthy ones.
!    e# Logical NOT.
</code>```

Title: Is it a prefix code?

Body:
CJam, 14 bytes

q~$W%2ew::#0&!

<a href="http://cjam.aditsu.net/#code=qN%2F%7B%3AQ%3B%0A%0AQ~%24W%252ew%3A%3A%230%26!%0A%0A%5DoNo%7D%2F&input=%5B%22Hello%22%20%22World%22%5D%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%0A%5B%22Code%22%20%22Golf%22%20%22Is%22%20%22Cool%22%5D%0A%5B%221%22%20%222%22%20%223%22%20%224%22%20%225%22%5D%0A%5B%22This%22%20%22test%22%20%22case%22%20%22is%22%20%22true%22%5D%20%20%20%20%20%20%20%20%20%20%0A%5B%22111%22%20%22010%22%20%22000%22%20%221101%22%20%221010%22%20%221000%22%20%220111%22%20%220010%22%20%221011%22%20%220110%22%20%2211001%22%20%2200110%22%20%2210011%22%20%2211000%22%20%2200111%22%20%2210010%22%5D%0A%5B%224%22%20%2242%22%5D%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%0A%5B%221%22%20%222%22%20%223%22%20%2234%22%5D%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%0A%5B%22This%22%20%22test%22%20%22case%22%20%22is%22%20%22false%22%20%22t%22%5D%0A%5B%22He%22%20%22said%22%20%22Hello%22%5D%0A%5B%220%22%20%2200%22%20%2200001%22%5D%0A%5B%22Duplicate%22%20%22Duplicate%22%20%22Keys%22%20%22Keys%22%5D" rel="nofollow">Test suite.

Explanation

q~   e# Read and evaluate input.
$    e# Sort strings. If a prefix exists it will end up directly in front
     e# of a string which contains it.
W%   e# Reverse list.
2ew  e# Get all consecutive pairs of strings.
::#  e# For each pair, find the first occurrence of the second string in the first.
     e# If a prefix exists that will result in a 0, otherwise in something non-zero.
0&   e# Set intersection with 0, yielding [0] for falsy cases and [] for truthy ones.
!    e# Logical NOT.


问:
Smallest groups in an array

Introduction

Let's observe the following array:

```<code>[1, 1, 1, 2, 2, 1, 1, 1, 1, 2, 2, 2, 1, 1, 1]
</code>```

A group consists of the same digits next to each other. In the above array, there are 5 different groups:

```<code>[1, 1, 1, 2, 2, 1, 1, 1, 1, 2, 2, 2, 1, 1, 1]

 1, 1, 1
          2, 2
                1, 1, 1, 1
                            2, 2, 2
                                     1, 1, 1
</code>```

The smallest group of these is [2, 2], so we output [2, 2].

Let's take another example:

```<code>[3, 3, 3, 4, 4, 4, 4, 5, 5, 4, 4, 3, 3, 4, 4]

 3, 3, 3
          4, 4, 4, 4
                      5, 5
                            4, 4
                                  3, 3
                                        4, 4
</code>```

You can see that there are multiple groups with the same length. The smallest groups are:

```<code>[3, 3], [4, 4], [4, 4] and [5, 5].
</code>```

So we just output [3, 3], [4, 4], [4, 4], [5, 5] in any reasonable format. You may output these in any order.

The Task

Given an array consisting of only positive integers, output the smallest group(s) from the array. You can assume that the array will contain at least 1 integer.

Test cases

```<code>Input: [1, 1, 2, 2, 3, 3, 4]
Output: [4]

Input: [1]
Output: [1]

Input: [1, 1, 10, 10, 10, 100, 100]
Output: [1, 1], [100, 100]
</code>```

This is code-golf, so the submission with the least amount of bytes wins!

答:
Python 2, 120 bytes

import re
r=[x.group().split()for x in re.finditer(r'(\d+ )\1*',input())]
print[x for x in r if len(x)==min(map(len,r))]
```

Takes input as a string of space-separated integers with a trailing space, and outputs a list of lists of strings. The strategy is to find groups using the regex (\d+ )\1* (which matches one or more space-separated integers, with a trailing space), then split them on spaces into lists of integers, and print those groups whose length is equal to the minimum group length.

Try it online

Title: Smallest groups in an array

Body:
Python 2, 120 bytes

import re
r=[x.group().split()for x in re.finditer(r'(\d+ )\1*',input())]
print[x for x in r if len(x)==min(map(len,r))]

Takes input as a string of space-separated integers with a trailing space, and outputs a list of lists of strings. The strategy is to find groups using the regex (\d+ )\1* (which matches one or more space-separated integers, with a trailing space), then split them on spaces into lists of integers, and print those groups whose length is equal to the minimum group length.

Try it online


答:
JavaScript (ES6), 87

n=>(b=>{for(l=[i=0,1];b<n*n;++b)for(v=b;v<n*n;)l[v*=b]=v;l.some(x=>n==i++?v=x:0)})(2)|v
```

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

<pre class="lang-js prettyprint-override"><code>f=n=>{
  for(b=2, l=[0,1]; b < n*n; ++b)
    for(v = b; v < n*n;)
      l[v*=b] = v;
  i = 0;
  l.some(x => n == i++ ? v=x : 0);
  return v;
  // shorter alternative, but too much memory used even for small inputs
  // return l.filter(x=>x) [n-1];
}
</code>```

Test

f=n=>(b=>{for(l=[i=0,1];b<n*n;++b)for(v=b;v<n*n;)l[v*=b]=v;l.some(x=>n==i++?v=x:0)})(2)|v

function test(){
  var v=+I.value
  O.textContent=f(v)
}

test()```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type=number id=I value=10><button onclick='test()'>-></button>
<span id=O></span></code>```

Title: Find the n-th perfect power!

Body:
A perfect power is a number of the form \$a^b\$, where \$a>0\$ and \$b>1\$.

For example, \$125\$ is a perfect power because it can be expressed as \$5^3\$.

Goal

Your task is to write  a program/function that finds the \$n\$-th perfect power, given a positive integer \$n\$.

Specs

The first perfect power is \$1\$ (which is \$1^2\$).

Input/output in any reasonable format.

Built-ins are allowed.

Further information

OEIS A001597

Scoring

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

Testcases

```<code>input  output
1      1
2      4
3      8
4      9
5      16
6      25
7      27
8      32
9      36
10     49
</code>```

Body:
JavaScript (ES6), 87

n=>(b=>{for(l=[i=0,1];b<n*n;++b)for(v=b;v<n*n;)l[v*=b]=v;l.some(x=>n==i++?v=x:0)})(2)|v

Less golfed

f=n=>{
  for(b=2, l=[0,1]; b < n*n; ++b)
    for(v = b; v < n*n;)
      l[v*=b] = v;
  i = 0;
  l.some(x => n == i++ ? v=x : 0);
  return v;
  // shorter alternative, but too much memory used even for small inputs
  // return l.filter(x=>x) [n-1];
}

Test

f=n=>(b=>{for(l=[i=0,1];b<n*n;++b)for(v=b;v<n*n;)l[v*=b]=v;l.some(x=>n==i++?v=x:0)})(2)|v

function test(){
  var v=+I.value
  O.textContent=f(v)
}

test()

<input type=number id=I value=10><button onclick='test()'>-></button>
<span id=O></span>


答:
Python 2, 48 <s>51</s> bytes

lambda l:all(1/map(a.find,l).count(0)for a in l)
```
<p>For each element <code>a</code> of <code>l</code>, the function <code>a.find</code> finds the index of the first occurrence of <code>a</code> in the input string, giving <code>-1</code> for an absence. So, <code>0</code> indicates a prefix. In a prefix-free list, mapping this function returns only a single <code>0</code> for <code>a</code> itself. The function checks that this is the case for every <code>a</code>.</p>
<hr />
<p><strong>51 bytes:</strong></p>
<pre class="lang-python prettyprint-override"><code>lambda l:[a for a in l for b in l if b<=a<b+'~']==l
</code>```

Replace ~ with a character with ASCII code 128 or higher.

For each element a in l, a copy is included for each element that's a prefix of it. For a prefix-free list, the only such element is a itself, so this gives the original list.

Title: Is it a prefix code?

Body:
Python 2, 48 <s>51</s> bytes

lambda l:all(1/map(a.find,l).count(0)for a in l)

For each element a of l, the function a.find finds the index of the first occurrence of a in the input string, giving -1 for an absence. So, 0 indicates a prefix. In a prefix-free list, mapping this function returns only a single 0 for a itself. The function checks that this is the case for every a.

51 bytes:

lambda l:[a for a in l for b in l if b<=a<b+'~']==l

Replace ~ with a character with ASCII code 128 or higher.

For each element a in l, a copy is included for each element that's a prefix of it. For a prefix-free list, the only such element is a itself, so this gives the original list.


答:
Actually, 18 bytes

```<code>;;u@ⁿr;`;√≈²=`M@░E
</code>```

Try it online! (may not work due to needing an update)

Explanation:

```<code>;;u@ⁿr;`;√≈²=`M@░E
;;u@ⁿr              push range(n**(n+1))
      ;`;√≈²=`M@░   filter: take if
        ;√≈²=         int(sqrt(x))**2 == x
                 E  get nth element
</code>```

Title: Find the n-th perfect power!

Body:
Actually, 18 bytes

;;u@ⁿr;`;√≈²=`M@░E

Try it online! (may not work due to needing an update)

Explanation:

;;u@ⁿr;`;√≈²=`M@░E
;;u@ⁿr              push range(n**(n+1))
      ;`;√≈²=`M@░   filter: take if
        ;√≈²=         int(sqrt(x))**2 == x
                 E  get nth element


答:
Haskell, 37 bytes

f l=[x|x<-l,y<-l,zip x x==zip x y]==l
```

Each element x of l is repeated once for every element that it's a prefix of, which is exactly once for a prefix-free list, giving the original list. The prefix property is checked by zipping both lists with x, which cuts off elements beyond the length of x.

Title: Is it a prefix code?

Body:
Haskell, 37 bytes

f l=[x|x<-l,y<-l,zip x x==zip x y]==l

Each element x of l is repeated once for every element that it's a prefix of, which is exactly once for a prefix-free list, giving the original list. The prefix property is checked by zipping both lists with x, which cuts off elements beyond the length of x.


答:
Retina, <s>91</s> <s>85</s> <s>80</s> <s>79</s> <s>77</s> <s>76</s> <s>75</s> 74 bytes

```<code>M!`\b(\d+)(,\1\b)*
(,()|.)+
$#2:$&
O#`.+
s`^(.*\b(.+:).*)¶(?!\2).+
$1
.+:
<empty-line>
</code>```

Try it online!

Explanation

The input is 1,1,10,10,10,100,100.

The first line matches groups with same terms:

```<code>M!`\b(\d+)(,\1\b)*
</code>```

The input becomes:

```<code>1,1
10,10,10
100,100
</code>```

The following two lines prepend the number of commas to the line:

```<code>(,()|.)+
$#2:$&
</code>```

The input becomes:

```<code>1:1,1
2:10,10,10
1:100,100
</code>```

Then they are sorted by this line, which looks for the first number as index:

```<code>O#`.+
</code>```

The input becomes:

```<code>1:1,1
1:100,100
2:10,10,10
</code>```

Then these two lines find the place where the length is different, and remove everything onwards:

```<code>s`^(.*\b(.+:).*)¶(?!\2).+
$1
</code>```

The input becomes:

```<code>1:1,1
1:100,100
</code>```

Then the numbers are removed by these two lines:

```<code>.+:
<empty-line>
</code>```

Where the input becomes:

```<code>M!`\b(\d+)(,\1\b)*
</code>```0

Title: Smallest groups in an array

Body:
Introduction

Let's observe the following array:

```<code>[1, 1, 1, 2, 2, 1, 1, 1, 1, 2, 2, 2, 1, 1, 1]
</code>```

A group consists of the same digits next to each other. In the above array, there are 5 different groups:

```<code>[1, 1, 1, 2, 2, 1, 1, 1, 1, 2, 2, 2, 1, 1, 1]

 1, 1, 1
          2, 2
                1, 1, 1, 1
                            2, 2, 2
                                     1, 1, 1
</code>```

The smallest group of these is [2, 2], so we output [2, 2].

Let's take another example:

```<code>[3, 3, 3, 4, 4, 4, 4, 5, 5, 4, 4, 3, 3, 4, 4]

 3, 3, 3
          4, 4, 4, 4
                      5, 5
                            4, 4
                                  3, 3
                                        4, 4
</code>```

You can see that there are multiple groups with the same length. The smallest groups are:

```<code>[3, 3], [4, 4], [4, 4] and [5, 5].
</code>```

So we just output [3, 3], [4, 4], [4, 4], [5, 5] in any reasonable format. You may output these in any order.

The Task

Given an array consisting of only positive integers, output the smallest group(s) from the array. You can assume that the array will contain at least 1 integer.

Test cases

```<code>Input: [1, 1, 2, 2, 3, 3, 4]
Output: [4]

Input: [1]
Output: [1]

Input: [1, 1, 10, 10, 10, 100, 100]
Output: [1, 1], [100, 100]
</code>```

This is code-golf, so the submission with the least amount of bytes wins!

Body:
Retina, <s>91</s> <s>85</s> <s>80</s> <s>79</s> <s>77</s> <s>76</s> <s>75</s> 74 bytes

M!`\b(\d+)(,\1\b)*
(,()|.)+
$#2:$&
O#`.+
s`^(.*\b(.+:).*)¶(?!\2).+
$1
.+:
<empty-line>

Try it online!

Explanation

The input is 1,1,10,10,10,100,100.

The first line matches groups with same terms:

M!`\b(\d+)(,\1\b)*

The input becomes:

1,1
10,10,10
100,100

The following two lines prepend the number of commas to the line:

(,()|.)+
$#2:$&

The input becomes:

1:1,1
2:10,10,10
1:100,100

Then they are sorted by this line, which looks for the first number as index:

O#`.+

The input becomes:

1:1,1
1:100,100
2:10,10,10

Then these two lines find the place where the length is different, and remove everything onwards:

s`^(.*\b(.+:).*)¶(?!\2).+
$1

The input becomes:

1:1,1
1:100,100

Then the numbers are removed by these two lines:

.+:
<empty-line>

Where the input becomes:

1,1
100,100


答:
Scala, 71 bytes

```<code>(s:Seq[String])=>(for{x<-s;y<-s}yield x!=y&&x.startsWith(y)).forall(!_)
</code>```

Title: Is it a prefix code?

Body:
In information theory, a "prefix code" is a dictionary where none of the keys are a prefix of another. In other words, this means that none of the strings starts with any of the other.

For example, {"9", "55"} is a prefix code, but {"5", "9", "55"} is not.

The biggest advantage of this, is that the encoded text can be written down with no separator between them, and it will still be uniquely decipherable. This shows up in compression algorithms such as Huffman coding, which always generates the optimal prefix code.

Your task is simple: Given a list of strings, determine whether or not it is a valid prefix code.

Your input:

Will be a list of strings in any reasonable format.

Will only contain printable ASCII strings.

Will not contain any empty strings.

Your output will be a truthy/falsey value: Truthy if it's a valid prefix code, and falsey if it isn't.

Here are some true test cases:

```<code>["Hello", "World"]
["Code", "Golf", "Is", "Cool"]
["1", "2", "3", "4", "5"]
["This", "test", "case", "is", "true"]

["111", "010", "000", "1101", "1010", "1000", "0111", "0010", "1011",
 "0110", "11001", "00110", "10011", "11000", "00111", "10010"]
</code>```

Here are some false test cases:

```<code>["4", "42"]
["1", "2", "3", "34"]
["This", "test", "case", "is", "false", "t"]
["He", "said", "Hello"]
["0", "00", "00001"]
["Duplicate", "Duplicate", "Keys", "Keys"]
</code>```

This is code-golf, so standard loopholes apply, and shortest answer in bytes wins.

Body:
Scala, 71 bytes

(s:Seq[String])=>(for{x<-s;y<-s}yield x!=y&&x.startsWith(y)).forall(!_)


答:
JavaScript (ES6), 112 bytes

```<code>n=>[...s=` `.repeat(n)].map(_=>s.replace(/./g,_=>`# `[+g(n+1,i++)],n-=i=1),g=(i,j)=>i?i>j||g(j%i,i):j>1).join`\n`
</code>```

Where \n represents the literal newline character. Alternative solution, also 112 bytes:

```<code>n=>(s=`# `.repeat(n)).replace(r=/../g,_=>s.replace(r,m=>m[+g(n+1,i++)],n-=i=1)+`
`,g=(i,j)=>i?i>j||g(j%i,i):j>1)
</code>```

Title: Draw a phi triangle

Body:
Clarification: Basically, you need to make this

Euler's totient function has the name phi.

Let's try to calculate phi(8)

First, list all numbers 8 and under backwards, not including 0 or under

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

Now find which numbers don't share a factor with 8 (1 doesn't count), and place a # in their place.

```<code>8
#
6
#
4
#
2
#
</code>```

Remove the numbers.

```<code>#

#

#

#
                                                 -
</code>```

Now do this, but string the outputs together in a triangle

```<code>        9
       88
      777
     6666
    55555
   444444
  3333333
 22222222
111111111
---------
123456789
</code>```

# out non-factor sharing numbers

```<code>        9
       8#
      7##
     6#66
    5####
   4#4#4#
  3##3##3
 2#2#2#2#
#########
</code>```

Remove numbers:

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

This would be the output for input 9 (since 9 columns.)

Leading + trailing newlines allowed.

Body:
JavaScript (ES6), 112 bytes

n=>[...s=` `.repeat(n)].map(_=>s.replace(/./g,_=>`# `[+g(n+1,i++)],n-=i=1),g=(i,j)=>i?i>j||g(j%i,i):j>1).join`\n`

Where \n represents the literal newline character. Alternative solution, also 112 bytes:

n=>(s=`# `.repeat(n)).replace(r=/../g,_=>s.replace(r,m=>m[+g(n+1,i++)],n-=i=1)+`
`,g=(i,j)=>i?i>j||g(j%i,i):j>1)


Title: Smallest groups in an array

Body:
JavaScript (ES6), 106

a=>(a.map((v,i)=>v==a[i-1]?g.push(v):h.push(g=[v]),h=[]),h.filter(x=>!x[Math.min(...h.map(x=>x.length))]))

Test

f=a=>(a.map((v,i)=>v==a[i-1]?g.push(v):h.push(g=[v]),h=[]),h.filter(x=>!x[Math.min(...h.map(x=>x.length))]))

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

;[[1, 1, 1, 2, 2, 1, 1, 1, 1, 2, 2, 2, 1, 1, 1]
, [3, 3, 3, 4, 4, 4, 4, 5, 5, 4, 4, 3, 3, 4, 4]
, [1, 1, 2, 2, 3, 3, 4]
, [1]
, [1, 1, 10, 10, 10, 100, 100]]
.forEach(t=>console.log(t+' -> '+f(t).join` `))

<pre id=O></pre>