问:
The IHIH Pyramid
I find it fascinating how the letters "H" and "I" are very similar. "H" is a horizontal stroke surrounded by two vertical strokes; "I" is a vertical stroke surrounded by two horizontal strokes (depending on your font). I bet this could be nested... You know what that reminds me of? Fractals!!!

Let's define the "IHIH" pyramid as follows: The first iteration is this ASCII representation of the letter "I":

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

The next iteration has a vertical stroke on either side.

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

If you view the "I" in the middle as a single horizontal stroke, then this second iteration is basically an "H". The third iteration adds a horizontal stroke on the top and bottom

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

Again, if you view the "H" in the middle as a single vertical stroke, then this iteration is basically an "I". This pattern continues, alternating between "H"s and "I"s on every iteration. For reference, here are the first 6 iterations:

```<code>1:
---
 |
---

2:
|   |
|---|
| | |
|---|
|   |

3:
-------
 |   |
 |---|
 | | |
 |---|
 |   |
-------

4:
|       |
|-------|
| |   | |
| |---| |
| | | | |
| |---| |
| |   | |
|-------|
|       |

5:
-----------
 |       |
 |-------|
 | |   | |
 | |---| |
 | | | | |
 | |---| |
 | |   | |
 |-------|
 |       |
-----------

6:
|           |
|-----------|
| |       | |
| |-------| |
| | |   | | |
| | |---| | |
| | | | | | |
| | |---| | |
| | |   | | |
| |-------| |
| |       | |
|-----------|
|           |
</code>```

The Challenge:

Write a program or function that outputs the N'th iteration of the IHIH pyramid, and an optional trailing newline. Your input will be a single positive integer in whatever reasonable format you want. You do not have to handle invalid inputs, e.g. non-integers, numbers smaller than 1, etc. Your program must at the very least produce the right output for inputs up to 20. Since this is code-golf, standard loopholes are not allowed and the shortest answer in bytes wins!

答:
Cheddar, <s>186</s> <s>177</s> <s>165</s> <s>154</s> <s>148</s> 131 bytes

```<code>(n,b?,c?,q?,g=s->(n-=1)<0?s:g((q=(c=s.lines[0].len)%4>2?b='|'+" "*c+"|":b='-'*(c+2))+"\n"+s.sub(/^|$/gm,q?'|':' ')+"\n"+b))->g("|")
</code>```

Uses recursion. Will add explanation once done golfing.

Try it online!

Explanation

This one is a bit complex too keep track off all the variables I'm using but I'll try to keep it simple:

```<code>(
 n,    // Input
 b?,   // Stores row to add to top/bottom
 c?,   // Width of string
 q?,   // false if I-ifying. true if not
 g=
   s->          // Main logic, s is generated string
    (n-=1)<0 ? s :   // Decrease input each iteration. Stop when 0
    g(               // Recurse with....
      (
        q= (         // Set `q` true if h-ifying. false if I-ifying
         c=s.lines[0].len    // Set `c` to width of string
        ) % 4>2 ?
        b='|'+" "*c+"|" :    // Set `b` to top/bottom row adding
        b='-'*(c+2)          // `*` is repeat, c is from before
      ) + "\n" +
        s.sub(/^|$/gm,       // Add the following to beginning/end of each line
          q?'|':' '          // if H-ifying, add `|`s if I-ifying add spaces
        ) + "\n" + b         // Add bottom row, generated from before
    )
) -> g("|")     // Middle item is `|`
</code>```

This was a pain to golf but its 55 bytes shorter than original.

Title: The IHIH Pyramid

Body:
Cheddar, <s>186</s> <s>177</s> <s>165</s> <s>154</s> <s>148</s> 131 bytes

(n,b?,c?,q?,g=s->(n-=1)<0?s:g((q=(c=s.lines[0].len)%4>2?b='|'+" "*c+"|":b='-'*(c+2))+"\n"+s.sub(/^|$/gm,q?'|':' ')+"\n"+b))->g("|")

Uses recursion. Will add explanation once done golfing.

Try it online!

Explanation

This one is a bit complex too keep track off all the variables I'm using but I'll try to keep it simple:

(
 n,    // Input
 b?,   // Stores row to add to top/bottom
 c?,   // Width of string
 q?,   // false if I-ifying. true if not
 g=
   s->          // Main logic, s is generated string
    (n-=1)<0 ? s :   // Decrease input each iteration. Stop when 0
    g(               // Recurse with....
      (
        q= (         // Set `q` true if h-ifying. false if I-ifying
         c=s.lines[0].len    // Set `c` to width of string
        ) % 4>2 ?
        b='|'+" "*c+"|" :    // Set `b` to top/bottom row adding
        b='-'*(c+2)          // `*` is repeat, c is from before
      ) + "\n" +
        s.sub(/^|$/gm,       // Add the following to beginning/end of each line
          q?'|':' '          // if H-ifying, add `|`s if I-ifying add spaces
        ) + "\n" + b         // Add bottom row, generated from before
    )
) -> g("|")     // Middle item is `|`

This was a pain to golf but its 55 bytes shorter than original.


问:
Fast inverse square root
Inspired by http://meta.codegolf.stackexchange.com/questions/547/write-a-code-golf-problem-in-which-script-languages-are-at-a-major-disadvantage question on meta, I've decided to make a question which could be problematic for scripting languages.

The goal is to calculate fast inverse square root, just like it was done in Quake III Arena. You will get the floating point number as first argument after program name and you should implement it. Simply doing ** -0.5 is disallowed as it doesn't implement the algorithm.

Your program will be called like this. The 12.34 could be other value.

```<code>$ interpreter program 12.34 # for interpreted languages
$ ./a.out 12.34 # for compiled languages
</code>```

For comparison, this is original Quake III Arena implementation.

```<code>float Q_rsqrt( float number )
{
        long i;
        float x2, y;
        const float threehalfs = 1.5F;

        x2 = number * 0.5F;
        y = number;
        i = * ( long * ) &y;                       // evil floating point bit level hacking
        i = 0x5f3759df - ( i >> 1 );               // what the heck?
        y = * ( float * ) &i;
        y = y * ( threehalfs - ( x2 * y * y ) );   // 1st iteration
//      y = y * ( threehalfs - ( x2 * y * y ) );   // 2nd iteration, this can be removed

        return y;
}
</code>```

You have to do just one iteration because the second was commented out.

Winning condition: Shortest code.

答:
Perl, 89 85 chars

includes the necessary symbols for declaring and implementing a function

edit: standalone program. receives input parameter as command line argument

```<code>$_=unpack'f',pack'i',0x5f3759df-unpack('i',pack'f',$n=shift)/2;
print$_*1.5-$n/2*$_**3
</code>```

ContentLicense: CC BY-SA 3.0

Title: Fast inverse square root

Body:
Perl, 89 85 chars

includes the necessary symbols for declaring and implementing a function

edit: standalone program. receives input parameter as command line argument

$_=unpack'f',pack'i',0x5f3759df-unpack('i',pack'f',$n=shift)/2;
print$_*1.5-$n/2*$_**3


答:
Python, <s>165</s> <s>145</s> <s>133</s> 123 bytes

A recursive solution:

def i(e):
 d="|";a=e*2;x=d+" "*(a-1)+d
 if e<1:return d
 if e%2:d,x=[" ","-"*(a+1)]
 return[x]+[d+z+d for z in i(e-1)]+[x]
```

Called with print ("\n".join(i(int(sys.argv[1])))), where the parameter is the iteration number of the IHIH pyramid.

Thanks to @DJMcMayhem for saving 20 bytes. Taking the idea behind those suggestions further saved another 12 bytes. Thanks to @Maltysen for suggestions that trimmed some more bytes.

The function sets the delimiter d to "|" and the intervening spaces to " " (for odd-numbered iterations), deals with returning in the degenerate case, then resets the delimiter to " " and the intervening spaces to "-" for even-numbered iterations. The function returns a list of strings for each line of the IHIH, having embedded the result of a recursive call to the function in the right place within the list.

Title: The IHIH Pyramid

Body:
I find it fascinating how the letters "H" and "I" are very similar. "H" is a horizontal stroke surrounded by two vertical strokes; "I" is a vertical stroke surrounded by two horizontal strokes (depending on your font). I bet this could be nested... You know what that reminds me of? Fractals!!!

Let's define the "IHIH" pyramid as follows: The first iteration is this ASCII representation of the letter "I":

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

The next iteration has a vertical stroke on either side.

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

If you view the "I" in the middle as a single horizontal stroke, then this second iteration is basically an "H". The third iteration adds a horizontal stroke on the top and bottom

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

Again, if you view the "H" in the middle as a single vertical stroke, then this iteration is basically an "I". This pattern continues, alternating between "H"s and "I"s on every iteration. For reference, here are the first 6 iterations:

```<code>1:
---
 |
---

2:
|   |
|---|
| | |
|---|
|   |

3:
-------
 |   |
 |---|
 | | |
 |---|
 |   |
-------

4:
|       |
|-------|
| |   | |
| |---| |
| | | | |
| |---| |
| |   | |
|-------|
|       |

5:
-----------
 |       |
 |-------|
 | |   | |
 | |---| |
 | | | | |
 | |---| |
 | |   | |
 |-------|
 |       |
-----------

6:
|           |
|-----------|
| |       | |
| |-------| |
| | |   | | |
| | |---| | |
| | | | | | |
| | |---| | |
| | |   | | |
| |-------| |
| |       | |
|-----------|
|           |
</code>```

The Challenge:

Write a program or function that outputs the N'th iteration of the IHIH pyramid, and an optional trailing newline. Your input will be a single positive integer in whatever reasonable format you want. You do not have to handle invalid inputs, e.g. non-integers, numbers smaller than 1, etc. Your program must at the very least produce the right output for inputs up to 20. Since this is code-golf, standard loopholes are not allowed and the shortest answer in bytes wins!

Body:
Python, <s>165</s> <s>145</s> <s>133</s> 123 bytes

A recursive solution:

def i(e):
 d="|";a=e*2;x=d+" "*(a-1)+d
 if e<1:return d
 if e%2:d,x=[" ","-"*(a+1)]
 return[x]+[d+z+d for z in i(e-1)]+[x]

Called with print ("\n".join(i(int(sys.argv[1])))), where the parameter is the iteration number of the IHIH pyramid.

Thanks to @DJMcMayhem for saving 20 bytes. Taking the idea behind those suggestions further saved another 12 bytes. Thanks to @Maltysen for suggestions that trimmed some more bytes.

The function sets the delimiter d to "|" and the intervening spaces to " " (for odd-numbered iterations), deals with returning in the degenerate case, then resets the delimiter to " " and the intervening spaces to "-" for even-numbered iterations. The function returns a list of strings for each line of the IHIH, having embedded the result of a recursive call to the function in the right place within the list.


问:
Number Plate Golf: Recognition
See also: Parsing

Introduction

You're working on a government programming team, who have been programming the speed cameras. However, the group of people who have programmed the speed calculator have taken up too much space, so you have to make the number plate recognition software as small as possible.

Challenge

Given an image of a number plate, return the text on the plate.

Number plates

The following are all of the characters which your program must recognise:

ABCDEFG

H1JKLMN0

PQRSTUVW

XYZ01234

56789

Note

On British number plates, the characters for I (i) and 1 (one) are the same and the characters for O (o) and 0 (zero) are the same. For that reason, always assume characters are the numbers. I.e. the following number plate is 10 (one zero):

Examples

C0D3 GLF

B3T4 DCY

M1NUS 15

YET1CGN

Other rules

Internet access and OCR libraries and functions are disallowed.

The number plates will always look identical to the ones shown above. All number plates will be roughly same size (there will be some inaccuracies due to cropping method).

If you require lossless PNG versions of any number plates, I will supply them to you.

Scoring

The shortest program in bytes wins.

All number plates are screenshots of the search bar at this site

Title: Number Plate Golf: Recognition

Body:
C#, <s>1040</s> 1027 bytes

using System;using System.Drawing;class _{static Bitmap i;static bool b(int x,int y)=>i.GetPixel(x,y).GetBrightness()<.4;static char l(int x,int y){if(y<45)return b(x+5,145)?((b(x+30,100)||b(x+30,50))?(b(x+68,94)?(b(x+40,50)?'D':b(x+40,120)?(b(x+45,80)?'M':'N'):'H'):b(x,97)?(b(x+30,140)?'E':b(x+60,70)?(b(x+50,140)?'R':'P'):'F'):b(x+65,45)?(b(x+5,100)?'K':b(x+30,145)?'Z':'X'):'B'):b(x+30,140)?'L':'1'):b(x+30,55)?(b(x+60,70)?'7':'T'):b(x+2,100)?'U':b(x+30,70)?'W':b(x+15,100)?'V':'Y';if(y<70)return b(x+50,110)?(b(x+50,70)?(b(x+10,110)?(b(x+30,100)?(b(x+55,80)?'8':'6'):b(x+55,80)?'0':'G'):b(x+10,70)?(b(x+60,80)?'9':'S'):b(x+60,120)?'3':'2'):'G'):b(x+30,125)?'Q':'C';if(y>150)return'A';if(y>120)return'J';else return b(x+10,135)?'5':'4';}static void Main(string[]z){i=new Bitmap(Console.ReadLine());bool s=true;int w=int.MinValue;for(int x=100;x<800;++x){for(int y=40;y<160;++y)if(s){if(b(x,y)){if(w>50)Console.Write(' ');Console.Write(l(x,y));s=false;goto e;}}else if(b(x,y))goto e;if(!s){s=true;w=0;}else++w;e:continue;}}}

Ungolfed:

using System;
using System.Drawing;

class _
{
    static Bitmap bmp;
    static bool b(int x, int y) => bmp.GetPixel(x, y).GetBrightness() < .4;
    static char l(int x, int y)
    {
        if (y < 45)
            return b(x + 5, 145) ? ((b(x + 30, 100) || b(x + 30, 50)) ? (b(x + 68, 94) ? (b(x + 40, 50) ? 'D' : b(x + 40, 120) ? (b(x + 45, 80) ? 'M' : 'N') : 'H') : b(x, 97) ? (b(x + 30, 140) ? 'E' : b(x + 60, 70) ? (b(x + 50, 140) ? 'R' : 'P') : 'F') : b(x + 65, 45) ? (b(x + 5, 100) ? 'K' : b(x + 30, 145) ? 'Z' : 'X') : 'B') : b(x + 30, 140) ? 'L' : '1') : b(x + 30, 55) ? (b(x + 60, 70) ? '7' : 'T') : b(x + 2, 100) ? 'U' : b(x + 30, 70) ? 'W' : b(x + 15, 100) ? 'V' : 'Y';
        if (y < 70)
            return b(x + 50, 110) ? (b(x + 50, 70) ? (b(x + 10, 110) ? (b(x + 30, 100) ? (b(x + 55, 80) ? '8' : '6') : b(x + 55, 80) ? '0' : 'G') : b(x + 10, 70) ? (b(x + 60, 80) ? '9' : 'S') : b(x + 60, 120) ? '3' : '2') : 'G') : b(x + 30, 125) ? 'Q' : 'C';
        if (y > 150)
            return 'A';
        if (y > 120)
            return 'J';
        if (y > 95)
            return b(x + 10, 135) ? '5' : '4';
        return '-';
    }
    static void Main(string[] args)
    {
        bmp = new Bitmap(Console.ReadLine());
        bool state = true;
        int space = int.MinValue;
        for (int x = 100; x < 800; ++x)
        {
            for (int y = 40; y < 160; ++y)
                if (state)
                {
                    if (b(x, y))
                    {
                        if (space > 50)
                            Console.Write(' ');
                        Console.Write(l(x, y));
                        state = false;
                        goto bad;
                    }
                }
                else if (b(x, y))
                    goto bad;
            if (!state)
            {
                state = true;
                space = 0;
            }
            else
                ++space;
            bad:
            continue;
        }
    }
}

Basically I found some specific reference points to check yellow/black to determine the identity of each character.


答:
Matricks, <s>80</s> 62 bytes

An iterative solution (Recursion in Matricks is hard...)

Run with python matricks.py ihih.txt [[]] <input> --asciiprint

```
<s>k124;FiQ%2:v;b[m124:Q*2+3:1;];a{z:Q*2+1;};:b;v[m45:1:Q*2+3;];u{zQ*2+1:;};;:1:n;;</s>
k124;FiQ%2:v;b[m124:Q*2+3:2;];B1;:b;v[m45:2:Q*2+3;];V1;;:1:n;;
```

Explanation:

```<code>k124;                 # Set the matrix to '|'
F...:1:n;;            # Repeat input times, (Q is iteration variable)
  iQ%2:...:...;       # if statement, check if Q is odd or even
                      # Q is even,
    b;                # Make space to the left
    v[m45:2:Q*2+3;];  # Set the top 2 rows to '-'s
    V1;               # Rotate the matrix up 1 unit, moving the topmost row to the bottom
                      # Q is odd,
    v;                # Make space above
    b[m124:Q*2+3:2;]; # Set the 2 left columns to '|'s
    B1;               # Rotate the matrix left 1 unit, moving the leftmost row to the right
</code>```

Title: The IHIH Pyramid

Body:
Matricks, <s>80</s> 62 bytes

An iterative solution (Recursion in Matricks is hard...)

Run with python matricks.py ihih.txt [[]] <input> --asciiprint

<s>k124;FiQ%2:v;b[m124:Q*2+3:1;];a{z:Q*2+1;};:b;v[m45:1:Q*2+3;];u{zQ*2+1:;};;:1:n;;</s>
k124;FiQ%2:v;b[m124:Q*2+3:2;];B1;:b;v[m45:2:Q*2+3;];V1;;:1:n;;

Explanation:

k124;                 # Set the matrix to '|'
F...:1:n;;            # Repeat input times, (Q is iteration variable)
  iQ%2:...:...;       # if statement, check if Q is odd or even
                      # Q is even,
    b;                # Make space to the left
    v[m45:2:Q*2+3;];  # Set the top 2 rows to '-'s
    V1;               # Rotate the matrix up 1 unit, moving the topmost row to the bottom
                      # Q is odd,
    v;                # Make space above
    b[m124:Q*2+3:2;]; # Set the 2 left columns to '|'s
    B1;               # Rotate the matrix left 1 unit, moving the leftmost row to the right


答:
Pyth, <s>50</s> <s>40</s> <s>31</s> 25 bytes

```
<s>j@s.u,J+*\-K+2lheN+jR*2;eN*\-KjR"||"+*dK+J*dKQ]]\|</s>
<s>LXR"|-")CbjyW%Q2uy+K*\-+2lhG+jR*2;GKQ]\|</s>
<s>juCGQuC+K*@"-|"H+3yH+jR*2;GKQ\|</s>
j@CBujR*@"-|"H2CjR*2;GQ\|
```

Test suite.

Explanation

This is a recursive algorithm.

In each iteration, we perform three actions:

prepend and append a space to each line

transpose the array

prepend and append to each line either "-" or "|" depending on the number of iteration.

After the iterations, the odd-numbered outputs will be transposed. Therefore, we transpose them.

```<code>j@CBujR*@"-|"H2CjR*2;GQ\|   input: Q
j@CBujR*@"-|"H2CjR*2;GQ\|Q  implicit filling of arguments

    u                 Q\|   for Q times, starting with "|", G as current output,
                            H as number of iterations:

                jR*2;G          prepend and append a space to each line
                                (using each line as separator, join [" "," "])
               C                transpose
     jR*      2                 prepend and append the following to each line:
        @"-|"H                      the H-th element of the string "-|" (modular indexing)

 @CB                     Q  select the Q-th element from [output,
                            transposed output] (modular indexing)
j                           join by newlines
</code>```

Title: The IHIH Pyramid

Body:
Pyth, <s>50</s> <s>40</s> <s>31</s> 25 bytes

<s>j@s.u,J+*\-K+2lheN+jR*2;eN*\-KjR"||"+*dK+J*dKQ]]\|</s>
<s>LXR"|-")CbjyW%Q2uy+K*\-+2lhG+jR*2;GKQ]\|</s>
<s>juCGQuC+K*@"-|"H+3yH+jR*2;GKQ\|</s>
j@CBujR*@"-|"H2CjR*2;GQ\|

Test suite.

Explanation

This is a recursive algorithm.

In each iteration, we perform three actions:

prepend and append a space to each line

transpose the array

prepend and append to each line either "-" or "|" depending on the number of iteration.

After the iterations, the odd-numbered outputs will be transposed. Therefore, we transpose them.

j@CBujR*@"-|"H2CjR*2;GQ\|   input: Q
j@CBujR*@"-|"H2CjR*2;GQ\|Q  implicit filling of arguments

    u                 Q\|   for Q times, starting with "|", G as current output,
                            H as number of iterations:

                jR*2;G          prepend and append a space to each line
                                (using each line as separator, join [" "," "])
               C                transpose
     jR*      2                 prepend and append the following to each line:
        @"-|"H                      the H-th element of the string "-|" (modular indexing)

 @CB                     Q  select the Q-th element from [output,
                            transposed output] (modular indexing)
j                           join by newlines


问:
Deciphering XKCD colors
Randall Munroe (author of XKCD) held a survey to give names to colors. The main outcome is a list of names for the 954 most common RGB monitor colors.

For ease of programming, here is the list in plain text: http://xkcd.com/color/rgb.txt. Beware, the first line is not data, but contains the license.

Write a program or function that takes a valid color name from above list as input and outputs the associated RGB color code. Your program does not have to handle invalid inputs in any defined manner.

Standard loopholes apply. Additionally, your answer must not use pre-defined (built-in or external) color code <-> color name maps. (This includes the linked list.) Shortest code in bytes wins. If you read from a file, the file's byte count must be included.

Examples:

```<code>dark peach -> #de7e5d
robin's egg blue -> #98eff9
pink/purple -> #ef1de7
</code>```

答:
Java, 4649 bytes

Java code : 497 bytes, data file : 4152 bytes

The file can be found here

```<code>import java.io.*;import java.util.*;public class A{static void main(String[] a) throws Exception{byte[]d=new byte[4864];new FileInputStream("d").read(d);long h=a[0].hashCode(),k,l,r=0;h=(h&1023)+(h&14336)/2+(h&491520)/4;BitSet b=BitSet.valueOf(d);for(int i=0,j;i<33216;i+=35){for(l=0,j=16;j>=0;){l<<=1;if(b.get(i+j--))l|=1;}r+=b.get(i+33)?1:0;r+=b.get(i+34)?2:0;if(l==h){for(k=0,j=15;j>=0;){k<<=1;if(b.get(i+17+j--))k|=1;}System.out.println("#"+String.format("%06X",(k<<8)+r).toLowerCase());}}}}
</code>```

ungolfed:

```<code>import java.io.*;
import java.util.*;

public class A{
    public static void main(String[] a) throws Exception{
        byte[]d=new byte[4864];
        new FileInputStream("d").read(d);
        // compute word hashcode
        long h=a[0].hashCode(),k,l,r=0;
        h=(h&1023)+(h&14336)/2+(h&491520)/4;
        BitSet b=BitSet.valueOf(d);
        // browse data file
        for(int i=0,j;i<33216;i+=35){
            for(l=0,j=16;j>=0;){
                l<<=1;
                if(b.get(i+j--))l|=1;
            }
            // compute color blue component
            r+=b.get(i+33)?1:0;
            r+=b.get(i+34)?2:0;
            // do hashcode match ?
            if(l==h){
                // compute color value
                for(k=0,j=15;j>=0;){
                    k<<=1;
                    if(b.get(i+17+j--))k|=1;
                }
                System.out.println("#"+String.format("%06X",(k<<8)+r).toLowerCase());
            }
        }
    }
}
</code>```

The program uses an improved version of Java hashcode that uses only 17 bits:

```<code>    long hash = s.hashCode();
    long hash2 = hash & 0b1111111111;
    hash2 += (hash & 0b11100000000000) / 2;
    hash2 += (hash & 0b1111000000000000000) / 4;
</code>```

Colors are sorted by blue component increasing. They are stored on 18 bits: 8 for red, 8 for green and 2 for delta blue.

Total file size: 949 colors * (18 + 17) = 33 215 = 4152 bytes

Title: Deciphering XKCD colors

Body:
Java, 4649 bytes

Java code : 497 bytes, data file : 4152 bytes

The file can be found here

import java.io.*;import java.util.*;public class A{static void main(String[] a) throws Exception{byte[]d=new byte[4864];new FileInputStream("d").read(d);long h=a[0].hashCode(),k,l,r=0;h=(h&1023)+(h&14336)/2+(h&491520)/4;BitSet b=BitSet.valueOf(d);for(int i=0,j;i<33216;i+=35){for(l=0,j=16;j>=0;){l<<=1;if(b.get(i+j--))l|=1;}r+=b.get(i+33)?1:0;r+=b.get(i+34)?2:0;if(l==h){for(k=0,j=15;j>=0;){k<<=1;if(b.get(i+17+j--))k|=1;}System.out.println("#"+String.format("%06X",(k<<8)+r).toLowerCase());}}}}

ungolfed:

import java.io.*;
import java.util.*;

public class A{
    public static void main(String[] a) throws Exception{
        byte[]d=new byte[4864];
        new FileInputStream("d").read(d);
        // compute word hashcode
        long h=a[0].hashCode(),k,l,r=0;
        h=(h&1023)+(h&14336)/2+(h&491520)/4;
        BitSet b=BitSet.valueOf(d);
        // browse data file
        for(int i=0,j;i<33216;i+=35){
            for(l=0,j=16;j>=0;){
                l<<=1;
                if(b.get(i+j--))l|=1;
            }
            // compute color blue component
            r+=b.get(i+33)?1:0;
            r+=b.get(i+34)?2:0;
            // do hashcode match ?
            if(l==h){
                // compute color value
                for(k=0,j=15;j>=0;){
                    k<<=1;
                    if(b.get(i+17+j--))k|=1;
                }
                System.out.println("#"+String.format("%06X",(k<<8)+r).toLowerCase());
            }
        }
    }
}

The program uses an improved version of Java hashcode that uses only 17 bits:

    long hash = s.hashCode();
    long hash2 = hash & 0b1111111111;
    hash2 += (hash & 0b11100000000000) / 2;
    hash2 += (hash & 0b1111000000000000000) / 4;

Colors are sorted by blue component increasing. They are stored on 18 bits: 8 for red, 8 for green and 2 for delta blue.

Total file size: 949 colors * (18 + 17) = 33 215 = 4152 bytes


问:
Wave-Particle Duality Laterally Programmatically
Write a program or function that takes in a nonempty single-line string. The string will either be zero or more spaces followed by one period (a particle), such as . or          ., or the string will be a sequence of one or more alternating forward and back slashes (a wave) that could start with either one, such as \ or /\/ or \/\/\/\/\/\/.

In either case, propagate the particle/wave to the right by one unit.

Specifically, in the particle case, insert a space before the ., moving it one place to the right, then output the resulting string. For example:

. →  .

 . →   .

  . →    .

   . →     .

    . →      .

     . →       .

      . →        .

       . →         .

In the wave case, append either / or \ appropriately so the wave keeps alternating and it's length increases by one, then output the resulting string. For example:

/ → /\

\ → \/

/\ → /\/

\/ → \/\

/\/ → /\/\

\/\ → \/\/

/\/\ → /\/\/

\/\/ → \/\/\

In either case, the output may not have trailing spaces but an optional trailing newline is allowed.

The shortest code in bytes wins.

答:
ARM machine code on Linux, 50 bytes

Hex dump:

```<code>b580 1e41 f811 2f01 2a00 d1fb 3901 780b 1a0a 4601 2001 2704 df00 2000 a103 2202 f013 0303 2b03 4159 df00 bd80 2e202f5c 5c2f
</code>```

First post here, hope I'm doing this right. This is 32-bit ARM assembly, specifically Thumb-2. The input string is a NUL-terminated string taken in through r0, the output is printed to the stdout. In C-syntax, the prototype for the function would be void func_name(char* string). It is AAPCS (ARM calling convention) complaint, if it weren't then 2 bytes could be shaved off.

Here's the equivalent assembly, with comments explaining what's happening:

```<code>    @Input: r0 is char* (the string)
    @Output: Modified string to console
    push {r7,lr} @Save r7 and the link register
    subs r1,r0,#1 @Make a copy of the char*, subtracting because we're
    @going to pre-increment.
    loop: @This loop is a little strlen routine
            ldrb r2,[r1,#1]! @In C-syntax, r2=*++r1;
            cmp r2,#0
            bne loop
    @Now r1 points to the null character that terminates the string
    subs r1,r1,#1 @Make r1 point to the last character
    ldrb r3,[r1] @Load the last character into r3
    subs r2,r1,r0 @r2=length(r0) - 1;
    mov  r1,r0 @r0 holds the original char*
    movs r0,#1 @1 is the file descriptor for stdout
    movs r7,#4 @4 is write
    swi #0

    @Now all the characters from the initial string have been printed,
    @except for the last one, which is currently in r3.

    movs r0,#1 @1 is stdout, have to reload this since the system call
    @returns in r0.
    adr r1,msg @Load msg into r1 (the pointer to the string)
    movs r2,#2 @We're going to print two more characters.

    @Now the bit magic. The ascii codes for '\', '.', and '/' map onto
    @0, 2, and 3 when bitwise anded with 3 (0b11).
    @This will be the offset into our string. However, since we must print
    @2 characters, we need our offsets to be 0, 2, and 4.
    @Therefore, we only set the carry if our value is >=3, then add with
    @carry (adcs). Thus we get the correct offset into the string msg.
    ands r3,r3,#3
    cmp r3,#3 @Sets carry if r3>=3
    adcs r1,r1,r3 @Add the offset to r1
    swi #0 @Make the system call
    pop {r7,pc} @Return and restore r7
msg:
    .ascii "\\/ ./\\" @The three different sequences of 2 characters that
    @can go at the end.
</code>```

Body:
ARM machine code on Linux, 50 bytes

Hex dump:

b580 1e41 f811 2f01 2a00 d1fb 3901 780b 1a0a 4601 2001 2704 df00 2000 a103 2202 f013 0303 2b03 4159 df00 bd80 2e202f5c 5c2f

First post here, hope I'm doing this right. This is 32-bit ARM assembly, specifically Thumb-2. The input string is a NUL-terminated string taken in through r0, the output is printed to the stdout. In C-syntax, the prototype for the function would be void func_name(char* string). It is AAPCS (ARM calling convention) complaint, if it weren't then 2 bytes could be shaved off.

Here's the equivalent assembly, with comments explaining what's happening:

    @Input: r0 is char* (the string)
    @Output: Modified string to console
    push {r7,lr} @Save r7 and the link register
    subs r1,r0,#1 @Make a copy of the char*, subtracting because we're
    @going to pre-increment.
    loop: @This loop is a little strlen routine
            ldrb r2,[r1,#1]! @In C-syntax, r2=*++r1;
            cmp r2,#0
            bne loop
    @Now r1 points to the null character that terminates the string
    subs r1,r1,#1 @Make r1 point to the last character
    ldrb r3,[r1] @Load the last character into r3
    subs r2,r1,r0 @r2=length(r0) - 1;
    mov  r1,r0 @r0 holds the original char*
    movs r0,#1 @1 is the file descriptor for stdout
    movs r7,#4 @4 is write
    swi #0

    @Now all the characters from the initial string have been printed,
    @except for the last one, which is currently in r3.

    movs r0,#1 @1 is stdout, have to reload this since the system call
    @returns in r0.
    adr r1,msg @Load msg into r1 (the pointer to the string)
    movs r2,#2 @We're going to print two more characters.

    @Now the bit magic. The ascii codes for '\', '.', and '/' map onto
    @0, 2, and 3 when bitwise anded with 3 (0b11).
    @This will be the offset into our string. However, since we must print
    @2 characters, we need our offsets to be 0, 2, and 4.
    @Therefore, we only set the carry if our value is >=3, then add with
    @carry (adcs). Thus we get the correct offset into the string msg.
    ands r3,r3,#3
    cmp r3,#3 @Sets carry if r3>=3
    adcs r1,r1,r3 @Add the offset to r1
    swi #0 @Make the system call
    pop {r7,pc} @Return and restore r7
msg:
    .ascii "\\/ ./\\" @The three different sequences of 2 characters that
    @can go at the end.


答:
Python 3, 4927

182 code + 4745 data file

```<code>from hashlib import*
def f(s):
 k,b=md5((67*s).encode('ascii')).digest()[5:7],open('X','rb').read()
 for j in range(0,4746,5):
  if b[j:j+2]==k:print(('{:2x}'*3).format(*b[j+2:j+5]))
</code>```

Theory of Operation:

md5((67*s).encode('ascii')).digest()[5:7] is a perfect hash from the color names to a 2-byte value.  The binary data file is simply a list of 5-byte chunks--2 byte hash and 3 byte color.  The code hashes the input color name and searches through the data to find a match.

The code to generate the binary file:

```<code>ba = bytearray()
with open('./rgb.txt','rt') as f:
    next(f)  # skip header line
    for name,code in (line.strip().split('\t#') for line in f):
        key = md5((67*name).encode('ascii')).digest()[5:7]
        ba.extend(key+bytes.fromhex(code))

with open('X', 'wb') as f:
    f.write(ba)
</code>```

Here's the code I used to find a perfect hash.  Nothing fancy, just three nested loops: number of time to repeat the name (e.g., 'blue', 'blueblue', ...); the available hash algorithms; and the offsets in the hashes.  It prints out combinations for which there are no collisions.

```<code>for i in range(1,100):
    for hashname in hashlib.algorithms_guaranteed:
        hashes = [hashlib.new(hashname,(name*i).encode('ascii')).digest() for name in names]
        for j in range(h.digest_size - 2):
            if len(set(x[j:j+2] for x in hashes)) == 949:
                print(i, hashname, j)
                break
    print(i)
</code>```

Title: Deciphering XKCD colors

Body:
Randall Munroe (author of XKCD) held a survey to give names to colors. The main outcome is a list of names for the 954 most common RGB monitor colors.

For ease of programming, here is the list in plain text: http://xkcd.com/color/rgb.txt. Beware, the first line is not data, but contains the license.

Write a program or function that takes a valid color name from above list as input and outputs the associated RGB color code. Your program does not have to handle invalid inputs in any defined manner.

Standard loopholes apply. Additionally, your answer must not use pre-defined (built-in or external) color code <-> color name maps. (This includes the linked list.) Shortest code in bytes wins. If you read from a file, the file's byte count must be included.

Examples:

```<code>dark peach -> #de7e5d
robin's egg blue -> #98eff9
pink/purple -> #ef1de7
</code>```

Body:
Python 3, 4927

182 code + 4745 data file

from hashlib import*
def f(s):
 k,b=md5((67*s).encode('ascii')).digest()[5:7],open('X','rb').read()
 for j in range(0,4746,5):
  if b[j:j+2]==k:print(('{:2x}'*3).format(*b[j+2:j+5]))

Theory of Operation:

md5((67*s).encode('ascii')).digest()[5:7] is a perfect hash from the color names to a 2-byte value.  The binary data file is simply a list of 5-byte chunks--2 byte hash and 3 byte color.  The code hashes the input color name and searches through the data to find a match.

The code to generate the binary file:

ba = bytearray()
with open('./rgb.txt','rt') as f:
    next(f)  # skip header line
    for name,code in (line.strip().split('\t#') for line in f):
        key = md5((67*name).encode('ascii')).digest()[5:7]
        ba.extend(key+bytes.fromhex(code))

with open('X', 'wb') as f:
    f.write(ba)

Here's the code I used to find a perfect hash.  Nothing fancy, just three nested loops: number of time to repeat the name (e.g., 'blue', 'blueblue', ...); the available hash algorithms; and the offsets in the hashes.  It prints out combinations for which there are no collisions.

for i in range(1,100):
    for hashname in hashlib.algorithms_guaranteed:
        hashes = [hashlib.new(hashname,(name*i).encode('ascii')).digest() for name in names]
        for j in range(h.digest_size - 2):
            if len(set(x[j:j+2] for x in hashes)) == 949:
                print(i, hashname, j)
                break
    print(i)


Title: The IHIH Pyramid

Body:
Mathematica, <s>158</s> 164 bytes

f[n_]:=Print/@StringJoin/@Map[{{{"|","|", },{ , , }},{{"|", ,"-"},{ ,"-","-"}}}[[##]]&@@#&,Table[{1+i~Mod~2, 1+j~Mod~2, 2+Sign[Abs[i]-Abs[j]]}, {i,-n,n}, {j,-n,n}],{2}]

Mathematically calculates the correct symbol at the coordinates (i,j), where both run from -n to n. Human formatted:

f[n_]:=Print/@
 StringJoin/@
  Map[
   {{{"|","|", },{ , , }},{{"|", ,"-"},{ ,"-","-"}}[[##]]&@@#&,
   Table[{1+i~Mod~2,1+j~Mod~2,2+Sign[Abs[i]-Abs[j]]},{i,-n,n},{j,-n,n}],
   {2}]


答:
MATLAB, 168 163 bytes

This is probably not the cleverest way to do it: Expanding a string on all sides in n steps:

```<code>function s=g(n);s='|';for m=1:n;if mod(m,2);a=45;b=a;c=0;else a='|';b=0;c=a;end;s=[a repmat(b,1,2*m-1);repmat(c,2*m-1,1) s];s(:,end+1)=s(:,1);s(end+1,:)=s(1,:);end
</code>```

Usage: Save as g.m (do I have to add that to the byte count?) and call e.g. g(15).

Ungolfed:

```<code>function s=g(n)

% // Initialize s
s = '|';

for m=1:n
   % // Decide if odd or even number and which symbol to add where
   if mod(m,2)
      a=45;b=a;c=0; % // char(45) is '-' and char(0) is ' ' (thx to Luis Mendo)
   else
      a='|';b=0;c=a;
   end
      % // Add symbols at top and left to s
      s = [a repmat(b,1,2*m-1);repmat(c,2*m-1,1) s];
      % // Add symbols at right and bottom to s
      s(:,end+1) = s(:,1);
      s(end+1,:) = s(1,:);
end
</code>```

Title: The IHIH Pyramid

Body:
MATLAB, 168 163 bytes

This is probably not the cleverest way to do it: Expanding a string on all sides in n steps:

function s=g(n);s='|';for m=1:n;if mod(m,2);a=45;b=a;c=0;else a='|';b=0;c=a;end;s=[a repmat(b,1,2*m-1);repmat(c,2*m-1,1) s];s(:,end+1)=s(:,1);s(end+1,:)=s(1,:);end

Usage: Save as g.m (do I have to add that to the byte count?) and call e.g. g(15).

Ungolfed:

function s=g(n)

% // Initialize s
s = '|';

for m=1:n
   % // Decide if odd or even number and which symbol to add where
   if mod(m,2)
      a=45;b=a;c=0; % // char(45) is '-' and char(0) is ' ' (thx to Luis Mendo)
   else
      a='|';b=0;c=a;
   end
      % // Add symbols at top and left to s
      s = [a repmat(b,1,2*m-1);repmat(c,2*m-1,1) s];
      % // Add symbols at right and bottom to s
      s(:,end+1) = s(:,1);
      s(end+1,:) = s(1,:);
end


问:
Print NxN spiral of ascending numbers
The numbers should be printed with leading zeroes in a field with length = (number of digits of N^2).

Input (N):

```<code>4
</code>```

Output:

```<code>01 12 11 10
02 13 16 09
03 14 15 08
04 05 06 07
</code>```

I am interested in the algorithm and the cleanliness of the implementation.
So, the white space does not count and the upper limit for N is 42.

答:
C#, 380-ish golfed

I didn't bother pasting in the golfed version as I was pretty confident this wasn't going to break any records. But I wanted to give it a shot thinking about it a bit differently. Rather than write out each line or position as I come to it, I'm moving the cursor into position, writing out the starting center number, and spiraling out from there (which illustrated an interesting pattern of positions-to-move per direction change).

There's a fair amount of character space wasted getting the console buffer to accept the larger values as well calculating the position for the upper left corner (which I'm sure can be improved).

At any rate, it was an interesting exercise.

```<code>    static void Main(string[] p)
    {
        int squareSize = 4;
        Console.BufferHeight = 300;
        Console.BufferWidth = 300;

        int maxTravel = 0;
        int currentTravel = 0;
        int travelCounter = 0;
        var a = squareSize % 2 == 0;
        int direction = a ? 2 : 0;
        int pad = squareSize * squareSize;
        int padLength = (pad + "").Length;

        int y = a ? (squareSize / 2) - 1 : (squareSize - 1) / 2;
        int x = a ? y + 1 : y;
        x = x + (x * padLength);

        for (int i = pad; i > 0; i--)
        {
            Console.SetCursorPosition(x, y);
            Console.Write((i + "").PadLeft(padLength, '0') + " ");

            switch (direction)
            {
                case 0:
                    y--;
                    break;

                case 1:
                    x += padLength + 1;
                    break;

                case 2:
                    y++;
                    break;

                case 3:
                    x -= padLength + 1;
                    break;
            }

            if (++currentTravel > maxTravel)
            {
                currentTravel = 0;
                direction = ++direction % 4;

                if (++travelCounter == 2)
                {
                    travelCounter = 0;
                    maxTravel++;
                }
            }

        }
    }
</code>```

Title: Print NxN spiral of ascending numbers

Body:
C#, 380-ish golfed

I didn't bother pasting in the golfed version as I was pretty confident this wasn't going to break any records. But I wanted to give it a shot thinking about it a bit differently. Rather than write out each line or position as I come to it, I'm moving the cursor into position, writing out the starting center number, and spiraling out from there (which illustrated an interesting pattern of positions-to-move per direction change).

There's a fair amount of character space wasted getting the console buffer to accept the larger values as well calculating the position for the upper left corner (which I'm sure can be improved).

At any rate, it was an interesting exercise.

    static void Main(string[] p)
    {
        int squareSize = 4;
        Console.BufferHeight = 300;
        Console.BufferWidth = 300;

        int maxTravel = 0;
        int currentTravel = 0;
        int travelCounter = 0;
        var a = squareSize % 2 == 0;
        int direction = a ? 2 : 0;
        int pad = squareSize * squareSize;
        int padLength = (pad + "").Length;

        int y = a ? (squareSize / 2) - 1 : (squareSize - 1) / 2;
        int x = a ? y + 1 : y;
        x = x + (x * padLength);

        for (int i = pad; i > 0; i--)
        {
            Console.SetCursorPosition(x, y);
            Console.Write((i + "").PadLeft(padLength, '0') + " ");

            switch (direction)
            {
                case 0:
                    y--;
                    break;

                case 1:
                    x += padLength + 1;
                    break;

                case 2:
                    y++;
                    break;

                case 3:
                    x -= padLength + 1;
                    break;
            }

            if (++currentTravel > maxTravel)
            {
                currentTravel = 0;
                direction = ++direction % 4;

                if (++travelCounter == 2)
                {
                    travelCounter = 0;
                    maxTravel++;
                }
            }

        }
    }

ContentLicense: CC BY-SA 2.5


问:
Reinvent the For loop
For loops are used extensively in many languages, but what would you do if no languages supported them?

Create a way to execute a basic for loop without using any repetition structures (for, foreach, while, do, etc).

The basic for loop that you need to replicate is set up like this

```<code>for(i=0;i<1000;i++)
</code>```

You must be able to replicate this without using repetition structures.  It must also execute code in your language that would be in the body of the loop.  Any form of eval is allowed, though it may not execute the for loop on its own.

You can test your code by having it print i with a space 100 times, add this test case to the end of your answer to verify your code with others.

There are no restrictions on what exactly it has to be, all it needs to do is replicate the for loop.

Winner will be decided based on upvotes at the time that it is chosen.

答:
Javascript (44 chars.):

Another rather pointless option, but then who said golf had to have a point :) Plus I gained something new... I never realised you could get away with i+++

```<code>eval(Array((i=0)+1e3).join('i+++" "+')+'i')
</code>```

I also learned that running .map and .forEach on an initialised undefined filled Array does nothing... at least in FireFox anyway

```<code>Array(1000).forEach(function(){ /* this code is never executed :( */ })
</code>```

Title: Reinvent the For loop

Body:
Javascript (44 chars.):

Another rather pointless option, but then who said golf had to have a point :) Plus I gained something new... I never realised you could get away with i+++

eval(Array((i=0)+1e3).join('i+++" "+')+'i')

I also learned that running .map and .forEach on an initialised undefined filled Array does nothing... at least in FireFox anyway

Array(1000).forEach(function(){ /* this code is never executed :( */ })


答:
Dyalog APL, <s>52</s> 43 bytes

{v=⊃⍵:h⍪⍨h⍪s,⍵,s⋄v,⍨v,s⍪⍵⍪s}⍣⎕⍪⊃v h s←'|- '
```

v h s←'|- ' assigns the three characters to three names (vertical, horizontal, space)

⊃ the first one, i.e. |

⍪ make into 1×1 table

{...}⍣⎕ get input and apply the braced function that many times

 v=⊃⍵: if the top-left character of the argument is a vertical, then:

  h⍪⍨ horizontals below

  h⍪ horizontals above

  s, spaces to the left of

  ⍵,s the argument with spaces to the right

 ⋄ else:

  v,⍨ verticals to the right of

  v, verticals to the left of

  s⍪ spaces above

  ⍵⍪s the argument with spaces below

TryAPL online!

Title: The IHIH Pyramid

Body:
Dyalog APL, <s>52</s> 43 bytes

{v=⊃⍵:h⍪⍨h⍪s,⍵,s⋄v,⍨v,s⍪⍵⍪s}⍣⎕⍪⊃v h s←'|- '

v h s←'|- ' assigns the three characters to three names (vertical, horizontal, space)

⊃ the first one, i.e. |

⍪ make into 1×1 table

{...}⍣⎕ get input and apply the braced function that many times

 v=⊃⍵: if the top-left character of the argument is a vertical, then:

  h⍪⍨ horizontals below

  h⍪ horizontals above

  s, spaces to the left of

  ⍵,s the argument with spaces to the right

 ⋄ else:

  v,⍨ verticals to the right of

  v, verticals to the left of

  s⍪ spaces above

  ⍵⍪s the argument with spaces below

TryAPL online!


问:
Construct the Identity Matrix
The challenge is very simple. Given an integer input n, output the n x n identity matrix. The identity matrix is one that has 1s spanning from the top left down to the bottom right. You will write a program or a function that will return or output the identity matrix you constructed. Your output may be a 2D array, or numbers separated by spaces/tabs and newlines.

Example input and output

```<code>1: [[1]]
2: [[1, 0], [0, 1]]
3: [[1, 0, 0], [0, 1, 0], [0, 0, 1]]
4: [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]]
5: [[1, 0, 0, 0, 0], [0, 1, 0, 0, 0], [0, 0, 1, 0, 0], [0, 0, 0, 1, 0], [0, 0, 0, 0, 1]]

1
===
1

2
===
1 0
0 1

3
===
1 0 0
0 1 0
0 0 1

etc.
</code>```

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

答:
Jellyfish, 12 bytes

```<code>P`N(Rri
   -
</code>```

Try it online!
This entry is non-competing.

Explanation

i is input, and r computes the range from 0 to input-1.

The operator ( is a left hook. On inputs - and R, it applies R (rotate) to the range and its negated version. This gives the i×i matrix whose rows are the ranges ri, rotated k steps to the right for each row k.

`N computes the logical negation of each entry: 0 goes to 1 and everything else to 0. Since the 0s are on the diagonal, this gives the identity matrix.

P prints the matrix.

Title: Construct the Identity Matrix

Body:
Jellyfish, 12 bytes

P`N(Rri
   -

Try it online!
This entry is non-competing.

Explanation

i is input, and r computes the range from 0 to input-1.

The operator ( is a left hook. On inputs - and R, it applies R (rotate) to the range and its negated version. This gives the i×i matrix whose rows are the ranges ri, rotated k steps to the right for each row k.

`N computes the logical negation of each entry: 0 goes to 1 and everything else to 0. Since the 0s are on the diagonal, this gives the identity matrix.

P prints the matrix.


问:
Output the nth rational number according to the Stern-Brocot sequence
The Stern-Brocot sequence is a Fibonnaci-like sequence which can be constructed as follows:

Initialise the sequence with s(1) = s(2) = 1

Set counter n = 1

Append s(n) + s(n+1) to the sequence

Append s(n+1) to the sequence

Increment n, return to step 3

This is equivalent to:

Amongst other properties, the Stern-Brocot sequence can be used to generate every possible positive rational number. Every rational number will be generated exactly once, and it will always appear in its simplest terms; for example, 1/3 is the 4th rational number in the sequence, but the equivalent numbers 2/6, 3/9 etc won't appear at all.

We can define the nth rational number as r(n) = s(n) / s(n+1), where s(n) is the nth Stern-Brocot number, as described above.

Your challenge is to write a program or function which will output the nth rational number generated using the Stern-Brocot sequence.

The algorithms described above are 1-indexed; if your entry is 0-indexed, please state in your answer

The algorithms described are for illustrative purposes only, the output can be derived in any way you like (other than hard-coding)

Input can be via STDIN, function parameters, or any other reasonable input mechanism

Ouptut can be to STDOUT, console, function return value, or any other reasonable output stream

Output must be as a string in the form a/b, where a and b are the relevant entries in the Stern-Brocot sequence. Evaluating the fraction before output is not permissable. For example, for input 12, output should be 2/5, not 0.4.

Standard loopholes are disallowed

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

Test cases

The test cases here are 1-indexed.

```<code>n    r(n)
--  ------
1    1/1
2    1/2
3    2/1
4    1/3
5    3/2
6    2/3
7    3/1
8    1/4
9    4/3
10   3/5
11   5/2
12   2/5
13   5/3
14   3/4
15   4/1
16   1/5
17   5/4
18   4/7
19   7/3
20   3/8
50   7/12
100  7/19
1000 11/39
</code>```

OEIS entry: A002487

Excellent Numberphile video discussing the sequence: Infinite Fractions

答:
><>, 34+2 = 36 bytes

After seeing Peter Taylor's excellent answer, I re-wrote my test answer (which was an embarrassing 82 bytes, using very clumsy recursion).

```<code>&01\$n"/"on;
&?!\:@}:{:@+@%2*-&1-:
</code>```

It expects the input to be present on the stack, so +2 bytes for the -v flag. Try it online!

Body:
><>, 34+2 = 36 bytes

After seeing Peter Taylor's excellent answer, I re-wrote my test answer (which was an embarrassing 82 bytes, using very clumsy recursion).

&01\$n"/"on;
&?!\:@}:{:@+@%2*-&1-:

It expects the input to be present on the stack, so +2 bytes for the -v flag. Try it online!


答:
JavaScript (ES6), <s>92</s> 90 bytes

f=
(n,[h,c,v]=n&1?`-- `:` ||`)=>n?(c+=h.repeat(n+n-1)+c)+`
${f(n-1).replace(/^|$/gm,v)}
`+c:v
;```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type=number min=0 oninput=o.textContent=f(+this.value)><pre id=o></code>```

Recursive solution works by taking the previous iteration, adding the v character to the sides, then adding the c character to the corners and the h character along the top and bottom. The set of characters simply alternates each iteration. Edit: Saved 2 bytes by returning v when n=0.

Title: The IHIH Pyramid

Body:
JavaScript (ES6), <s>92</s> 90 bytes

f=
(n,[h,c,v]=n&1?`-- `:` ||`)=>n?(c+=h.repeat(n+n-1)+c)+`
${f(n-1).replace(/^|$/gm,v)}
`+c:v
;

<input type=number min=0 oninput=o.textContent=f(+this.value)><pre id=o>

Recursive solution works by taking the previous iteration, adding the v character to the sides, then adding the c character to the corners and the h character along the top and bottom. The set of characters simply alternates each iteration. Edit: Saved 2 bytes by returning v when n=0.


答:
Mata, 4 bytes

```<code>I(3)
</code>```

Output

```<code>[symmetric]
       1   2   3
    +-------------+
  1 |  1          |
  2 |  0   1      |
  3 |  0   0   1  |
    +-------------+
</code>```

Mata is the matrix programming language available within the Stata statistical package. I(n) creates an identity matrix of size n*n

Title: Construct the Identity Matrix

Body:
The challenge is very simple. Given an integer input n, output the n x n identity matrix. The identity matrix is one that has 1s spanning from the top left down to the bottom right. You will write a program or a function that will return or output the identity matrix you constructed. Your output may be a 2D array, or numbers separated by spaces/tabs and newlines.

Example input and output

```<code>1: [[1]]
2: [[1, 0], [0, 1]]
3: [[1, 0, 0], [0, 1, 0], [0, 0, 1]]
4: [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]]
5: [[1, 0, 0, 0, 0], [0, 1, 0, 0, 0], [0, 0, 1, 0, 0], [0, 0, 0, 1, 0], [0, 0, 0, 0, 1]]

1
===
1

2
===
1 0
0 1

3
===
1 0 0
0 1 0
0 0 1

etc.
</code>```

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

Body:
Mata, 4 bytes

I(3)

Output

[symmetric]
       1   2   3
    +-------------+
  1 |  1          |
  2 |  0   1      |
  3 |  0   0   1  |
    +-------------+

Mata is the matrix programming language available within the Stata statistical package. I(n) creates an identity matrix of size n*n


问:
Calculate the difficulty of a Code Golf question

Briefing

The difficulty of a Code Golf question can be calculated as such:

$$\text{clamp} \left( \left\lceil \left( \frac v a \div 700 \right) \times 10 \right\rceil, 0, 10 \right)$$

Where \$v\$ is the number of views a question has

and \$a\$ is the number of answers a question has

and \$⌈x⌉\$ is the ceiling operator.

Also:

$$\text{clamp}(x, min, max) = \begin{cases}
min & x < min \\
x   & min \le x \le max \\
max & max < x
\end{cases}$$

This question's current difficulty: ***

Task

Write a program that will take two integers (v and a) and output the difficulty in asterisks (*).

The input can be in the form of an array, a separated string or as separate function arguments

Test Data

```<code>Views   Answers Difficulty  Program Output
163     2       2           **
548     22      1           *
1452    24      1           *
1713    37      1           *
4162    32      2           **
3067    15      3           ***
22421   19      10          **********
</code>```

Example with pseudocode

```<code>v: 1713
a: 37
out = clamp(ceil(((v/a)/700)*10), 0, 10); // evaluates to 1
//program will output '*'
</code>```

The shortest code in bytes wins! Trailing/ leading spaces are allowed.

答:
Ruby, 47 35 bytes

```<code>f=->(v,a){'*'*((v/=a*70)<9?v+1:10)}
</code>```

Called with f.call(v,a)

Saved 12 bytes thanks to user3334690, now the function implicitly returns the result.

ContentLicense: CC BY-SA 4.0

Body:
Ruby, 47 35 bytes

f=->(v,a){'*'*((v/=a*70)<9?v+1:10)}

Called with f.call(v,a)

Saved 12 bytes thanks to user3334690, now the function implicitly returns the result.


答:
Brachylog, 84 bytes

```<code>,[[["|"]]:?:1]i:1:zi:ca~@nw
hh~m["-|":B]:ramggL," "ggS,?:Sz:ca:Srz:caz:Lz:ca:Lrz:ca.
</code>```

Try it online!

A port of my answer in Pyth.

Title: The IHIH Pyramid

Body:
I find it fascinating how the letters "H" and "I" are very similar. "H" is a horizontal stroke surrounded by two vertical strokes; "I" is a vertical stroke surrounded by two horizontal strokes (depending on your font). I bet this could be nested... You know what that reminds me of? Fractals!!!

Let's define the "IHIH" pyramid as follows: The first iteration is this ASCII representation of the letter "I":

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

The next iteration has a vertical stroke on either side.

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

If you view the "I" in the middle as a single horizontal stroke, then this second iteration is basically an "H". The third iteration adds a horizontal stroke on the top and bottom

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

Again, if you view the "H" in the middle as a single vertical stroke, then this iteration is basically an "I". This pattern continues, alternating between "H"s and "I"s on every iteration. For reference, here are the first 6 iterations:

```<code>1:
---
 |
---

2:
|   |
|---|
| | |
|---|
|   |

3:
-------
 |   |
 |---|
 | | |
 |---|
 |   |
-------

4:
|       |
|-------|
| |   | |
| |---| |
| | | | |
| |---| |
| |   | |
|-------|
|       |

5:
-----------
 |       |
 |-------|
 | |   | |
 | |---| |
 | | | | |
 | |---| |
 | |   | |
 |-------|
 |       |
-----------

6:
|           |
|-----------|
| |       | |
| |-------| |
| | |   | | |
| | |---| | |
| | | | | | |
| | |---| | |
| | |   | | |
| |-------| |
| |       | |
|-----------|
|           |
</code>```

The Challenge:

Write a program or function that outputs the N'th iteration of the IHIH pyramid, and an optional trailing newline. Your input will be a single positive integer in whatever reasonable format you want. You do not have to handle invalid inputs, e.g. non-integers, numbers smaller than 1, etc. Your program must at the very least produce the right output for inputs up to 20. Since this is code-golf, standard loopholes are not allowed and the shortest answer in bytes wins!

Body:
Brachylog, 84 bytes

,[[["|"]]:?:1]i:1:zi:ca~@nw
hh~m["-|":B]:ramggL," "ggS,?:Sz:ca:Srz:caz:Lz:ca:Lrz:ca.

Try it online!

A port of my answer in Pyth.


问:
All in all it's just, uh, another trick in code golf
The purpose of this challenge is to produce an ASCII version of the cover of this great album by the rock band Pink Floyd.

The brick junctions are made of characters _ and |. Bricks have width 7 and height 2 characters, excluding junctions. So the basic unit, including the junctions, is:

```<code>_________
|       |
|       |
_________
</code>```

Each row of bricks is offset by half a brick width (4 chars) with respect to the previous row:

```<code>________________________________________
  |       |       |       |       |
  |       |       |       |       |
________________________________________
      |       |       |       |       |
      |       |       |       |       |
________________________________________
  |       |       |       |       |
  |       |       |       |       |
</code>```

The wall is parameterized as follows. All parameters are measured in chars including junctions:

Horizontal offset of first row, F. This is the distance between the left margin and the first vertical junction of the upmost row. (Remember also the half-brick relative offset between rows). Its possible values are 0, 1, ..., 7.

Total width, W. This includes junctions. Its value is a positive integer.

Total height, H. This includes junctions. Its value is a positive integer.

The top of the wall always coincides with the top of a row. The bottom may be ragged (if the total height is not a multiple of 3). For example, here's the output for 6, 44, 11:

```<code>____________________________________________
      |       |       |       |       |
      |       |       |       |       |
____________________________________________
  |       |       |       |       |       |
  |       |       |       |       |       |
____________________________________________
      |       |       |       |       |
      |       |       |       |       |
____________________________________________
  |       |       |       |       |       |
</code>```

and a visual explanation of parameters:

```<code>          F=6
         ......
     .   ____________________________________________
     .         |       |       |       |       |
     .         |       |       |       |       |
     .   ____________________________________________
     .     |       |       |       |       |       |
H=11 .     |       |       |       |       |       |
     .   ____________________________________________
     .         |       |       |       |       |
     .         |       |       |       |       |
     .   ____________________________________________
     .     |       |       |       |       |       |

         ............................................
                             W=44
</code>```

Additional rules

You may provide a program or a function.

Input format is flexible as usual. Output may be through STDOUT or an argument returned by a function. In this case it may be a string with newlines or an array of strings.

Trailing spaces or newlines are allowed.

Shortest code in bytes wins.

Test cases

Inputs are in the order given above, that is: horizontal offset of first row, total width, total height.

```<code>6, 44, 11:
____________________________________________
      |       |       |       |       |
      |       |       |       |       |
____________________________________________
  |       |       |       |       |       |
  |       |       |       |       |       |
____________________________________________
      |       |       |       |       |
      |       |       |       |       |
____________________________________________
  |       |       |       |       |       |

2, 20, 10:
____________________
  |       |       |
  |       |       |
____________________
      |       |
      |       |
____________________
  |       |       |
  |       |       |
____________________

1, 1, 1:
_

1, 2, 3:
__
 |
 |

3, 80, 21:
________________________________________________________________________________
   |       |       |       |       |       |       |       |       |       |
   |       |       |       |       |       |       |       |       |       |
________________________________________________________________________________
       |       |       |       |       |       |       |       |       |       |
       |       |       |       |       |       |       |       |       |       |
________________________________________________________________________________
   |       |       |       |       |       |       |       |       |       |
   |       |       |       |       |       |       |       |       |       |
________________________________________________________________________________
       |       |       |       |       |       |       |       |       |       |
       |       |       |       |       |       |       |       |       |       |
________________________________________________________________________________
   |       |       |       |       |       |       |       |       |       |
   |       |       |       |       |       |       |       |       |       |
________________________________________________________________________________
       |       |       |       |       |       |       |       |       |       |
       |       |       |       |       |       |       |       |       |       |
________________________________________________________________________________
   |       |       |       |       |       |       |       |       |       |
   |       |       |       |       |       |       |       |       |       |
</code>```

答:
Delphi/Object Pascal, 305, 302, 292 bytes

Full console program that reads 3 parameters.

```<code>uses SySutils,Math;var i,q,o,w,h:byte;begin o:=StrToInt(paramstr(1));w:=StrToInt(paramstr(2));h:=StrToInt(paramstr(3));for q:=0to h-1do begin for i:=1to w do if q mod 3=0then Write('_')else if IfThen(Odd(q div 3),((i+o)mod 8),((i-o)mod 8))=1then Write('|')else Write(' ');Writeln('');end end.
</code>```

ungolfed

```<code>uses
  SySutils,
  Math;
var
  i,q,o,w,h:byte;
begin
  o:=StrToInt(paramstr(1));
  w:=StrToInt(paramstr(2));
  h:=StrToInt(paramstr(3));

  for q := 0 to h-1 do
  begin
    for i := 1 to w do
      if q mod 3 = 0  then
        Write('_')
      else
        if IfThen(Odd(q div 3),((i+o)mod 8),((i-o)mod 8)) = 1 then
          Write('|')
        else Write(' ');
    Writeln('');
  end
end.
</code>```

Sadly, Delphi does not have a ternary operator and it is quite a verbose language.

test case

```<code>D:\Test\CodeGolfWall\Win32\Debug>Project1.exe 2 20 10
____________________
  |       |       |
  |       |       |
____________________
      |       |
      |       |
____________________
  |       |       |
  |       |       |
____________________

D:\Test\CodeGolfWall\Win32\Debug>Project1.exe 6 44 11
____________________________________________
      |       |       |       |       |
      |       |       |       |       |
____________________________________________
  |       |       |       |       |       |
  |       |       |       |       |       |
____________________________________________
      |       |       |       |       |
      |       |       |       |       |
____________________________________________
  |       |       |       |       |       |
</code>```

Edit: Could shave of 3 bytes by using byte as type for all variables.

Edit 2: And console applications do not need the program declaration, -10

Body:
Delphi/Object Pascal, 305, 302, 292 bytes

Full console program that reads 3 parameters.

uses SySutils,Math;var i,q,o,w,h:byte;begin o:=StrToInt(paramstr(1));w:=StrToInt(paramstr(2));h:=StrToInt(paramstr(3));for q:=0to h-1do begin for i:=1to w do if q mod 3=0then Write('_')else if IfThen(Odd(q div 3),((i+o)mod 8),((i-o)mod 8))=1then Write('|')else Write(' ');Writeln('');end end.

ungolfed

uses
  SySutils,
  Math;
var
  i,q,o,w,h:byte;
begin
  o:=StrToInt(paramstr(1));
  w:=StrToInt(paramstr(2));
  h:=StrToInt(paramstr(3));

  for q := 0 to h-1 do
  begin
    for i := 1 to w do
      if q mod 3 = 0  then
        Write('_')
      else
        if IfThen(Odd(q div 3),((i+o)mod 8),((i-o)mod 8)) = 1 then
          Write('|')
        else Write(' ');
    Writeln('');
  end
end.

Sadly, Delphi does not have a ternary operator and it is quite a verbose language.

test case

D:\Test\CodeGolfWall\Win32\Debug>Project1.exe 2 20 10
____________________
  |       |       |
  |       |       |
____________________
      |       |
      |       |
____________________
  |       |       |
  |       |       |
____________________

D:\Test\CodeGolfWall\Win32\Debug>Project1.exe 6 44 11
____________________________________________
      |       |       |       |       |
      |       |       |       |       |
____________________________________________
  |       |       |       |       |       |
  |       |       |       |       |       |
____________________________________________
      |       |       |       |       |
      |       |       |       |       |
____________________________________________
  |       |       |       |       |       |

Edit: Could shave of 3 bytes by using byte as type for all variables.

Edit 2: And console applications do not need the program declaration, -10


答:
PHP – <s>1741</s> <s>1674</s> 1143 bytes

It was first set up by learning the profiles of the characters from the first few examples, which then summarized each character into six numbers. I chose six because I originally had five, and it didn't work as great as I'd like, but six seems to work much better. Much of the optimization involves squeezing these profiles into smaller and smaller byte counts.

The first and second profile *lhdfdn and |nnmmkk are actually the blue blob with "GB" at the bottom *, and the right border |, which we're ignoring. It's safer to include them so that the blob and right border have something to match against.

Should handle any image format, any reasonable scaling provided the aspect ratio doesn't change too much, any dark on light color, and even a bit of noise and shading!

It does need the border, at least at the top and bottom, that's part of the profile.

```<code><?php $X=[];foreach(str_split('*lhdfdn|nnmmkkA<njjk;BOnKB`^Chn::E7DHn?1X`EnkGGD4Fn_330!Gnj9G[IHnX!!XnJ%(##knKnX.EN6LnX!!!!Mn_<:bnNn^77_nPn^33@6QhfBDjnRn_8LaDSOlYYnUT$$nn$$Uh_##^nV9c][n;W_nWTlhXHnLTiCY4LhnM5ZJbnmaI0ng88lk1nnnnnn2C[__n`34B?Kna4+=Fnb"5NnUReX6gnKKaM7*4Xnb=8gkIIne9K`KKni',7)as$s){$t=[];foreach(str_split(substr($s,1))as$u)$t[]=ord($u)-11;$X[$s[0]]=$t;}echo m(r($argv[1]),$X)."\n";function r($u){$a=[];$i=imagecreatefromstring(file_get_contents($u));$w=imagesx($i);$h=imagesy($i);$s=[];for($x=0;$x<$w;$x++){$s[$x]=0;for($y=0;$y<$h;$y++){$p=imagecolorsforindex($i,imagecolorat($i,$x,$y));if(3*$p['red']+6*$p['green']+$p['blue']<1280)$s[$x]++;}}$j=0;$k=[];for($x=0;$x<$w;$x++){if($s[$x]>$h/10)for($o=0;$o<6;$o++)$k[]=$s[$x];elseif(count($k)){$a[]=$k;$j++;$k=[];}}$b=[];foreach($a as$v){$t=[];$u=array_chunk($v,intval(count($v)/6));foreach($u as$c)$t[]=array_sum($c)/count($c);$m=99/max($t);$e=[];foreach($t as$x)$e[]=intval($x*$m+0.5);$b[]=$e;}return$b;}function m($A,$X){$r='';foreach($A as$a){$s=INF;$c='';foreach($X as$k=>$x){$t=0;for($i=0;$i<6;$i++)$t+=pow($a[$i]-$x[$i],2);if($s>$t){$s=$t;$c=$k;}}$r.=$c;}return trim($r,'|*');}
</code>```

Save as ocr.php, then run from the command line:

```<code>$ php ocr.php http://i.imgur.com/UfI63md.png
ABCDEFG

$ php ocr.php http://i.imgur.com/oSAK7dy.png
H1JKLMN0

$ php ocr.php http://i.imgur.com/inuIHjm.png
PQRSTUVW

$ php ocr.php http://i.imgur.com/Th0QkhT.png
XYZ01234

$ php ocr.php http://i.imgur.com/igH3ZPQ.png
56789

$ php ocr.php http://i.imgur.com/YfVwebo.png
10

$ php ocr.php http://i.imgur.com/3ibQARb.png
C0D3GLF

$ php ocr.php http://i.imgur.com/c7XZqhL.png
B3T4DCY

$ php ocr.php http://i.imgur.com/ysBgXhn.png
M1NUS15
</code>```

For those that are interested, here is the learning code. Save as learn.php and run from the command line, no arguments.

```<code><?php

define('BANDS', 6);

main();

function main()
{
    $glyphs = [];

    learn($glyphs, 'http://imgur.com/UfI63md.png', '*ABCDEFG|');
    learn($glyphs, 'http://imgur.com/oSAK7dy.png', '*H1JKLMN0|');
    learn($glyphs, 'http://imgur.com/inuIHjm.png', '*PQRSTUVW|');
    learn($glyphs, 'http://imgur.com/Th0QkhT.png', '*XYZ01234|');
    learn($glyphs, 'http://imgur.com/igH3ZPQ.png', '*56789|');

    $profiles = summarize($glyphs);

    foreach ($profiles as $glyph=>$profile)
    {
        print $glyph;
        foreach ($profile as $value)
            print chr($value + 11);
        print "\n";
    }
}

function learn(&$glyphs, $url, $answer)
{
    $image = imagecreatefromstring(file_get_contents($url));
    $width = imagesx($image);
    $height = imagesy($image);
    $counts = [];
    for ($x = 0; $x < $width; $x++)
    {
        $counts[$x] = 0;
        for ($y = 0; $y < $height; $y++)
        {
            $pixel = imagecolorsforindex($image, imagecolorat($image, $x, $y));
            if (3 * $pixel['red'] + 6 * $pixel['green'] + $pixel['blue'] < 1280)
                $counts[$x]++;
        }
    }

    $index = 0;
    $expanded = [];
    for ($x = 0; $x < $width; $x++)
    {
        if ($counts[$x] > $height / 10)
            for ($inner = 0; $inner < BANDS; $inner++)
                $expanded[] = $counts[$x];
        else if (count($expanded)) {
            $glyphs[$answer[$index]] = $expanded;
            $index++;
            $expanded = [];
        }
    }
}

function summarize($glyphs)
{
    $profiles = [];
    foreach ($glyphs as $glyph=>$expanded)
    {
        $averages = [];
        $bands = array_chunk($expanded, count($expanded) / BANDS);
        foreach ($bands as $band)
            $averages[] = array_sum($band) / count($band);
        $scaling = 99 / max($averages);
        $profile = [];
        foreach ($averages as $average)
            $profile[] = intval($average * $scaling + 0.5);
        $profiles[$glyph] = $profile;
    }
    return $profiles;
}

?>
</code>```

Title: Number Plate Golf: Recognition

Body:
See also: Parsing

Introduction

You're working on a government programming team, who have been programming the speed cameras. However, the group of people who have programmed the speed calculator have taken up too much space, so you have to make the number plate recognition software as small as possible.

Challenge

Given an image of a number plate, return the text on the plate.

Number plates

The following are all of the characters which your program must recognise:

ABCDEFG

H1JKLMN0

PQRSTUVW

XYZ01234

56789

Note

On British number plates, the characters for I (i) and 1 (one) are the same and the characters for O (o) and 0 (zero) are the same. For that reason, always assume characters are the numbers. I.e. the following number plate is 10 (one zero):

Examples

C0D3 GLF

B3T4 DCY

M1NUS 15

YET1CGN

Other rules

Internet access and OCR libraries and functions are disallowed.

The number plates will always look identical to the ones shown above. All number plates will be roughly same size (there will be some inaccuracies due to cropping method).

If you require lossless PNG versions of any number plates, I will supply them to you.

Scoring

The shortest program in bytes wins.

All number plates are screenshots of the search bar at this site

Body:
PHP – <s>1741</s> <s>1674</s> 1143 bytes

It was first set up by learning the profiles of the characters from the first few examples, which then summarized each character into six numbers. I chose six because I originally had five, and it didn't work as great as I'd like, but six seems to work much better. Much of the optimization involves squeezing these profiles into smaller and smaller byte counts.

The first and second profile *lhdfdn and |nnmmkk are actually the blue blob with "GB" at the bottom *, and the right border |, which we're ignoring. It's safer to include them so that the blob and right border have something to match against.

Should handle any image format, any reasonable scaling provided the aspect ratio doesn't change too much, any dark on light color, and even a bit of noise and shading!

It does need the border, at least at the top and bottom, that's part of the profile.

<?php $X=[];foreach(str_split('*lhdfdn|nnmmkkA<njjk;BOnKB`^Chn::E7DHn?1X`EnkGGD4Fn_330!Gnj9G[IHnX!!XnJ%(##knKnX.EN6LnX!!!!Mn_<:bnNn^77_nPn^33@6QhfBDjnRn_8LaDSOlYYnUT$$nn$$Uh_##^nV9c][n;W_nWTlhXHnLTiCY4LhnM5ZJbnmaI0ng88lk1nnnnnn2C[__n`34B?Kna4+=Fnb"5NnUReX6gnKKaM7*4Xnb=8gkIIne9K`KKni',7)as$s){$t=[];foreach(str_split(substr($s,1))as$u)$t[]=ord($u)-11;$X[$s[0]]=$t;}echo m(r($argv[1]),$X)."\n";function r($u){$a=[];$i=imagecreatefromstring(file_get_contents($u));$w=imagesx($i);$h=imagesy($i);$s=[];for($x=0;$x<$w;$x++){$s[$x]=0;for($y=0;$y<$h;$y++){$p=imagecolorsforindex($i,imagecolorat($i,$x,$y));if(3*$p['red']+6*$p['green']+$p['blue']<1280)$s[$x]++;}}$j=0;$k=[];for($x=0;$x<$w;$x++){if($s[$x]>$h/10)for($o=0;$o<6;$o++)$k[]=$s[$x];elseif(count($k)){$a[]=$k;$j++;$k=[];}}$b=[];foreach($a as$v){$t=[];$u=array_chunk($v,intval(count($v)/6));foreach($u as$c)$t[]=array_sum($c)/count($c);$m=99/max($t);$e=[];foreach($t as$x)$e[]=intval($x*$m+0.5);$b[]=$e;}return$b;}function m($A,$X){$r='';foreach($A as$a){$s=INF;$c='';foreach($X as$k=>$x){$t=0;for($i=0;$i<6;$i++)$t+=pow($a[$i]-$x[$i],2);if($s>$t){$s=$t;$c=$k;}}$r.=$c;}return trim($r,'|*');}

Save as ocr.php, then run from the command line:

$ php ocr.php http://i.imgur.com/UfI63md.png
ABCDEFG

$ php ocr.php http://i.imgur.com/oSAK7dy.png
H1JKLMN0

$ php ocr.php http://i.imgur.com/inuIHjm.png
PQRSTUVW

$ php ocr.php http://i.imgur.com/Th0QkhT.png
XYZ01234

$ php ocr.php http://i.imgur.com/igH3ZPQ.png
56789

$ php ocr.php http://i.imgur.com/YfVwebo.png
10

$ php ocr.php http://i.imgur.com/3ibQARb.png
C0D3GLF

$ php ocr.php http://i.imgur.com/c7XZqhL.png
B3T4DCY

$ php ocr.php http://i.imgur.com/ysBgXhn.png
M1NUS15

For those that are interested, here is the learning code. Save as learn.php and run from the command line, no arguments.

<?php

define('BANDS', 6);

main();

function main()
{
    $glyphs = [];

    learn($glyphs, 'http://imgur.com/UfI63md.png', '*ABCDEFG|');
    learn($glyphs, 'http://imgur.com/oSAK7dy.png', '*H1JKLMN0|');
    learn($glyphs, 'http://imgur.com/inuIHjm.png', '*PQRSTUVW|');
    learn($glyphs, 'http://imgur.com/Th0QkhT.png', '*XYZ01234|');
    learn($glyphs, 'http://imgur.com/igH3ZPQ.png', '*56789|');

    $profiles = summarize($glyphs);

    foreach ($profiles as $glyph=>$profile)
    {
        print $glyph;
        foreach ($profile as $value)
            print chr($value + 11);
        print "\n";
    }
}

function learn(&$glyphs, $url, $answer)
{
    $image = imagecreatefromstring(file_get_contents($url));
    $width = imagesx($image);
    $height = imagesy($image);
    $counts = [];
    for ($x = 0; $x < $width; $x++)
    {
        $counts[$x] = 0;
        for ($y = 0; $y < $height; $y++)
        {
            $pixel = imagecolorsforindex($image, imagecolorat($image, $x, $y));
            if (3 * $pixel['red'] + 6 * $pixel['green'] + $pixel['blue'] < 1280)
                $counts[$x]++;
        }
    }

    $index = 0;
    $expanded = [];
    for ($x = 0; $x < $width; $x++)
    {
        if ($counts[$x] > $height / 10)
            for ($inner = 0; $inner < BANDS; $inner++)
                $expanded[] = $counts[$x];
        else if (count($expanded)) {
            $glyphs[$answer[$index]] = $expanded;
            $index++;
            $expanded = [];
        }
    }
}

function summarize($glyphs)
{
    $profiles = [];
    foreach ($glyphs as $glyph=>$expanded)
    {
        $averages = [];
        $bands = array_chunk($expanded, count($expanded) / BANDS);
        foreach ($bands as $band)
            $averages[] = array_sum($band) / count($band);
        $scaling = 99 / max($averages);
        $profile = [];
        foreach ($averages as $average)
            $profile[] = intval($average * $scaling + 0.5);
        $profiles[$glyph] = $profile;
    }
    return $profiles;
}

?>


Title: The IHIH Pyramid

Body:
Cheddar, 107 bytes

(n,g=n->n?(f->f(f(g(n-1)," ").turn(1),n%2?"-":"|"))((a,b)->a.map(i->b+i+b)):["|"])->(n%2?g(n).turn(1):g(n))

Try it online!


答:
C#, 157 chars

Horrible for golfing, but why not...

```<code>class C{unsafe static void Main(string[]a){var n=float.Parse(a[0]);var i=*(int*)&n/-2+0x5f3759df;var y=*(float*)&i;System.Console.Write(y*1.5f-y*n/2f*y*y);}}
</code>```

Readable version:

```<code>class C
{
    unsafe static void Main( string[] a )
    {
        var n = float.Parse( a[0] );
        var i = *(int*) &n / -2 + 0x5f3759df;
        var y = *(float*) &i;
        System.Console.Write( y * 1.5f - y * n / 2f * y * y );
    }
}
</code>```

Title: Fast inverse square root

Body:
Inspired by http://meta.codegolf.stackexchange.com/questions/547/write-a-code-golf-problem-in-which-script-languages-are-at-a-major-disadvantage question on meta, I've decided to make a question which could be problematic for scripting languages.

The goal is to calculate fast inverse square root, just like it was done in Quake III Arena. You will get the floating point number as first argument after program name and you should implement it. Simply doing ** -0.5 is disallowed as it doesn't implement the algorithm.

Your program will be called like this. The 12.34 could be other value.

```<code>$ interpreter program 12.34 # for interpreted languages
$ ./a.out 12.34 # for compiled languages
</code>```

For comparison, this is original Quake III Arena implementation.

```<code>float Q_rsqrt( float number )
{
        long i;
        float x2, y;
        const float threehalfs = 1.5F;

        x2 = number * 0.5F;
        y = number;
        i = * ( long * ) &y;                       // evil floating point bit level hacking
        i = 0x5f3759df - ( i >> 1 );               // what the heck?
        y = * ( float * ) &i;
        y = y * ( threehalfs - ( x2 * y * y ) );   // 1st iteration
//      y = y * ( threehalfs - ( x2 * y * y ) );   // 2nd iteration, this can be removed

        return y;
}
</code>```

You have to do just one iteration because the second was commented out.

Winning condition: Shortest code.

Body:
C#, 157 chars

Horrible for golfing, but why not...

class C{unsafe static void Main(string[]a){var n=float.Parse(a[0]);var i=*(int*)&n/-2+0x5f3759df;var y=*(float*)&i;System.Console.Write(y*1.5f-y*n/2f*y*y);}}

Readable version:

class C
{
    unsafe static void Main( string[] a )
    {
        var n = float.Parse( a[0] );
        var i = *(int*) &n / -2 + 0x5f3759df;
        var y = *(float*) &i;
        System.Console.Write( y * 1.5f - y * n / 2f * y * y );
    }
}


问:
Golf me a card dealer
Frank has been working IT his whole life. Each day he responds to tickets, organizes equipment, and reports to his boss. One day, near the closing time on friday, Frank is doing his final inventory and sorting come cables in the supply closet. Suddenly, the door closes and locks from the outside! Such audacity! Frank shakes the door to try and let anyone know that he's stuck in the closet. Blast, nobody comes to his aid. With no cellphone, and no internet connection, Frank settles in with his laptop. After countless games of solitaire, frank decides to make his own card game....

Challenge:

In this case, you are frank (but not really). Your challenge is to create a dealer that can deal hands of cards, that could be dealt realistically. Your program needs to do 2 things: deal hands of cards according to an input, and take all the hands and reshuffle them. You must do this in the least ammount of bytes possible.

Rules:

Possible cards include all classic numbers and faces (a,2,3,4,5,6,7,8,9,10,j,q,k) and all suits (c,s,h,d), and two jokers (0j).

If a card is dealt, it cannot be dealt again until the program is given the reshuffle command, or it runs out of cards.

valid inputs are 'd' to deal a hand of 6 cards, and 'r' to reshuffle. NOTE that you can only deal out 9 hands before you run out of cards. Your program can either:

Automatically reshuffle,

Or give a 'X' to indicate that the dealer is out of cards.

your program needs to be able to take multiple commands over its running span.

All possible hands need to be able to be dealt in every order. Though, your program does NOT have to be random.

Examples:

We deal twice, the first hand yields the 2 of hearts, a 4 of spades, 9 of clubs, a joker, an ace of spades, and a 6 of diamonds. The second hand yields the 3 of hearts, the 10 of diamonds, the 10 of clubs, the king of clubs, the ace of diamonds, and the queen of spades. this is VALID because this is possible in real life.

d

  2h4s9c0jas6d

  d

  3h10d10ckcadqs

We deal twice, the first hand yields a mass of 5 cards (indicated by the dashes) and a 6 of hearts. The second hand deals another mass of 5 cards (again, the dashes) and another 6 of hearts. This is INVALID because it cannot happen in real life.

d

  -----6h

  d

  6h-----

we deal once, reset, and deal again. some of the cards from the first and the second deal match. this is VALID because cardstacks are renewed when shuffled.

d

  123456

  r

d

  456789

Scoring:

As with any golf, the lowest byte count wins! Good luck!

答:
Python 3, <s>184 192</s> 179 bytes

```<code>d=lambda:[(v+s,'10'+s)[v=='1']for v in'123456789JQKA'for s in'SCHD']+['0J']*2
_=0;c=d()
while 1:
 if input()<'r'*(len(c)>5):[print(c.pop())for i in'_'*6]
 else:c=d();del c[_];_+=1
</code>```

Edit: jokers
Edit 2: switched from using random and shuffling the list to cycling through the list and deleting 1 index from it incrementally.

Try it

Title: Golf me a card dealer

Body:
Python 3, <s>184 192</s> 179 bytes

d=lambda:[(v+s,'10'+s)[v=='1']for v in'123456789JQKA'for s in'SCHD']+['0J']*2
_=0;c=d()
while 1:
 if input()<'r'*(len(c)>5):[print(c.pop())for i in'_'*6]
 else:c=d();del c[_];_+=1

Edit: jokers
Edit 2: switched from using random and shuffling the list to cycling through the list and deleting 1 index from it incrementally.

Try it


答:
Python 2, 93 bytes

Leaky Nun saved 7 bytes.

r=range(input()+1)
r=r[:0:-1]+r
for y in r:print''.join('| -'[[x%2,y%2+1][x&-2<y]]for x in r)
```

Title: The IHIH Pyramid


问:
Code golf ABC's: The ASCII Box Challenge
Given two positive integers, 'a' and 'b', output an ascii-art "box" that is a characters wide and b characters tall. For example, with '4' and '6':

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

Simple right? Here's the twist: The border of the box must be the characters of "a" and "b" alternating. This starts at the top left corner, and continues in a clockwise spiral. For example, the previous example with 4 and 6 should be

```<code>4646
6  4
4  6
6  4
4  6
6464
</code>```

A and B may be two-digit numbers. For example, the inputs "10" and "3" should output this:

```<code>1031031031
1        0
3013013013
</code>```

In order to keep the output relatively small, you do not have to support three or more digit numbers. Also, since inputs are restricted to positive integers, '0' is an invalid input, which you do not have to handle.

Here are some more test cases:

```<code>Input: (3, 5)
Output:

353
5 5
3 3
5 5
353

Input: (1, 1)
Output:

1

Input: (4, 4)
Output:

4444
4  4
4  4
4444

Input: (27, 1)
Output:

271271271271271271271271271

Input: (1, 17)
Output:

1
1
7
1
1
7
1
1
7
1
1
7
1
1
7
1
1

Input: (12, 34):
Output:

123412341234
4          1
3          2
2          3
1          4
4          1
3          2
2          3
1          4
4          1
3          2
2          3
1          4
4          1
3          2
2          3
1          4
4          1
3          2
2          3
1          4
4          1
3          2
2          3
1          4
4          1
3          2
2          3
1          4
4          1
3          2
2          3
1          4
432143214321
</code>```

You may take input and output in any reasonable format, and standard loopholes are banned. Since this is code-golf, the shortest answer in bytes wins!

答:
TSQL, 291 bytes

Golfed:

```<code>DECLARE @ INT=5,@2 INT=4

,@t INT,@z varchar(max)SELECT @t=iif(@*@2=1,1,(@+@2)*2-4),@z=left(replicate(concat(@,@2),99),@t)v:PRINT iif(len(@z)=@t,left(@z,@),iif(len(@z)>@,right(@z,1)+isnull(space(@-2)+left(@z,1),''),reverse(@z)))SET @z=iif(len(@z)=@t,stuff(@z,1,@,''),substring(@z,2,abs(len(@z)-2)))IF @<=len(@z)goto v
</code>```

Ungolfed:

```<code>DECLARE @ INT=5,@2 INT=4

,@t INT,@z varchar(max)
SELECT @t=iif(@*@2=1,1,(@+@2)*2-4),@z=left(replicate(concat(@,@2),99),@t)

v:
  PRINT
    iif(len(@z)=@t,left(@z,@),iif(len(@z)>@,right(@z,1)
      +isnull(space(@-2)+left(@z,1),''),reverse(@z)))
  SET @z=iif(len(@z)=@t,stuff(@z,1,@,''),substring(@z,2,abs(len(@z)-2)))
IF @<=len(@z)goto v
</code>```

Fiddle

Body:
TSQL, 291 bytes

Golfed:

DECLARE @ INT=5,@2 INT=4

,@t INT,@z varchar(max)SELECT @t=iif(@*@2=1,1,(@+@2)*2-4),@z=left(replicate(concat(@,@2),99),@t)v:PRINT iif(len(@z)=@t,left(@z,@),iif(len(@z)>@,right(@z,1)+isnull(space(@-2)+left(@z,1),''),reverse(@z)))SET @z=iif(len(@z)=@t,stuff(@z,1,@,''),substring(@z,2,abs(len(@z)-2)))IF @<=len(@z)goto v

Ungolfed:

DECLARE @ INT=5,@2 INT=4

,@t INT,@z varchar(max)
SELECT @t=iif(@*@2=1,1,(@+@2)*2-4),@z=left(replicate(concat(@,@2),99),@t)

v:
  PRINT
    iif(len(@z)=@t,left(@z,@),iif(len(@z)>@,right(@z,1)
      +isnull(space(@-2)+left(@z,1),''),reverse(@z)))
  SET @z=iif(len(@z)=@t,stuff(@z,1,@,''),substring(@z,2,abs(len(@z)-2)))
IF @<=len(@z)goto v

Fiddle


答:
Pyth - 16 bytes

```<code>?}\.Q+dQ+Q-"\/"e
</code>```

Test Suite.

Title: Wave-Particle Duality Laterally Programmatically

Body:
Write a program or function that takes in a nonempty single-line string. The string will either be zero or more spaces followed by one period (a particle), such as . or          ., or the string will be a sequence of one or more alternating forward and back slashes (a wave) that could start with either one, such as \ or /\/ or \/\/\/\/\/\/.

In either case, propagate the particle/wave to the right by one unit.

Specifically, in the particle case, insert a space before the ., moving it one place to the right, then output the resulting string. For example:

. →  .

 . →   .

  . →    .

   . →     .

    . →      .

     . →       .

      . →        .

       . →         .

In the wave case, append either / or \ appropriately so the wave keeps alternating and it's length increases by one, then output the resulting string. For example:

/ → /\

\ → \/

/\ → /\/

\/ → \/\

/\/ → /\/\

\/\ → \/\/

/\/\ → /\/\/

\/\/ → \/\/\

In either case, the output may not have trailing spaces but an optional trailing newline is allowed.

The shortest code in bytes wins.

Body:
Pyth - 16 bytes

?}\.Q+dQ+Q-"\/"e

Test Suite.


答:
Javascript: 60 bytes

```<code> i=>i.includes(".")?" "+i:i.charAt(i.length-1)=="/"?i+"\\":i+"/"
</code>```

Body:
Javascript: 60 bytes

 i=>i.includes(".")?" "+i:i.charAt(i.length-1)=="/"?i+"\\":i+"/"


答:
Ruby, <s>81</s> <s>78</s> 77 bytes

This is based on Lynn's Python answer. Golfing suggestions welcome.

Edit: 3 bytes thanks to Lynn. Corrections and golfing 1 byte thanks to Jordan.

->n{r=(-n..n).map &:abs;r.map{|y|puts r.map{|x|"| -"[x&-2<y ?y%2+1:x%2]}*""}}
```

<p><strong>Ungolfing:</strong></p>

<pre class="lang-ruby prettyprint-override"><code>def f(n)
  r = -n..n            # Range from -n to n (inclusive)
  r = r.map{|i|i.abs}  # Turns every element of r positive
  r.each do |y|
    s = ""             # a line of the fractal
    r.each do |x|      # build up the fractal based on x and y
      if x/2*2 < y
        s += " -"[y%2]
      else
        s += "| "[x%2]
      end
    end
    puts s             # print the line
  end
end
</code>```

Title: The IHIH Pyramid

Body:
Ruby, <s>81</s> <s>78</s> 77 bytes

This is based on Lynn's Python answer. Golfing suggestions welcome.

Edit: 3 bytes thanks to Lynn. Corrections and golfing 1 byte thanks to Jordan.

->n{r=(-n..n).map &:abs;r.map{|y|puts r.map{|x|"| -"[x&-2<y ?y%2+1:x%2]}*""}}

Ungolfing:

def f(n)
  r = -n..n            # Range from -n to n (inclusive)
  r = r.map{|i|i.abs}  # Turns every element of r positive
  r.each do |y|
    s = ""             # a line of the fractal
    r.each do |x|      # build up the fractal based on x and y
      if x/2*2 < y
        s += " -"[y%2]
      else
        s += "| "[x%2]
      end
    end
    puts s             # print the line
  end
end


问:
Implement this key cipher

Implement this key cipher

Goal

Use the algorithm (explained in the Algorithm section) to implement a certain cipher.

The program must read input from STDIN or the closest available equivalent, use the algorithm to generate the ciphertext and a key.

The ciphertext and the key will be written to STDOUT or the closest available equivalent. Any format is allowed, as long as it outputs the ciphertext and the key.

Algorithm

Convert the characters in the string into the respective ASCII values. For example:

Hello -> 72 101 108 108 111

Next, you will need to generate a key as long as the string with random numbers in the range of 0-9.

Hello -> 62841

Add the integers in the random number sequence to the ASCII values of the string. In the above examples, 72 would become 78, and 101 would become 104.

72 + 6 = 78, 101 + 2 = 103, 108 + 8 = 116, etc

Next, convert the new values back to characters. In the above examples, the text Hello has become Ngtpp.

Examples

(These are simply examples of what the output might look like. The output can and will vary.)

```<code>Hello World

Lfrlu)_supg
41606984343
</code>```

```<code>This will be encoded

Zhjs$~koo gj$iuhofgj
60104723305544750226
</code>```

Rules

You can assume that the input will only contain characters in the range a-z, A-Z, and spaces.

Submissions must be full programs or functions.

Submissions will be scored in bytes.

Standard loopholes are forbidden.

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

(This is one of my first challenges, if there's something wrong with it, feel free to tell me how I could improve it.)

答:
Pyth - 16 bytes

Waiting for decision by OP on the output formats.

```<code>sCM+VCMQKmOTQjkK
</code>```

Test Suite.

Title: Implement this key cipher

Body:
Pyth - 16 bytes

Waiting for decision by OP on the output formats.

sCM+VCMQKmOTQjkK

Test Suite.


答:
PowerShell v2+, <s>79</s> 77 bytes

```<code>param($n)-join(($x=[char[]]$n|%{0..9|Random})|%{[char]($_+$n[$i++])});-join$x
</code>```

Takes input $n, loops over every character and gets a Random element from 0..9 each iteration. Stores those numbers (as an array) into $x. Pipes that array into another loop. Each iteration, takes the current element $_, adds it to the positional char sliced out of $n (implicit char-to-int cast), then re-casts as [char]. Leaves that on the pipeline. That's encapsulated in parens and -joined together to form the word. That's left on the pipeline. Additionally, the number $x is also -joined together and left on the pipeline. Those are implicitly printed with a Write-Output at the end of execution, which results in them being printed with a newline by default.

Example

```<code>PS C:\Tools\Scripts\golfing> .\implement-this-key-cipher.ps1 'Hello World!'
Lhoot(Yt{mf"
433358259121
</code>```

Title: Implement this key cipher

Body:
Implement this key cipher

Goal

Use the algorithm (explained in the Algorithm section) to implement a certain cipher.

The program must read input from STDIN or the closest available equivalent, use the algorithm to generate the ciphertext and a key.

The ciphertext and the key will be written to STDOUT or the closest available equivalent. Any format is allowed, as long as it outputs the ciphertext and the key.

Algorithm

Convert the characters in the string into the respective ASCII values. For example:

Hello -> 72 101 108 108 111

Next, you will need to generate a key as long as the string with random numbers in the range of 0-9.

Hello -> 62841

Add the integers in the random number sequence to the ASCII values of the string. In the above examples, 72 would become 78, and 101 would become 104.

72 + 6 = 78, 101 + 2 = 103, 108 + 8 = 116, etc

Next, convert the new values back to characters. In the above examples, the text Hello has become Ngtpp.

Examples

(These are simply examples of what the output might look like. The output can and will vary.)

```<code>Hello World

Lfrlu)_supg
41606984343
</code>```

```<code>This will be encoded

Zhjs$~koo gj$iuhofgj
60104723305544750226
</code>```

Rules

You can assume that the input will only contain characters in the range a-z, A-Z, and spaces.

Submissions must be full programs or functions.

Submissions will be scored in bytes.

Standard loopholes are forbidden.

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

(This is one of my first challenges, if there's something wrong with it, feel free to tell me how I could improve it.)

Body:
PowerShell v2+, <s>79</s> 77 bytes

param($n)-join(($x=[char[]]$n|%{0..9|Random})|%{[char]($_+$n[$i++])});-join$x

Takes input $n, loops over every character and gets a Random element from 0..9 each iteration. Stores those numbers (as an array) into $x. Pipes that array into another loop. Each iteration, takes the current element $_, adds it to the positional char sliced out of $n (implicit char-to-int cast), then re-casts as [char]. Leaves that on the pipeline. That's encapsulated in parens and -joined together to form the word. That's left on the pipeline. Additionally, the number $x is also -joined together and left on the pipeline. Those are implicitly printed with a Write-Output at the end of execution, which results in them being printed with a newline by default.

Example

PS C:\Tools\Scripts\golfing> .\implement-this-key-cipher.ps1 'Hello World!'
Lhoot(Yt{mf"
433358259121


答:
CJam - 14 bytes

When I saw the ascii code math, I knew I had to write a CJam answer.

```<code>q_{;Amr}%_@.+p
</code>```

Try it online here.

Title: Implement this key cipher

Body:
CJam - 14 bytes

When I saw the ascii code math, I knew I had to write a CJam answer.

q_{;Amr}%_@.+p

Try it online here.


问:
Hello World 0.0!

 source: Dilbert, September 8, 1992

I'm hoping to add a new twist on the classic "Hello World!" program.

Code a program that outputs Hello World! without:

String/Character literals

Numbers (any base)

Pre-built functions that return "Hello World!"

RegEx literals

With the exceptions of "O"† and 0.

†"O" is capitalized, "o" is not acceptable.

答:
JavaScript 100 chars (when all in one line)

Borrowing subtly from zzzzBov -- with regard to the -~ trick, not seen that before :) -- this is another way to source those pesky space and exclamation characters.

Relies on the Function.toString() ability:

```<code>c=!0<<-~-~!0;a=[];
for(i in{Hello:0,world:"O"}){a+=i+([]+function(){!0}).charAt(c);c+=c>>!0}
alert(a)
</code>```

JavaScript 89 chars (when all in one line)

Also zzzzBov could slightly improve the first example by using the fact that arrays in JS collapse down to strings when used in a calculation; oh, and not creating needless vars ;)

```<code>t=!0<<-~-~-~-~!0;r=[];for(i in{Hello:"O",World:0})r+=i+String.fromCharCode(t++);alert(r)
</code>```

Title: Hello World 0.0!

Body:
JavaScript 100 chars (when all in one line)

Borrowing subtly from zzzzBov -- with regard to the -~ trick, not seen that before :) -- this is another way to source those pesky space and exclamation characters.

Relies on the Function.toString() ability:

c=!0<<-~-~!0;a=[];
for(i in{Hello:0,world:"O"}){a+=i+([]+function(){!0}).charAt(c);c+=c>>!0}
alert(a)

JavaScript 89 chars (when all in one line)

Also zzzzBov could slightly improve the first example by using the fact that arrays in JS collapse down to strings when used in a calculation; oh, and not creating needless vars ;)

t=!0<<-~-~-~-~!0;r=[];for(i in{Hello:"O",World:0})r+=i+String.fromCharCode(t++);alert(r)


答:
Python 3, 130 bytes

Thanks to @Rod for pointing out a bug

```<code>from random import*
def f(x):l=10**len(x);k=str(randint(0,l-1)+l)[1:];print(''.join(chr(ord(i)+int(j))for i,j in zip(x,k))+'\n'+k)
</code>```

A function that takes input via argument as a string and prints to STDOUT.

How it works

```<code>from random import*  Import everything from the random module
def f(x):            Function with input string x
l=10**len(x)         Define l for later use as 10^length(x)
randint(0,l-1)+l     Generate a random integer in the range [0, l-1] and add l, giving a
                     number with l+1 digits...
k=str(...)[1:]       ...convert to a string and remove the first character, giving a key of
                     length l that can include leading zeroes, and store in k
for i,j in zip(x,k)  For each character pair i,j in x and k:
chr(ord(i)+int(j))    Find the UTF-8 code-point (same as ASCII for the ASCII characters),
                      add the relevant key digit and convert back to character
''.join(...)         Concatenate the characters of the ciphertext
print(...+'\n'+k)    Add newline and key, then print to STDOUT
</code>```

Try it on Ideone

Title: Implement this key cipher

Body:
Python 3, 130 bytes

Thanks to @Rod for pointing out a bug

from random import*
def f(x):l=10**len(x);k=str(randint(0,l-1)+l)[1:];print(''.join(chr(ord(i)+int(j))for i,j in zip(x,k))+'\n'+k)

A function that takes input via argument as a string and prints to STDOUT.

How it works

from random import*  Import everything from the random module
def f(x):            Function with input string x
l=10**len(x)         Define l for later use as 10^length(x)
randint(0,l-1)+l     Generate a random integer in the range [0, l-1] and add l, giving a
                     number with l+1 digits...
k=str(...)[1:]       ...convert to a string and remove the first character, giving a key of
                     length l that can include leading zeroes, and store in k
for i,j in zip(x,k)  For each character pair i,j in x and k:
chr(ord(i)+int(j))    Find the UTF-8 code-point (same as ASCII for the ASCII characters),
                      add the relevant key digit and convert back to character
''.join(...)         Concatenate the characters of the ciphertext
print(...+'\n'+k)    Add newline and key, then print to STDOUT

Try it on Ideone


答:
Actually, 17 bytes

```<code>;`X9J`M;(O¥♂cΣ@εj
</code>```

Try it online!

Explanation:

```<code>;`X9J`M;(O¥♂cΣ@εj
;                  dupe input
 `X9J`M            for each character in input copy:
  X9J                discard the character, push a random integer in [0, 9]
       ;           duplicate the offset array
        (O         bring input to top of stack, ordinal array
          ¥♂c      pairwise addition with offset array, turn each ordinal into a character
             Σ     concatenate
              @εj  concatenate the copy of the offset array
</code>```

Title: Implement this key cipher

Body:
Actually, 17 bytes

;`X9J`M;(O¥♂cΣ@εj

Try it online!

Explanation:

;`X9J`M;(O¥♂cΣ@εj
;                  dupe input
 `X9J`M            for each character in input copy:
  X9J                discard the character, push a random integer in [0, 9]
       ;           duplicate the offset array
        (O         bring input to top of stack, ordinal array
          ¥♂c      pairwise addition with offset array, turn each ordinal into a character
             Σ     concatenate
              @εj  concatenate the copy of the offset array