Title: Generate a valid sequence of numbers with specific rules

Body:
The challenge

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

Rules

x is the size of the sequence;

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

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

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

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

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

Examples

If x=4:

2413 valid

3142 valid

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

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

Still don't get it?
Other example:

If x=8:

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

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

Additional Information

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

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

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

Good, luck. =)

Body:
Python, 37

range(3,x+1,2)+[1]+range(4,x+1,2)+[2])

http://ideone.com/xK40m


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

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

Rules:

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

Last two digits will be between 01 and 12.

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

List of months with corresponding code:

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

Examples:

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

答:
Factor, <s>82</s> 78 bytes

```<code>[ [ 2 tail* 10 base> month-abbreviation ] [ 4 head 2 tail ] bi append >upper ]
</code>```

Eshplained:

```<code>[                    ! new anonymouse function block (quotation)
  [                  ! new quotation
    2 tail*          ! "201604" -> "04"
    10 base>         ! "04"     -> 4
    month-abbreviation ! 4 -> "Apr"
  ]                  ! end quotation
  [                  ! new quotation
    4 head           ! "201604" -> "2016"
    2 tail           ! "2016"   -> "16"
  ]                  ! end quotation
  bi                 ! bifurcate two quotations to TOS
  append             ! "Apr" "16" -> "Apr16"
  >upper             ! "Apr16"    -> "APR16"
]                    ! end quotation
</code>```

ContentLicense: CC BY-SA 3.0

Title: Convert YYYYMM to MMMYY

Body:
Factor, <s>82</s> 78 bytes

[ [ 2 tail* 10 base> month-abbreviation ] [ 4 head 2 tail ] bi append >upper ]

Eshplained:

[                    ! new anonymouse function block (quotation)
  [                  ! new quotation
    2 tail*          ! "201604" -> "04"
    10 base>         ! "04"     -> 4
    month-abbreviation ! 4 -> "Apr"
  ]                  ! end quotation
  [                  ! new quotation
    4 head           ! "201604" -> "2016"
    2 tail           ! "2016"   -> "16"
  ]                  ! end quotation
  bi                 ! bifurcate two quotations to TOS
  append             ! "Apr" "16" -> "Apr16"
  >upper             ! "Apr16"    -> "APR16"
]                    ! end quotation


问:
Bytes/Character

Task

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

Examples

! → 1

Ciao → 1 1 1 1

tʃaʊ → 1 2 1 2

Adám → 1 1 2 1

ĉaŭ → 2 1 2 (single characters)

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

チャオ → 3 3 3

 (empty input) →  (empty output)

!±≡ → 1 2 3 4

� (a null byte) → 1

Null bytes

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

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

答:
C, 85 bytes.

```<code>l(unsigned char* c){while(*c){int d=(*c>>4)-11;
d=d<0?1:d+(d==1);putchar(48+d);c+=d;}}
</code>```

Examines the high 4 bits of each byte to determine the encoding and the number of subsequent bytes to skip;

Title: Bytes/Character

Body:
C, 85 bytes.

l(unsigned char* c){while(*c){int d=(*c>>4)-11;
d=d<0?1:d+(d==1);putchar(48+d);c+=d;}}

Examines the high 4 bits of each byte to determine the encoding and the number of subsequent bytes to skip;


答:
C, <s>68</s> 65 bytes

b;main(c){for(;~c;b=c/64^2?b?putchar(b+48)/48:1:b+1)c=getchar();}
```

Thanks to @FryAmTheEggman for golfing off 3 bytes!

Test it on Ideone.

Title: Bytes/Character

Body:
Task

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

Examples

! → 1

Ciao → 1 1 1 1

tʃaʊ → 1 2 1 2

Adám → 1 1 2 1

ĉaŭ → 2 1 2 (single characters)

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

チャオ → 3 3 3

 (empty input) →  (empty output)

!±≡ → 1 2 3 4

� (a null byte) → 1

Null bytes

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

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

Body:
C, <s>68</s> 65 bytes

b;main(c){for(;~c;b=c/64^2?b?putchar(b+48)/48:1:b+1)c=getchar();}

Thanks to @FryAmTheEggman for golfing off 3 bytes!

Test it on Ideone.


问:
Simple cat program
One of the most common standard tasks (especially when showcasing esoteric programming languages) is to implement a "cat program": read all of STDIN and print it to STDOUT. While this is named after the Unix shell utility cat it is of course much less powerful than the real thing, which is normally used to print (and concatenate) several files read from disc.

Task

You should write a full program which reads the contents of the standard input stream and writes them verbatim to the standard output stream. If and only if your language does not support standard input and/or output streams (as understood in most languages), you may instead take these terms to mean their closest equivalent in your language (e.g. JavaScript's prompt and alert). These are the only admissible forms of I/O, as any other interface would largely change the nature of the task and make answers much less comparable.

The output should contain exactly the input and nothing else. The only exception to this rule is constant output of your language's interpreter that cannot be suppressed, such as a greeting, ANSI color codes or indentation. This also applies to trailing newlines. If the input does not contain a trailing newline, the output shouldn't include one either! (The only exception being if your language absolutely always prints a trailing newline after execution.)

Output to the standard error stream is ignored, so long as the standard output stream contains the expected output. In particular, this means your program can terminate with an error upon hitting the end of the stream (EOF), provided that doesn't pollute the standard output stream. If you do this, I encourage you to add an error-free version to your answer as well (for reference).

As this is intended as a challenge within each language and not between languages, there are a few language specific rules:

If it is at all possible in your language to distinguish null bytes in the standard input stream from the EOF, your program must support null bytes like any other bytes (that is, they have to be written to the standard output stream as well).

If it is at all possible in your language to support an arbitrary infinite input stream (i.e. if you can start printing bytes to the output before you hit EOF in the input), your program has to work correctly in this case. As an example yes | tr -d \\n | ./my_cat should print an infinite stream of ys. It is up to you how often you print and flush the standard output stream, but it must be guaranteed to happen after a finite amount of time, regardless of the stream (this means, in particular, that you cannot wait for a specific character like a linefeed before printing).

Please add a note to your answer about the exact behaviour regarding null-bytes, infinite streams, and extraneous output.

Additional rules

This is not about finding the language with the shortest solution for this (there are some where the empty program does the trick) - this is about finding the shortest solution in every language. Therefore, no answer will be marked as accepted.

Submissions in most languages will be scored in bytes in an appropriate preexisting encoding, usually (but not necessarily) UTF-8.

Some languages, like Folders, are a bit tricky to score. If in doubt, please ask on Meta.

Feel free to use a language (or language version) even if it's newer than this challenge. Languages specifically written to submit a 0-byte answer to this challenge are fair game but not particularly interesting.

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

Also note that languages do have to fulfil our usual criteria for programming languages.

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

Unless they have been overruled earlier, all standard code-golf rules apply, including the http://meta.codegolf.stackexchange.com/q/1061.

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

Catalogue

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

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

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

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

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

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

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

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

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

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

Shortest Solution by Language

Language	User	Score

Leaderboard

	Author	Language	Size

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

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

```

答:
V, 0 bytes

Try it online!

V's idea of "memory" is just a gigantic 2D array of characters. Before any program is ran, all input it loaded into this array (known as "The Buffer"). Then, at the end of any program, all text in the buffer is printed.

In other words, the empty program is a cat program.

Title: Simple cat program


问:
Generate ASCII Art
Given a black-and-white image in any reasonable lossless format as input, output ASCII art that is as close to the input image as possible.

Rules

Only linefeeds and ASCII bytes 32-127 may be used.

The input image will be cropped so that there is no extraneous whitespace surrounding the image.

Submissions must be able to complete the entire scoring corpus in under 5 minutes.

Only raw text is acceptable; no rich text formats.

The font used in the scoring is 20-pt Linux Libertine.

The output text file, when converted to an image as described below, must be the same dimensions as the input image, within 30 pixels in either dimension.

Scoring

These images will be used for scoring:

You can download a zipfile of the images here.

Submissions should not be optimized for this corpus; rather, they should work for any 8 black-and-white images of similar dimensions. I reserve the right to change the images in the corpus if I suspect submissions are being optimized for these specific images.

The scoring will be performed via this script:

#!/usr/bin/env python
from __future__ import print_function
from __future__ import division
# modified from http://stackoverflow.com/a/29775654/2508324
# requires Linux Libertine fonts - get them at https://sourceforge.net/projects/linuxlibertine/files/linuxlibertine/5.3.0/
# requires dssim - get it at https://github.com/pornel/dssim
import PIL
import PIL.Image
import PIL.ImageFont
import PIL.ImageOps
import PIL.ImageDraw
import pathlib
import os
import subprocess
import sys

PIXEL_ON = 0  # PIL color to use for "on"
PIXEL_OFF = 255  # PIL color to use for "off"

def dssim_score(src_path, image_path):
    out = subprocess.check_output(['dssim', src_path, image_path])
    return float(out.split()[0])

def text_image(text_path):
    """Convert text file to a grayscale image with black characters on a white background.

    arguments:
    text_path - the content of this file will be converted to an image
    """
    grayscale = 'L'
    # parse the file into lines
    with open(str(text_path)) as text_file:  # can throw FileNotFoundError
        lines = tuple(l.rstrip() for l in text_file.readlines())

    # choose a font (you can see more detail in my library on github)
    large_font = 20  # get better resolution with larger size
    if os.name == 'posix':
        font_path = '/usr/share/fonts/linux-libertine/LinLibertineO.otf'
    else:
        font_path = 'LinLibertine_DRah.ttf'
    try:
        font = PIL.ImageFont.truetype(font_path, size=large_font)
    except IOError:
        print('Could not use Libertine font, exiting...')
        exit()

    # make the background image based on the combination of font and lines
    pt2px = lambda pt: int(round(pt * 96.0 / 72))  # convert points to pixels
    max_width_line = max(lines, key=lambda s: font.getsize(s)[0])
    # max height is adjusted down because it's too large visually for spacing
    test_string = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
    max_height = pt2px(font.getsize(test_string)[1])
    max_width = pt2px(font.getsize(max_width_line)[0])
    height = max_height * len(lines)  # perfect or a little oversized
    width = int(round(max_width + 40))  # a little oversized
    image = PIL.Image.new(grayscale, (width, height), color=PIXEL_OFF)
    draw = PIL.ImageDraw.Draw(image)

    # draw each line of text
    vertical_position = 5
    horizontal_position = 5
    line_spacing = int(round(max_height * 0.8))  # reduced spacing seems better
    for line in lines:
        draw.text((horizontal_position, vertical_position),
                  line, fill=PIXEL_ON, font=font)
        vertical_position += line_spacing
    # crop the text
    c_box = PIL.ImageOps.invert(image).getbbox()
    image = image.crop(c_box)
    return image

if __name__ == '__main__':
    compare_dir = pathlib.PurePath(sys.argv[1])
    corpus_dir = pathlib.PurePath(sys.argv[2])
    images = []
    scores = []
    for txtfile in os.listdir(str(compare_dir)):
        fname = pathlib.PurePath(sys.argv[1]).joinpath(txtfile)
        if fname.suffix != '.txt':
            continue
        imgpath = fname.with_suffix('.png')
        corpname = corpus_dir.joinpath(imgpath.name)
        img = text_image(str(fname))
        corpimg = PIL.Image.open(str(corpname))
        img = img.resize(corpimg.size, PIL.Image.LANCZOS)
        corpimg.close()
        img.save(str(imgpath), 'png')
        img.close()
        images.append(str(imgpath))
        score = dssim_score(str(corpname), str(imgpath))
        print('{}: {}'.format(corpname, score))
        scores.append(score)
    print('Score: {}'.format(sum(scores)/len(scores)))
```

The scoring process:

Run the submission for each corpus image, outputting the results to .txt files with the same stem as the corpus file (done manually).

Convert each text file to a PNG image, using 20-point font, cropping out whitespace.

Resize the result image to the dimensions of the original image using Lanczos resampling.

Compare each text image with the original image using dssim.

Output the dssim score for each text file.

Output the average score.

Structural Similarity (the metric by which dssim calculates scores) is a metric based on human vision and object identification in images. To put it plainly: if two images look similar to humans, they will (probably) have a low score from dssim.

The winning submission will be the submission with the lowest average score.

related

答:
Java, score 0.57058675

This is actually my first time doing image manipulation so it's kind of awkward but I think it turned out OK.

I couldn't get dssim to work on my machine, but I was able to make images using PIL.

Interestingly, the font tells me in Java that each of the characters I'm using are width 6. You can see that in my program FontMetrics::charWidth is 6 for all characters that I have used. The {} logo looks pretty decent in a monospace font. But for some reason the lines do not actually line up in the full text file. I blame ligatures. (And yes, I should be using the correct font.)

In monospaced font:

```<code>                                                                                .
                         .,:ff:,                                                   ,:fff::,.
                ,ff .fIIIIIf,                                                         .:fIIIIIf.:f:.
            .,:III: ,ff::                       ..,,            ,,..                      ,:fff, IIII.,
          :IIf,f:,:fff:,                  .:fIIIIIII.          .IIIIIIIf:.                 .,:fff:,ff IIf,
       ,.fIIIf,:ffff,                   ,IIIIIII:,,.            .,,:IIIIIII.                  .:ffff:,IIII,:.
     ,III.::.,,,,,.                     IIIIII:                      ,IIIIII                     ,,,,,.,:,:IIf
     IIIII :ffIIf,                      IIIIII,                      .IIIIII                      :IIIf:,.IIIIf.
  ,II,fIf.:::,..                        IIIIII,                      .IIIIII                       ..,:::,,If::II
  IIIIf.  ,:fII:                       .IIIIII,                      .IIIIII.                       IIff:.  :IIII:
 ::IIIIf:IIIf: .                  ,::fIIIIIII,                        ,fIIIIIIf::,                   ,ffIII,IIIIf,,
:IIf:::    .,fI:                  IIIIIIIII:                            :IIIIIIIIf                  If:,    .::fIIf
 IIIIII, :IIIIf                     .,:IIIIIIf                        fIIIIII:,.                    ,IIIII. fIIIII:
 ,:IIIII ff:,   f,                      IIIIII,                      .IIIIII                      f.  .::f::IIIIf,.
 fIf::,,     ,fIII                      IIIIII,                      .IIIIII                     :III:      ,,:fII.
  fIIIIIIf, :IIIIf   ,                  IIIIII,                      .IIIIII                 .,  ,IIIII. :fIIIIII,
   .:IIIIIII,ff,    :II:                IIIIIIf                      fIIIIII               .fII.   .:ff:IIIIIIf,
     :fffff:,      IIIIIf   ,            :IIIIIIIfff            fffIIIIIII:           ..   IIIII:      ::fffff,
      .fIIIIIIIf:, fIIII,   ,IIf,           ,:ffIIII.          .IIIIff:,          .:fII    fIIII,.:ffIIIIIII:
         ,fIIIIIIIIIf:,     ,IIIII:  .,::,                               .,::,  .IIIIII      ::fIIIIIIIIf:.
             :fffffff,      .fIIIII,   .IIIIIf:                     ,:fIIII:    IIIIII:       :fffffff,
              .:fIIIIIIIIIIIIffffI:      IIIIIIII.                :IIIIIII:     .fIffffIIIIIIIIIIII:,
                   ,:fIIIIIIIIIIIf,       .:fIIIII               ,IIIIIf,        :IIIIIIIIIIIff,.
                         .:ffffffffIIIIIIIIIIIfff:.              ,ffffIIIIIIIIIIIfffffff:,
                             .,:ffIIIIIIIIIIIIIIIIf,   .,,,,.  .:fIIIIIIIIIIIIIIIIff:,.
                                       ....... .,,:fffff:.,:fffff:,.  .......
                                    ..,,:fffIIIIf:,.            .,:fIIIIff::,,..
                                   .IIIIIf:,.                          .,:fIIIII
                                     f,                                      ,f
</code>```

After running it through the image tool:

Anyway, here's the actual code.

//package cad97;

import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.awt.image.Raster;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import javax.imageio.ImageIO;

public final class AsciiArt {

    private static final Font LINUX_LIBERTINE = new Font("LinLibertine_DRah", Font.PLAIN, 20);
    private static final FontMetrics LL_METRICS = Toolkit.getDefaultToolkit().getFontMetrics(LINUX_LIBERTINE);
    // Toolkit::getFontMetrics is deprecated, but that's the only way to get FontMetrics without an explicit Graphics environment.
    // If there's a better way to get the widths of characters, please tell me.

    public static void main(String[] args) throws IOException {
        File jar = new java.io.File(AsciiArt.class.getProtectionDomain().getCodeSource().getLocation().getPath());
        if (args.length != 1) {
            String jarName = jar.getName();
            System.out.println("Usage: java -jar " + jarName + " file");
        } else {
            File image = new File(args[0]);
            try (InputStream input = new FileInputStream(image)) {
                String art = createAsciiArt(ImageIO.read(input), LINUX_LIBERTINE, LL_METRICS);
                System.out.print(art); // If you want to save as a file, change this.
            } catch (FileNotFoundException fnfe) {
                System.out.println("Unable to find file " + image + ".");
                System.out.println("Please note that you need to pass the full file path.");
            }
        }
    }

    private static String createAsciiArt(BufferedImage image, Font font, FontMetrics metrics) {
        final int height = metrics.getHeight();
        final Map<Character,Integer> width = new HashMap<>();
        for (char c=32; c<127; c++) { width.put(c, metrics.charWidth(c)); }

        StringBuilder art = new StringBuilder();

        for (int i=0; i<=image.getHeight(); i+=height) {
            final int tempHeight = Math.min(height, image.getHeight()-i);
            art.append(createAsciiLine(image.getSubimage(0, i, image.getWidth(), tempHeight), width));
        }

        return art.toString();
    }

    private static String createAsciiLine(BufferedImage image, Map<Character,Integer> charWidth) {
        if (image.getWidth()<6) return "\n";
        /*
        I'm passing in the charWidth Map because I could use it, and probably a later revision if I
        come back to this will actually use non-6-pixel-wide characters. As is, I'm only using the
        6-pixel-wide characters for simplicity. They are those in this set: { !,./:;I[\]ft|}
        */
        assert charWidth.get(' ') == 6; assert charWidth.get('!') == 6;
        assert charWidth.get(',') == 6; assert charWidth.get('.') == 6;
        assert charWidth.get('/') == 6; assert charWidth.get(':') == 6;
        assert charWidth.get(';') == 6; assert charWidth.get('I') == 6;
        assert charWidth.get('[') == 6; assert charWidth.get('\\') == 6;
        assert charWidth.get(']') == 6; assert charWidth.get('f') == 6;
        assert charWidth.get('t') == 6; assert charWidth.get('|') == 6;

        // Measure whiteness of 6-pixel-wide sample
        Raster sample = image.getData(new Rectangle(6, image.getHeight()));
        int whiteCount = 0;
        for (int x=sample.getMinX(); x<sample.getMinX()+sample.getWidth(); x++) {
            for (int y=sample.getMinY(); y<sample.getMinY()+sample.getHeight(); y++) {
                int pixel = sample.getPixel(x, y, new int[1])[0];
                whiteCount += pixel==1?0:1;
            }
        }

        char next;

        int area = sample.getWidth()*sample.getHeight();

        if (whiteCount > area*0.9) {
            next = ' ';
        } else if (whiteCount > area*0.8) {
            next = '.';
        } else if (whiteCount > area*0.65) {
            next = ',';
        } else if (whiteCount > area*0.5) {
            next = ':';
        } else if (whiteCount > area*0.3) {
            next = 'f';
        } else {
            next = 'I';
        }

        return next + createAsciiLine(image.getSubimage(charWidth.get(','), 0, image.getWidth()-sample.getWidth(), image.getHeight()), charWidth);
    }

}
```

<p>Compile:</p>

<ul>
<li>Make sure you have the JDK installed</li>
<li>Make sure that the JDK bin is on your PATH (for me it's <code>C:\Program Files\Java\jdk1.8.0_91\bin</code>)</li>
<li>Save the file as <code>AsciiArt.java</code></li>
<li><code>javac AsciiArt.java</code></li>
<li><code>jar cvfe WhateverNameYouWant.jar AsciiArt AsciiArt.class</code></li>
</ul>

<p>Usage: <code>java -jar WhateverNameYouWant.jar C:\full\file\path.png</code>, prints to STDOUT</p>

<p>REQUIRES the source file to be saved with 1-bit depth and the sample for a white pixel to be <code>1</code>.</p>

<p>Scoring output:</p>

<pre class="lang-none prettyprint-override"><code>corp/board.png: 0.6384
corp/Doppelspalt.png: 0.605746
corp/down.png: 1.012326
corp/img2.png: 0.528794
corp/pcgm.png: 0.243618
corp/peng.png: 0.440982
corp/phi.png: 0.929552
corp/text2image.png: 0.165276
Score: 0.57058675
</code>```

Title: Generate ASCII Art

Body:
Java, score 0.57058675

This is actually my first time doing image manipulation so it's kind of awkward but I think it turned out OK.

I couldn't get dssim to work on my machine, but I was able to make images using PIL.

Interestingly, the font tells me in Java that each of the characters I'm using are width 6. You can see that in my program FontMetrics::charWidth is 6 for all characters that I have used. The {} logo looks pretty decent in a monospace font. But for some reason the lines do not actually line up in the full text file. I blame ligatures. (And yes, I should be using the correct font.)

In monospaced font:

                                                                                .
                         .,:ff:,                                                   ,:fff::,.
                ,ff .fIIIIIf,                                                         .:fIIIIIf.:f:.
            .,:III: ,ff::                       ..,,            ,,..                      ,:fff, IIII.,
          :IIf,f:,:fff:,                  .:fIIIIIII.          .IIIIIIIf:.                 .,:fff:,ff IIf,
       ,.fIIIf,:ffff,                   ,IIIIIII:,,.            .,,:IIIIIII.                  .:ffff:,IIII,:.
     ,III.::.,,,,,.                     IIIIII:                      ,IIIIII                     ,,,,,.,:,:IIf
     IIIII :ffIIf,                      IIIIII,                      .IIIIII                      :IIIf:,.IIIIf.
  ,II,fIf.:::,..                        IIIIII,                      .IIIIII                       ..,:::,,If::II
  IIIIf.  ,:fII:                       .IIIIII,                      .IIIIII.                       IIff:.  :IIII:
 ::IIIIf:IIIf: .                  ,::fIIIIIII,                        ,fIIIIIIf::,                   ,ffIII,IIIIf,,
:IIf:::    .,fI:                  IIIIIIIII:                            :IIIIIIIIf                  If:,    .::fIIf
 IIIIII, :IIIIf                     .,:IIIIIIf                        fIIIIII:,.                    ,IIIII. fIIIII:
 ,:IIIII ff:,   f,                      IIIIII,                      .IIIIII                      f.  .::f::IIIIf,.
 fIf::,,     ,fIII                      IIIIII,                      .IIIIII                     :III:      ,,:fII.
  fIIIIIIf, :IIIIf   ,                  IIIIII,                      .IIIIII                 .,  ,IIIII. :fIIIIII,
   .:IIIIIII,ff,    :II:                IIIIIIf                      fIIIIII               .fII.   .:ff:IIIIIIf,
     :fffff:,      IIIIIf   ,            :IIIIIIIfff            fffIIIIIII:           ..   IIIII:      ::fffff,
      .fIIIIIIIf:, fIIII,   ,IIf,           ,:ffIIII.          .IIIIff:,          .:fII    fIIII,.:ffIIIIIII:
         ,fIIIIIIIIIf:,     ,IIIII:  .,::,                               .,::,  .IIIIII      ::fIIIIIIIIf:.
             :fffffff,      .fIIIII,   .IIIIIf:                     ,:fIIII:    IIIIII:       :fffffff,
              .:fIIIIIIIIIIIIffffI:      IIIIIIII.                :IIIIIII:     .fIffffIIIIIIIIIIII:,
                   ,:fIIIIIIIIIIIf,       .:fIIIII               ,IIIIIf,        :IIIIIIIIIIIff,.
                         .:ffffffffIIIIIIIIIIIfff:.              ,ffffIIIIIIIIIIIfffffff:,
                             .,:ffIIIIIIIIIIIIIIIIf,   .,,,,.  .:fIIIIIIIIIIIIIIIIff:,.
                                       ....... .,,:fffff:.,:fffff:,.  .......
                                    ..,,:fffIIIIf:,.            .,:fIIIIff::,,..
                                   .IIIIIf:,.                          .,:fIIIII
                                     f,                                      ,f

After running it through the image tool:

Anyway, here's the actual code.

//package cad97;

import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.awt.image.Raster;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import javax.imageio.ImageIO;

public final class AsciiArt {

    private static final Font LINUX_LIBERTINE = new Font("LinLibertine_DRah", Font.PLAIN, 20);
    private static final FontMetrics LL_METRICS = Toolkit.getDefaultToolkit().getFontMetrics(LINUX_LIBERTINE);
    // Toolkit::getFontMetrics is deprecated, but that's the only way to get FontMetrics without an explicit Graphics environment.
    // If there's a better way to get the widths of characters, please tell me.

    public static void main(String[] args) throws IOException {
        File jar = new java.io.File(AsciiArt.class.getProtectionDomain().getCodeSource().getLocation().getPath());
        if (args.length != 1) {
            String jarName = jar.getName();
            System.out.println("Usage: java -jar " + jarName + " file");
        } else {
            File image = new File(args[0]);
            try (InputStream input = new FileInputStream(image)) {
                String art = createAsciiArt(ImageIO.read(input), LINUX_LIBERTINE, LL_METRICS);
                System.out.print(art); // If you want to save as a file, change this.
            } catch (FileNotFoundException fnfe) {
                System.out.println("Unable to find file " + image + ".");
                System.out.println("Please note that you need to pass the full file path.");
            }
        }
    }

    private static String createAsciiArt(BufferedImage image, Font font, FontMetrics metrics) {
        final int height = metrics.getHeight();
        final Map<Character,Integer> width = new HashMap<>();
        for (char c=32; c<127; c++) { width.put(c, metrics.charWidth(c)); }

        StringBuilder art = new StringBuilder();

        for (int i=0; i<=image.getHeight(); i+=height) {
            final int tempHeight = Math.min(height, image.getHeight()-i);
            art.append(createAsciiLine(image.getSubimage(0, i, image.getWidth(), tempHeight), width));
        }

        return art.toString();
    }

    private static String createAsciiLine(BufferedImage image, Map<Character,Integer> charWidth) {
        if (image.getWidth()<6) return "\n";
        /*
        I'm passing in the charWidth Map because I could use it, and probably a later revision if I
        come back to this will actually use non-6-pixel-wide characters. As is, I'm only using the
        6-pixel-wide characters for simplicity. They are those in this set: { !,./:;I[\]ft|}
        */
        assert charWidth.get(' ') == 6; assert charWidth.get('!') == 6;
        assert charWidth.get(',') == 6; assert charWidth.get('.') == 6;
        assert charWidth.get('/') == 6; assert charWidth.get(':') == 6;
        assert charWidth.get(';') == 6; assert charWidth.get('I') == 6;
        assert charWidth.get('[') == 6; assert charWidth.get('\\') == 6;
        assert charWidth.get(']') == 6; assert charWidth.get('f') == 6;
        assert charWidth.get('t') == 6; assert charWidth.get('|') == 6;

        // Measure whiteness of 6-pixel-wide sample
        Raster sample = image.getData(new Rectangle(6, image.getHeight()));
        int whiteCount = 0;
        for (int x=sample.getMinX(); x<sample.getMinX()+sample.getWidth(); x++) {
            for (int y=sample.getMinY(); y<sample.getMinY()+sample.getHeight(); y++) {
                int pixel = sample.getPixel(x, y, new int[1])[0];
                whiteCount += pixel==1?0:1;
            }
        }

        char next;

        int area = sample.getWidth()*sample.getHeight();

        if (whiteCount > area*0.9) {
            next = ' ';
        } else if (whiteCount > area*0.8) {
            next = '.';
        } else if (whiteCount > area*0.65) {
            next = ',';
        } else if (whiteCount > area*0.5) {
            next = ':';
        } else if (whiteCount > area*0.3) {
            next = 'f';
        } else {
            next = 'I';
        }

        return next + createAsciiLine(image.getSubimage(charWidth.get(','), 0, image.getWidth()-sample.getWidth(), image.getHeight()), charWidth);
    }

}

Compile:

Make sure you have the JDK installed

Make sure that the JDK bin is on your PATH (for me it's C:\Program Files\Java\jdk1.8.0_91\bin)

Save the file as AsciiArt.java

javac AsciiArt.java

jar cvfe WhateverNameYouWant.jar AsciiArt AsciiArt.class

Usage: java -jar WhateverNameYouWant.jar C:\full\file\path.png, prints to STDOUT

REQUIRES the source file to be saved with 1-bit depth and the sample for a white pixel to be 1.

Scoring output:

corp/board.png: 0.6384
corp/Doppelspalt.png: 0.605746
corp/down.png: 1.012326
corp/img2.png: 0.528794
corp/pcgm.png: 0.243618
corp/peng.png: 0.440982
corp/phi.png: 0.929552
corp/text2image.png: 0.165276
Score: 0.57058675


问:
Find the Cheese
Update: There are 6 mazes. They are included in the controller. There is a tar.gz of the mazes and their .bmp files here (dropbox). There is also a utility for making more mazes at that link (the maze_4.txt file is incorrect in archive). At this point, please feel free to run your own entry and update your score. Details on how to do so are included at the bottom. If you have questions or trouble, please ping me in chat.

You're a mouse. You're in a maze. Find the cheese.

Concept

You are in a maze that exists on a rectangular grid. Each space of the grid contains one of several things:

! - An impassable wall

  - An empty space, which is traversable

O - You, the mouse

+ - The cheese, your goal

Please use the same characters so that I do not have to modify the controller.

On each turn, you will be given the tiles that are North, South, East, and West of your current position. You must then output the direction that you wish to travel. You win when you get to the cheese. Fewer steps is better.

Input

You will be given input through stdin in the following fashion: nesw, where each letter represents the tile at that compass point. For example, if the current state looks like

```<code>  !          <--- Wall
 !O          <--- You
  +          <--- Cheese
</code>```

then you will be given the string ! +!.

At the end of the game, the controller will send you a string of four zeroes: 0000. Upon receiving this string, your program should terminate. No other input given will contain the 0 character.

Please ignore all other inputs.

Output

You are to output one letter n, s, e, or w, to indicate which direction you want to travel, followed by a new line character.

Scoring

Your score on each test is the number of steps it takes you to find the cheese.

Your overall score will be the sum of your average score per maze across a battery of mazes of variable sizes, all of which will fit inside a square of length 50.

For example, if it takes your bot 100 moves to complete each of the 6 mazes, then your score is 600.

If your bot is not deterministic, please try each maze 10 times and use average as the score for that maze. Your final score will be the sum of all the averages.

Rules

Each maze will fit inside a 50x50 square.

Each maze will have at least one valid path from start to cheese.

Each maze will be entirely walled in, except that the cheese will always be on the outer wall so that it essentially serves as an exit to the maze.

If you run into a wall, your submission is disqualified.

If your submission takes too long (as determined by me, as I start testing), it will be disqualified. This is in large part to prevent infinite loops. The soft limit will be one minute per maze, although I reserve the right to change this at any time in either direction.

Entries need not be deterministic, but if you are too random, you will likely be disqualified by the above point.

At some point, the battery of mazes will be released, future answers may not optimize toward them, and they are subject to change.

Submissions:

Your submission is a full program that takes input via stdin and output via stdout. This is important because the submission will be interacting with the maze controller. I'm not going to ban languages that are not freely available, but know that someone else will have to offer their time to run the tests if I do not have access to the language.

Please include instructions on how to run your submission.

Please state whether your submission is deterministic or not, so that I know whether I need to run it multiple times.

Test Mazes

In the test mazes, . characters outline the shortest route to the cheese. They are the same as the  (space) character. They are not visible to your submission. The controller replaces them with spaces.

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

31x31 test maze. Shamelessly stolen.

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

Controller

The controller is in Rust (1.11 Nightly)

    type Maze = Vec<Vec<char>>;

fn str_to_maze(input: &str) -> Result<Maze,i32> {
    let mut maze: Vec<Vec<char>> = vec![ vec![] ];
    let mut row: Vec<char> = vec![];

    for c in input.chars() {
        if c == '!' || c == '+' || c == 'O'  || c == ' ' {
            row.push(c);
        }
        else if c =='.' {
            row.push(' ');
        }
        else if c == '#' {
            maze.push(row);
            row = vec![];
        }
        else if c =='\0' {
            break;
        }
        else {
            println!("Bad character in maze: {}, exiting.", c);
            return Err(1);
        }
    }
    return Ok(maze);
}

fn display_maze(maze: &Maze, position: [usize;2]) {
    for y in 0..maze.len() {
        for x in 0..maze[y].len() {
            if [x,y] == position {
                print!("O");
            }
            else if maze[y][x] == '#' {
                println!("\n");
            }
            else {
                print!("{}",maze[y][x]);
            }
        }
        println!("");
    }
    println!("\n");
}

fn get_starting_position(maze: &mut Maze) -> Result<[usize;2],&str> {
    for y in 0..maze.len() {
        for x in 0..maze[y].len() {
            if maze[y][x] == 'O' {
                maze[y][x] = ' ';
                return Ok([x,y]);
            }
        }
    }
    return Err("No mouse found");
}

enum State {
    Continue([char;4]),
    Win,
    Disqualify,
}

fn output(maze: &Maze, position: [usize;2]) -> State {
    let x = position[0];
    let y = position[1];
    if maze[y][x] == '+' {
        return State::Win;
    }
    else if maze[y][x] == '!' {
        return State::Disqualify;
    }

    let n = maze[y-1][x];

    assert!(y+1<maze.len());
    let s = maze[y+1][x];

    let w = maze[y][x-1];

    assert!(x+1<maze[y].len());
    let e = maze[y][x+1];

    return State::Continue([n,e,s,w]);
}

fn get_input() -> char {
    use std::io;
    use std::io::Read;
    let mut buffer: [u8;2] = [0;2];
    io::stdin().read_exact(&mut buffer).unwrap();
    //println!("{:?}", buffer); // to see exactly what the input is
    return buffer[0] as char;
}

fn next_position(current_position: [usize;2], direction: char) -> Result<[usize;2],char> {
    let mut x = current_position[0];
    let mut y = current_position[1];
    if direction == 'n' {
        y -= 1;
    }
    else if direction == 'e' {
        x += 1;
    }
    else if direction == 's' {
        y += 1;
    }
    else if direction == 'w' {
        x -= 1;
    }
    else {
        return Err(direction);
    }
    return Ok([x,y]);
}

fn play(maze: &mut Maze) -> (State, usize) {
    let mut position: [usize;2];
    match get_starting_position(maze) {
        Ok(pos) => position = pos,
        Err(s) => {
            println!("{}",s);
            std::process::exit(2);
        }
    }

    let mut moves = 0;

    loop {

        let state = output(maze, position);

        /* uncomment below to view the maze at each step  */
        //display_maze(&maze, position);
        /* ----------------------------------------------*/

        match state {
            State::Win => {
                //println!("You found the cheese");
                return(State::Win, moves);
            }
            State::Disqualify => {
                //println!("You were disqualified");
                return(State::Disqualify, moves);
            }
            State::Continue(out) => {
                println!("{}{}{}{}",out[0],out[1],out[2],out[3]);
            }
        }
        // only get here with Continue
        let input = get_input();
        moves += 1;
        match next_position(position, input) {
            Err(c) => {
                println!("Invalid input: {}", c as u8);
                return (State::Disqualify, moves);
            }
            Ok(next_pos) => position = next_pos,
        }
    }
}

fn main() {

    let mut arg_counter = 0;
    for argument in std::env::args() {
        if arg_counter != 0 {

            let mut maze = match argument.as_str(){
                "1" => maze_1(),
                "2" => maze_2(),
                "3" => maze_3(),
                "4" => maze_4(),
                "5" => maze_5(),
                "6" => maze_6(),
                _ => {
                    println!("invalid input: {}, breaking", argument);
                    break;
                }

            };

            let game_result = play(&mut maze);

            println!("0000");
            match game_result.0 {
                State::Win => println!("WIN"),
                State::Disqualify => println!("DISQUALIFY"),
                _ => println!("Error"),
            }
            println!("moves: {}", game_result.1 );
        }
        arg_counter += 1;
    }

}

fn maze_1() -> Maze {
    let maze_str = "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!#\
                    !O !                    !      !#\
                    !. ! !!!!!!!!!!!!!!!!!! ! !!!!!!#\
                    !. !                    ! !    !#\
                    !. ! !!!!!!!!!!!!!!!!!!!! ! !! !#\
                    !. !...........           ! !!.+#\
                    !. !.!!!!!!!!!.!!!!!!!!!!!!!!!.!#\
                    !.!..!        ...............!.!#\
                    !.!.!! !!!!!!!!!!!!!!!!!!!!!.!.!#\
                    !.!.!! !!!  !               .!.!#\
                    !.!.!! !!!  !!!!!!!!!!!!!!!!.!.!#\
                    !...!! !!!                  .!.!#\
                    ! ! !! !!!                  .!.!#\
                    ! ! !! !!!  !!!!!!!!! !!!!!!.!.!#\
                    ! ! !! !!!  !      !! !     .!.!#\
                    ! ! !! !!!  ! !!!!!!! !     .!.!#\
                    ! ! !! !!!  !      !! !     .!.!#\
                    ! ! !! !!!  !      !! !     .!.!#\
                    ! ! !!   !  !      !! !     .!.!#\
                    ! ! !! ! !  !!!!!! !! !     .!.!#\
                    ! ! !! ! !  !      !! !     ...!#\
                    ! ! !! ! !  !      !! !        !#\
                    ! ! !! ! !  !      !! !      ! !#\
                    ! ! !! ! !  !  !!!!!! !      ! !#\
                    ! ! !! ! !  !      !! !      ! !#\
                    ! !    !    !      !! !      ! !#\
                    ! !!!!!!  !!!!!!!! !! !      ! !#\
                    !                ! !! !      ! !#\
                    ! !!!!!!!!!!! !!!! !! !      ! !#\
                    !                     !      ! !#\
                    ! !!!!!!!! !!!!       !        !#\
                    !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!#\
                    ";

    match str_to_maze(&maze_str) {
        Ok(x) => return x,
        Err(i) => std::process::exit(i),
    }
}

fn maze_2() -> Maze {
    let maze_str = "!!!!!!!!!!!!!!!#\
                    !      .......!#\
                    ! !!! !.!!!! .!#\
                    !   ! !.!!O!!.!#\
                    !!!   !....! .!#\
                    !   !!!!!!!!!.!#\
                    ! !!        ..!#\
                    !  !!!!!!!!!.!!#\
                    !           ..+#\
                    !!!!!!!!!!!!!!!#\
                    ";

    match str_to_maze(&maze_str) {
        Ok(x) => return x,
        Err(i) => std::process::exit(i),
    }
}

fn maze_3() -> Maze {
    let maze_str = "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!#\
                    !                            !!!#\
                    ! !  !!!  !!!!!!!!!!!!!!!!!!   !#\
                    ! !  ! !!!              !!!  ! !#\
                    ! !  ! !!!!!!!!!!!!!!!!     !! !#\
                    ! !  !                  !!!!   !#\
                    ! !! !!!!!!!!!!        !!    ! !#\
                    !  ! !        !!!! !!!!!   !!! !#\
                    !! ! ! !!!!      !         !   !#\
                    !! ! ! !!!!   !!!!!!!!!!!!!! ! !#\
                    !! ! ! !!!! ! !              ! !#\
                    !! ! ! !!!! ! ! !!!!       ! ! !#\
                    !! ! ! !!!! ! ! !   !!!    ! ! !#\
                    !  ! ! !!!! ! ! !     !!!  ! ! !#\
                    !  ! ! !!!! ! ! !!!!!      !   !#\
                    !  ! ! !!!! !!! !   !!     ! !!!#\
                    !  ! !  !!!  !! !    !!!   ! !!!#\
                    !  ! !     ! !! !!!!   !!  ! !!!#\
                    !  ! !!    ! !! !  !!      ! !!!#\
                    !  !  !   !! !!     !!!    ! !!!#\
                    !  !! !!!!     !!!    !!   !   !#\
                    !!  ! !! !       !!!   !!  !!! !#\
                    !!  !    !    !    !           !#\
                    !!  !!!!!!    !!   !!!!!!!!!!! !#\
                    !             !!!! !!!!!!!!!!! !#\
                    !  ..........O!!!! !!!!!!!!!!!.+#\
                    !! .!!!!!!    !!   !!!!!!!!!!!.!#\
                    !! .!    !    !    !          .!#\
                    !!..! !! !       !!!   !!  !!!.!#\
                    ! .!! !!!!     !!!    !!   !...!#\
                    ! .!  !   !! !!     !!!    !.!!!#\
                    ! .! !!    ! !! !  !!      !.!!!#\
                    ! .! !     ! !! !!!!   !!  !.!!!#\
                    ! .! !  !!!  !! !    !!!   !.!!!#\
                    ! .! ! !!!! !!! !   !!     !.!!!#\
                    ! .! ! !!!! ! ! !!!!!      !...!#\
                    ! .! ! !!!! ! ! !     !!!  ! !.!#\
                    !!.! ! !!!! ! ! !   !!!    ! !.!#\
                    !!.! ! !!!! ! ! !!!!       ! !.!#\
                    !!.! ! !!!! ! !              !.!#\
                    !!.! ! !!!!   !!!!!!!!!!!!!! !.!#\
                    !!.! ! !!!!      !         !  .!#\
                    !..! !        !!!! !!!!!   !!!.!#\
                    !.!! !!!!!!!!!!        !!    !.!#\
                    !.!  !                  !!!!  .!#\
                    !.!  ! !!!!!!!!!!!!!!!!     !!.!#\
                    !.!  ! !!!              !!!  !.!#\
                    !.!  !!!  !!!!!!!!!!!!!!!!!!...!#\
                    !............................!!!#\
                    !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!#\
                    ";

    match str_to_maze(&maze_str) {
        Ok(x) => return x,
        Err(i) => std::process::exit(i),
    }
}

fn maze_4() -> Maze {
    let maze_str = "!!!!!!!!!!!!!!!!!+!!!!!!!!!!!!!!#\
                    !.................           !!!#\
                    !.!  !!!  !!!!!!!!!!!!!!!!!!   !#\
                    !.!  ! !!!              !!!  ! !#\
                    !.!  ! !!!!!!!!!!!!!!!!     !! !#\
                    !.!  !                  !!!!   !#\
                    !.!! !!!!!!!!!!        !!    ! !#\
                    !..! !        !!!! !!!!!   !!! !#\
                    !!.! ! !!!!      !         !   !#\
                    !!.! ! !!!!   !!!!!!!!!!!!!! ! !#\
                    !!.! ! !!!! ! !              ! !#\
                    !!.! ! !!!! ! ! !!!!       ! ! !#\
                    !!.! ! !!!! ! ! !   !!!    ! ! !#\
                    ! .! ! !!!! ! ! !     !!!  ! ! !#\
                    ! .! ! !!!! ! ! !!!!!      !   !#\
                    ! .! ! !!!! !!! !   !!     ! !!!#\
                    ! .! !  !!!  !! !    !!!   ! !!!#\
                    ! .! !     ! !! !!!!   !!  ! !!!#\
                    ! .! !!    ! !! !  !!      ! !!!#\
                    ! .!  !   !! !!     !!!    ! !!!#\
                    ! .!! !!!!     !!!    !!   !   !#\
                    !!. ! !! !       !!!   !!  !!! !#\
                    !!. !    !    !    !           !#\
                    !!. !!!!!!    !!   !!!!!!!!!!! !#\
                    ! ........... !!!! !!!!!!!!!!! !#\
                    !           . !!!! !!!!!!!!!!! !#\
                    !!  !!!!!!  . !!   !!!!!!!!!!! !#\
                    !!  !    !  . !    !           !#\
                    !!  ! !! !  .    !!!   !!  !!! !#\
                    !  !! !!!!  .  !!!    !!   !   !#\
                    !  !  !   !!.!!     !!!    ! !!!#\
                    !  ! !!    !.!! !  !!      ! !!!#\
                    !  ! !     !.!! !!!!   !!  ! !!!#\
                    !  ! !  !!!..!! !    !!!   ! !!!#\
                    !  ! ! !!!!.!!! !   !!     ! !!!#\
                    !  ! ! !!!!.! ! !!!!!      !   !#\
                    !  ! ! !!!!.! ! !     !!!  ! ! !#\
                    !! ! ! !!!!.! ! !   !!!    ! ! !#\
                    !! ! ! !!!!.! ! !!!!       ! ! !#\
                    !! ! ! !!!!.! !              ! !#\
                    !! ! ! !!!!.  !!!!!!!!!!!!!! ! !#\
                    !! ! ! !!!!.....O!         !   !#\
                    !  ! !        !!!! !!!!!   !!! !#\
                    ! !! !!!!!!!!!!        !!    ! !#\
                    ! !  !                  !!!!   !#\
                    ! !  ! !!!!!!!!!!!!!!!!     !! !#\
                    ! !  ! !!!              !!!  ! !#\
                    ! !  !!!  !!!!!!!!!!!!!!!!!!   !#\
                    !                            !!!#\
                    !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!#\
                    ";

    match str_to_maze(&maze_str) {
        Ok(x) => return x,
        Err(i) => std::process::exit(i),
    }
}

fn maze_5() -> Maze {
    let maze_str = "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!#\
                    +......!!!!       !!!        !!!       !!!!     !!#\
                    !     .!       !!                            !!!!!#\
                    !  !!!.! !!      !!!  !!!!  !!!!!!!!!      !!!   !#\
                    ! !!...!   !!!!!   !!    !          !!    !!     !#\
                    !!!..!!         !    !!  !           !    !     !!#\
                    !! .!!........        !! !!!     !    !   !  !  !!#\
                    !!!. !.  !  !.   !      !!!!!    !!   !   ! !! !!!#\
                    !!!. !.  !  !.   !       !!!!!    !   !!    !  !!!#\
                    !!.. !.  !  !..  !        !  !    !!   !    !   !!#\
                    !!.! !.!  ! ! ..  ! !!!!!!  !      !   !    !   !!#\
                    !!.! !.!  ! !! .  ! !      !        !  !    !   !!#\
                    !!.! !.!  !  ! .  ! !!   !!    !!!! !  !    !   !!#\
                    !!.! !.!! !  ! .  !  !!!   !!!!     !  !    !!  !!#\
                    !!.! !. ! !  ! .  !    !!        !  !   !    !  !!#\
                    ! .!!!. ! !  !!.   !    !        !  !   !    !   !#\
                    ! .!!!. ! !   !.   !     !       !   !  !    !   !#\
                    ! .! !. ! !   !.   !     !       !   !   !   !   !#\
                    ! .! !. ! !!  !....!!!   !      !!   !     ! !   !#\
                    ! .!  ..!  !  !   ...!!!!       !    !     ! ! ! !#\
                    ! .!   .!  !  !!!!!!.... !!!!!!!             ! ! !#\
                    ! .! !!.!  !! !  !!!!  .!                        !#\
                    ! .!!!!.!   !!!! !!!   .!   !!!!!   !!!!!!!!!!!  !#\
                    ! .. !!.!    !!!  !!  !.!!                       !#\
                    !!!.. !. !   !!!      !..!        !!!   !   !    !#\
                    !!! .... !  !!!!      ! .!        !             !!#\
                    !!!!!!!!!!!!!!!!!!!!!!! .! !!!!!!!!!!!!!!!!!!!! !!#\
                    !!!  !                  .!                     !!!#\
                    !!   !   !!!  !!        .!                      !!#\
                    !!   !  !     !!  !!!!!!.!  !!!!!!              !!#\
                    !!   !  !    !!   !!!!!!.! !!!!!!!!          !  !!#\
                    !!  !   !   !!   !!!!!!!.! !!!!!! !!   !  !     !!#\
                    !!  !   !   !   !!!!!!!!.! !!!  !  !   !        !!#\
                    !!  !   !   !  !!!!!!!!!.! !!!! !   !  !  !  !  !!#\
                    !!  !   !   !           .!  !!  !   !  !     !  !!#\
                    !! !!!  !   !   !!!!!!  .!      !    !!         !!#\
                    !! ! !   !  !   !     !!. !    !!!    !    !    !!#\
                    !! ! !   !  !   ! !     .  !   ! !!    !     !  !!#\
                    !! ! !   !  !   ! !!  !!.   !!!   !!   !   ! !  !!#\
                    !! ! !   !  !!  ! !!! ! .....     !!   !      ! !!#\
                    !! ! !   !   !  ! !!!!!!!   .     !    !        !!#\
                    !  ! !   !   !  !  !!!  !   .!!!!     !  !       !#\
                    !  ! !   !   !! !       !   .!      !!.......... !#\
                    ! !! !   !    !  !!!!!!!!!  .!    !!  .!   !!!!. !#\
                    ! !  !   !    !!       !!!  .!!!!!   ..   !    . !#\
                    ! !  !    !!   !!!     !!!  .......... !!!!    . !#\
                    ! !  !     !!     !!!!      !!!!!!!!!!!!      !. !#\
                    ! !         !         !!!!!!                  O. !#\
                    !           !                                    !#\
                    !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!#\
                    ";

    match str_to_maze(&maze_str) {
        Ok(x) => return x,
        Err(i) => std::process::exit(i),
    }
}

fn maze_6() -> Maze {
    let maze_str = "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!#\
                    !      !!!!   ....!!!        !!!       !!!!     !!#\
                    !      !      .!!..........                  !!!!!#\
                    !  !!! ! !!   ...!!!  !!!!. !!!!!!!!!      !!!   !#\
                    ! !!   !   !!!!!.. !!    !.         !!    !!     !#\
                    !!!  !!         !.   !!  !.....      !    !     !!#\
                    !!  !!          ..    !! !!!  .  !    !   !  !  !!#\
                    !!!  !   !  !   .!      !!!!! .  !!   !   ! !! !!!#\
                    !!!  !   !  !   .!       !!!!!.   !   !!    !  !!!#\
                    !!   !   !  !   .!        !  !.   !!   !    !   !!#\
                    !! ! ! !  ! !   . ! !!!!!!  ! ..   !   !    !   !!#\
                    !! ! ! !  ! !!  . ! !      !   .....!  !    !   !!#\
                    !! ! ! !  !  !  . ! !!   !!    !!!!.!  !    !   !!#\
                    !! ! ! !! !  !  ..!  !!!   !!!!    .!  !    !!  !!#\
                    !! ! !  ! !  !   .!    !!        ! .!   !    !  !!#\
                    !  !!!  ! !  !!  . !    !        ! .!   !    !   !#\
                    !  !!!  ! !   !  ..!     !       ! . !  !    !   !#\
                    !  ! !  ! !   !   .!     !       ! . !   !   !   !#\
                    !  ! !  ! !!  !   .!!!   !      !! . !     ! !   !#\
                    !  !    !  !  !   ...!!!!       !  . !     ! ! ! !#\
                    !  !    !  !  !!!!!!.... !!!!!!!   .         ! ! !#\
                    !  ! !! !  !! !  !!!!  .!          .             !#\
                    !  !!!! !   !!!! !!!   .!   !!!!!  .!!!!!!!!!!!  !#\
                    !    !! !    !!!  !!  !.!!..........             !#\
                    !!!   !  !   !!!      !. !.       !!!   !   !    !#\
                    !!!      !  !!!!      !. !.       !             !!#\
                    !!!!!!!!!!!!!!!!!!!!!!!. !.!!!!!!!!!!!!!!!!!!!! !!#\
                    !!!  !                 . !.....................!!!#\
                    !!   !   !!!  !!  O..... !                    ..!!#\
                    !!   !  !     !!  !!!!!! !  !!!!!!             .!!#\
                    !!   !  !    !!   !!!!!! ! !!!!!!!!          ! .!!#\
                    !!  !   !   !!   !!!!!!! ! !!!!!! !!   !  !    .!!#\
                    !!  !   !   !   !!!!!!!! ! !!!  !  !   !       .!!#\
                    !!  !   !   !  !!!!!!!!! ! !!!! !   !  !  !  ! .!!#\
                    !!  !   !   !            !  !!  !   !  !     ! .!!#\
                    !! !!!  !   !   !!!!!!   !      !    !!        .!!#\
                    !! ! !   !  !   !     !!  !    !!!    !    !   .!!#\
                    !! ! !   !  !   ! !        !   ! !!    !     ! .!!#\
                    !! ! !   !  !   ! !!  !!    !!!   !!   !   ! ! .!!#\
                    !! ! !   !  !!  ! !!! !           !!   !      !.!!#\
                    !! ! !   !   !  ! !!!!!!!         !    !       .!!#\
                    !  ! !   !   !  !  !!!  !    !!!!     !  !     . !#\
                    !  ! !   !   !! !       !    !      !!         . !#\
                    ! !! !   !    !  !!!!!!!!!   !    !!   !   !!!!. !#\
                    ! !  !   !    !!       !!!   !!!!!        !    . !#\
                    ! !  !    !!   !!!     !!!   !         !!!!    . !#\
                    ! !  !     !!     !!!!      !!!!!!!!!!!!      !..+#\
                    ! !         !         !!!!!!                     !#\
                    !           !              !                     !#\
                    !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!#\
                    ";

    match str_to_maze(&maze_str) {
        Ok(x) => return x,
        Err(i) => std::process::exit(i),
    }
}
```

<p>To test the larger maze, simply replace the maze string in the <code>maze_1</code> function. Make sure to append the correct <code>#\</code> characters to each line. </p>

<p><strong>Testing your entry</strong></p>

<p>This script can be used to test entries</p>

<pre class="lang-bash prettyprint-override"><code>#!/bin/bash

mkfifo /tmp/pipe1
mkfifo /tmp/pipe2

for arg in "$@"; do
    <path to controller> $arg < /tmp/pipe1 | tee /tmp/pipe2 trascript.txt &
    ( <path to entry> < /tmp/pipe2 | tee /tmp/pipe1 ) > /dev/null
done

rm /tmp/pipe1
rm /tmp/pipe2
</code>```

For example, my script looks like:

#!/bin/bash

mkfifo /tmp/pipe1
mkfifo /tmp/pipe2

for arg in "$@"; do
    ./maze/target/release/maze $arg < /tmp/pipe1 | tee /tmp/pipe2 trascript.txt &
    ( ./maze_test/main < /tmp/pipe2 | tee /tmp/pipe1 ) > /dev/null
done

rm /tmp/pipe1
rm /tmp/pipe2
```

<p>It is used in the following way:</p>

```./script <mazes to test>
```

<p>For example </p>

```./script 1 2 3 4 5 6
```

<p>It will print everything to the console as well as writing everything to a file called <code>transcript.txt</code></p>

<p>For the purpose of developing your entry, you can uncomment the </p>

```display_maze(&maze, position)
```

line in the play function. This will cause the controller to display the maze at each step.

答:
PHP 362 + 37 + 1638 + 1508 + 6696 + 1613 = 11854 steps

Ran benchmark on bug-fixed code:

```<code><?php

class Maze {
    public $map, $pos;
    public $prevPos = FALSE;
    public $intersections = [];

    public $n = 75, $e = 75, $w = 75, $s = 75;

    public function __construct() {
        // since we don't know where we start, build a 150x150 map and position ourselves at the middle
        $this->map = array_pad([], 150, array_pad([], 150, 0)); // 0 is unknown
        $this->pos = ['x'=> 75, 'y'=> 75];
    }

    public function play($input){
        $this->updateMap($input);
        $this->move();
    }

    private function updateField($x, $y, $inData) {
        if ($inData == '!' || $this->map[$x][$y] >= 1000) {                 // avoid overwriting our observations
            $this->map[$x][$y] = 1000;
            return;
        }

        // update our known borders
        if ($x <= $this->w) {
            $this->w = $x - 1;
        }
        elseif ($x >= $this->e) {
            $this->e = $x + 1;
        }
        elseif ($y <= $this->n) {
            $this->n = $y - 1;
        }
        elseif ($y >= $this->s) {
            $this->s = $y + 1;
        }

        if (!$this->map[$x][$y]) {
            $this->map[$x][$y] = $inData == '+' ? -1 : 1;
        }
    }

    private function checkForIntersection($input) {
        if (array_key_exists('x' . $this->pos['x'] . 'y' . $this->pos['y'], $this->intersections)) {
            if ($this->intersections['x' . $this->pos['x'] . 'y' . $this->pos['y']] > 0) {
                $this->intersections['x' . $this->pos['x'] . 'y' . $this->pos['y']] --;
                return TRUE;                                        // intersection already crossed
            }
        }
        elseif ($c = substr_count($input, ' ') > 2) {
            $this->intersections['x' . $this->pos['x'] . 'y' . $this->pos['y']] = $c - 1;
        }

        return FALSE;
    }

    private function updateMap($input) {
        if ($this->checkForIntersection($input)) {
            // if we're at a known intersection, we know that the path we come from lead nowhere
            $this->updateField($this->prevPos['x'], $this->prevPos['y'], '!');
        }

        // update discovered information
        $this->updateField($this->pos['x'], $this->pos['y'] - 1, $input[0]);
        $this->updateField($this->pos['x'] + 1, $this->pos['y'], $input[1]);
        $this->updateField($this->pos['x'], $this->pos['y'] + 1, $input[2]);
        $this->updateField($this->pos['x'] - 1, $this->pos['y'], $input[3]);
    }

    private function move() {
        if ($this->prevPos) {

            $this->map[$this->prevPos['x']][$this->prevPos['y']] ++;    // count times stepped on
        }

        $best = ['w' => 1000];

        foreach ([
            ['x' => $this->pos['x'], 'y' => $this->pos['y'] - 1, 'w' => $this->map[$this->pos['x']][$this->pos['y'] - 1], 'd' => 'n'],
            ['x' => $this->pos['x'] + 1, 'y' => $this->pos['y'], 'w' => $this->map[$this->pos['x'] + 1][$this->pos['y']], 'd' => 'e'],
            ['x' => $this->pos['x'], 'y' => $this->pos['y'] + 1, 'w' => $this->map[$this->pos['x']][$this->pos['y'] + 1], 'd' => 's'],
            ['x' => $this->pos['x'] - 1, 'y' => $this->pos['y'], 'w' => $this->map[$this->pos['x'] - 1][$this->pos['y']], 'd' => 'w']]
        as $direction) {
            if ($direction['w'] < $best['w'] || ($direction['w'] == $best['w'] && $best['w'] < 1000 && max($this->e - $direction['x'],  $direction['x'] - $this->w, $direction['y'] - $this->n, $this->s - $direction['y']) > max($best['x'] - $this->e, $this->w - $best['x'], $best['y'] - $this->n, $this->s - $best['y']))) {
            // encourage searching for borders which will later allow to block certain dead end paths without walking them
            // testing with middle search instead
                $best = $direction;
            }
        }

        echo $best['d'] . "\n";

        $this->prevPos = $this->pos;
        $this->pos = $best;
    }
}

$maze = new Maze();

while (strncmp(($input = fgets(STDIN)), '0000', 4)) {
    $len = strlen($input);
    if (($len > 6) || $len < 3) { continue; }

    $maze->play($input);
}
</code>```

Title: Find the Cheese

Body:
PHP 362 + 37 + 1638 + 1508 + 6696 + 1613 = 11854 steps

Ran benchmark on bug-fixed code:

<?php

class Maze {
    public $map, $pos;
    public $prevPos = FALSE;
    public $intersections = [];

    public $n = 75, $e = 75, $w = 75, $s = 75;

    public function __construct() {
        // since we don't know where we start, build a 150x150 map and position ourselves at the middle
        $this->map = array_pad([], 150, array_pad([], 150, 0)); // 0 is unknown
        $this->pos = ['x'=> 75, 'y'=> 75];
    }

    public function play($input){
        $this->updateMap($input);
        $this->move();
    }

    private function updateField($x, $y, $inData) {
        if ($inData == '!' || $this->map[$x][$y] >= 1000) {                 // avoid overwriting our observations
            $this->map[$x][$y] = 1000;
            return;
        }

        // update our known borders
        if ($x <= $this->w) {
            $this->w = $x - 1;
        }
        elseif ($x >= $this->e) {
            $this->e = $x + 1;
        }
        elseif ($y <= $this->n) {
            $this->n = $y - 1;
        }
        elseif ($y >= $this->s) {
            $this->s = $y + 1;
        }

        if (!$this->map[$x][$y]) {
            $this->map[$x][$y] = $inData == '+' ? -1 : 1;
        }
    }

    private function checkForIntersection($input) {
        if (array_key_exists('x' . $this->pos['x'] . 'y' . $this->pos['y'], $this->intersections)) {
            if ($this->intersections['x' . $this->pos['x'] . 'y' . $this->pos['y']] > 0) {
                $this->intersections['x' . $this->pos['x'] . 'y' . $this->pos['y']] --;
                return TRUE;                                        // intersection already crossed
            }
        }
        elseif ($c = substr_count($input, ' ') > 2) {
            $this->intersections['x' . $this->pos['x'] . 'y' . $this->pos['y']] = $c - 1;
        }

        return FALSE;
    }

    private function updateMap($input) {
        if ($this->checkForIntersection($input)) {
            // if we're at a known intersection, we know that the path we come from lead nowhere
            $this->updateField($this->prevPos['x'], $this->prevPos['y'], '!');
        }

        // update discovered information
        $this->updateField($this->pos['x'], $this->pos['y'] - 1, $input[0]);
        $this->updateField($this->pos['x'] + 1, $this->pos['y'], $input[1]);
        $this->updateField($this->pos['x'], $this->pos['y'] + 1, $input[2]);
        $this->updateField($this->pos['x'] - 1, $this->pos['y'], $input[3]);
    }

    private function move() {
        if ($this->prevPos) {

            $this->map[$this->prevPos['x']][$this->prevPos['y']] ++;    // count times stepped on
        }

        $best = ['w' => 1000];

        foreach ([
            ['x' => $this->pos['x'], 'y' => $this->pos['y'] - 1, 'w' => $this->map[$this->pos['x']][$this->pos['y'] - 1], 'd' => 'n'],
            ['x' => $this->pos['x'] + 1, 'y' => $this->pos['y'], 'w' => $this->map[$this->pos['x'] + 1][$this->pos['y']], 'd' => 'e'],
            ['x' => $this->pos['x'], 'y' => $this->pos['y'] + 1, 'w' => $this->map[$this->pos['x']][$this->pos['y'] + 1], 'd' => 's'],
            ['x' => $this->pos['x'] - 1, 'y' => $this->pos['y'], 'w' => $this->map[$this->pos['x'] - 1][$this->pos['y']], 'd' => 'w']]
        as $direction) {
            if ($direction['w'] < $best['w'] || ($direction['w'] == $best['w'] && $best['w'] < 1000 && max($this->e - $direction['x'],  $direction['x'] - $this->w, $direction['y'] - $this->n, $this->s - $direction['y']) > max($best['x'] - $this->e, $this->w - $best['x'], $best['y'] - $this->n, $this->s - $best['y']))) {
            // encourage searching for borders which will later allow to block certain dead end paths without walking them
            // testing with middle search instead
                $best = $direction;
            }
        }

        echo $best['d'] . "\n";

        $this->prevPos = $this->pos;
        $this->pos = $best;
    }
}

$maze = new Maze();

while (strncmp(($input = fgets(STDIN)), '0000', 4)) {
    $len = strlen($input);
    if (($len > 6) || $len < 3) { continue; }

    $maze->play($input);
}


问:
Index sum and strip my matrix

Index sum and strip my matrix

Given a matrix/2d array in your preferable language

Input:

The matrix will always have an odd length

The matrix will always be perfectly square

The matrix values can be any integer in your language (positive or negative)

Example:

```<code>1  2  3  4  5  6  7
2  3  4  5  6  7  8
3  4  50 6  7  8  9
4  5  6 100 8  9  10
5  6  7  8 -9  10 11
6  7  8  9  10 11 12
7  8 900 10 11 12 0
</code>```

Definitions:

The "central number" is defined as the number that has the same amount of numbers to the left,right,up and down

In this case its middlemost 100

The "outer shell" is the collection of numbers which their x and y index is or 0 or the matrix size

```<code>1  2  3  4  5  6  7
2                 8
3                 9
4                 10
5                 11
6                 12
7  8 900 10 11 12 0
</code>```

Your task:

Add to the central number the sum of each row and column after multiplying the values in each by their 1-based index

A single row for example

```<code>4  5  6  7  8
</code>```

for each number

```<code>number * index + number * index.....

4*1 + 5*2 + 6*3 + 7*4 + 8*5 => 100
</code>```

example:

```<code> 2 -3 -9  4  7  1  5  => 61
-2  0 -2 -7 -7 -7 -4  => -141
 6 -3 -2 -2 -3  2  1  => -10
 8 -8  4  1 -8  2  0  => -20
-5  6  7 -1  8  4  8  => 144
 1  5  7  8  7 -9 -5  => 10
 7  7 -2  2 -7 -8  0  => -60
                         |
78 65 60 45 -15 -89 10   => 154
                     |
                     => -16
</code>```

For all rows and columns you combine these values..

Now you sum these too => 154-16 = 138

You add that number to the "central number" and remove the "outer shell" of the matrix

```<code> 0 -2 -7 -7 -7     => -88
-3 -2 -2 -3  2     => -15
-8  4 1+138 -8  2  => 395
 6  7 -1  8  4     => 69
 5  7  8  7 -9     => 26

19 69 442 30 -26
</code>```

do this untill you end up with a single number

```<code>-2 -2 -3     => -15
 4  1060 -8  => 2100
 7 -1  8     => 29

27 2115 5
</code>```

Add 2114+2147 to 1060

Remove the "outer shell" and get 5321

Now we have a single number left

this is the output!

test cases:

```<code>-6

-6
</code>```

```<code>-7 -1  8
-4 -6  7
-3 -6  6

2
</code>```

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

-365
</code>```

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

17611
</code>```

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

-28473770
</code>```

This is a codegolf challenge so the program with the lowest bytecount wins

答:
MATL, <s>36</s> 34 bytes

```<code>tnq?`t&+stn:*sytn2/)+ 7M(6Lt3$)tnq
</code>```

Input is a 2D array with ; as row separator

Try it online! Or verify all test cases.

Explanation

```<code>tnq       % Take input. Duplicate, get number of elements, subtract 1
?         % If greater than 0
  `       %   Do...while
    t     %     Duplicate
    &+    %     Sum matrix with its transpose
    s     %     Sum each column. Gives a row vector
    tn:   %     Vector [1 2 ...] with the same size
    *     %     Multiply element-wise
    s     %     Sum of vector. This will be added to center entry of the matrix
    y     %     Duplicate matrix
    tn2/  %     Duplicate, get half its number of elements. Gives non-integer value
    )     %     Get center entry of the matrix, using linear index with implicit rounding
    +     %     Add center entry to sum of previous vector
    7M    %     Push index of center entry again
    (     %     Assgined new value to center of the matrix
    6Lt   %     Array [2 j1-1], twice. This will be used to remove shell
    3$)   %     Apply row and col indices to remove outer shell of the matrix
    tnq   %     Duplicate, number of elements, subtract 1. Falsy if matrix has 1 entry
          %   End do...while implicitly. The loop is exited when matrix has 1 entry
          % End if implicitly
          % Display stack implicitly
</code>```

Title: Index sum and strip my matrix

Body:
MATL, <s>36</s> 34 bytes

tnq?`t&+stn:*sytn2/)+ 7M(6Lt3$)tnq

Input is a 2D array with ; as row separator

Try it online! Or <a href="http://matl.tryitonline.net/#code=YCAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgJSBMb29wIHRvIHJlYWQgYWxsIGlucHV0cwp0bnE_YHQmK3N0bjoqc3l0bjIvKSsgN00oNkx0MyQpdG5xICAgICAlIEFjdHVhbCBjb2RlCl1dRFQgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICUgRW5kIGxvb3BzLCBkaXNwbGF5&input=Wy02XQpbLTcgLTEgIDg7IC00IC02ICA3OyAtMyAtNiAgNl0KWzYgIDcgLTIgIDUgIDE7IC0yICA2IC00IC0yICAzOyAtMSAtNCAgMCAtMiAtNzsgMCAgMSAgNCAtNCAgODsgLTggLTYgLTUgIDAgIDJdCls4ICAzICA1ICA2ICA2IC03ICA1OyA2ICAyICA0IC0yIC0xICA4ICAzOyAyICAxIC01ICAzICA4ICAyIC0zOyAzIC0xICAwICA3IC02ICA3IC01OyAwIC04IC00IC05IC00ICAyIC04OyA4IC05IC0zICA1ICA3ICA4ICA1OyA4IC0xICA0ICA1ICAxIC00ICA4XQpbLTkgLTcgIDIgIDEgIDEgLTIgIDMgLTcgLTMgIDYgIDcgIDEgIDA7IC03IC04IC05IC0yICA3IC0yICA1ICA0ICA3IC03ICA4IC05ICA4OyAtNCAgNCAtMSAgMCAgMSAgNSAtMyAgNyAgMSAtMiAtOSAgNCAgODsgIDQgIDggIDEgLTEgIDAgIDcgIDQgIDYgLTkgIDMgLTkgIDMgLTk7IC02IC04IC00IC04IC05ICAyICAxICAxIC04ICA4ICAyICA2IC00OyAtOCAtNSAgMSAgMSAgMiAtOSAgMyAgNyAgMiAgNSAtNiAtMSAgMjsgLTggLTUgLTcgLTQgLTkgLTIgIDUgIDAgIDIgLTQgIDIgIDAgLTI7IC0zIC02IC0zICAyIC05ICA4ICAxIC01ICA1ICAwIC00IC0xIC05OyAtOSAtOSAtOCAgMCAtNSAtNyAgMSAtMiAgMSAtNCAtMSAgNSAgNzsgLTYgLTkgIDQgLTIgIDggIDcgLTkgLTUgIDMgLTEgIDEgIDggIDQ7IC02ICA2IC0zIC00ICAzICA1ICA2ICA4IC0yICA1IC0xIC03IC05OyAtMSAgNyAtOSAgNCAgNiAgNyAgNiAtOCAgNSAgMSAgMCAtMyAgMDsgLTMgLTIgIDUgLTQgIDAgIDAgIDAgLTEgIDcgIDQgLTkgLTQgIDJdCgoKCg" rel="nofollow noreferrer">verify all test cases.

Explanation

tnq       % Take input. Duplicate, get number of elements, subtract 1
?         % If greater than 0
  `       %   Do...while
    t     %     Duplicate
    &+    %     Sum matrix with its transpose
    s     %     Sum each column. Gives a row vector
    tn:   %     Vector [1 2 ...] with the same size
    *     %     Multiply element-wise
    s     %     Sum of vector. This will be added to center entry of the matrix
    y     %     Duplicate matrix
    tn2/  %     Duplicate, get half its number of elements. Gives non-integer value
    )     %     Get center entry of the matrix, using linear index with implicit rounding
    +     %     Add center entry to sum of previous vector
    7M    %     Push index of center entry again
    (     %     Assgined new value to center of the matrix
    6Lt   %     Array [2 j1-1], twice. This will be used to remove shell
    3$)   %     Apply row and col indices to remove outer shell of the matrix
    tnq   %     Duplicate, number of elements, subtract 1. Falsy if matrix has 1 entry
          %   End do...while implicitly. The loop is exited when matrix has 1 entry
          % End if implicitly
          % Display stack implicitly


问:
Count sum of all digits
This challenge is to write a program or script which counts the sum of all digits within the integers from 1 up to and including a given number.

Input, one positive integer.
Output, the sum of digits in that number and all smaller numbers.

Examples:

```<code>Input: 5
Integer Sequence: 1, 2, 3, 4, 5
Sum of Digits: 1 + 2 + 3 + 4 + 5 = 15

Input: 12
Integer Sequence: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12
Sum of Digits: 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 1 + 0 + 1 + 1 + 1 + 2 = 51
</code>```

To be clear, this is to count a sum of the digits - not the integers. For single-digit inputs, this will be the same. However, inputs larger than 10 will have different responses. This would be an incorrect response:

```<code>Input: 12
Output: 78
</code>```

Another example, to show the difference:

```<code>Input: 10

Integer Sequence: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
Sum of Integers (INCORRECT RESPONSE): 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 = 55

Digit Sequence: 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 0
Sum of Digits (CORRECT RESPONSE): 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 1 + 0 = 46
</code>```

A larger test case (CORRECT RESPONSE):

```<code>Input: 1000000
Output: 27000001
</code>```

Rules & Guidelines:

Submitted code must be a complete program or script - not just a function. If the code requires includes, imports, etc., they must be included in the posted code.

The number must be input by the user - not hard-coded. Input may be received as a command-line argument, file, stdin, or any other means by which your language can take user input.

The code must be able to properly handle inputs at least up to (2^64)-1.

The code should only output the sum.

Submitted programs & scripts should be user-friendly and not wasteful of computer resources (e.g.: they should not declare insanely-large arrays to hold every character). There is no strict bonus or penalty for this, but please be good programmers.

Scoring:

Primary scoring mechanism is by code length. Lower scores are better. The following bonuses and penalties also apply:

-25 Bonus if your code can handle all positive numbers, for example: 1234567891234567891234564789087414984894900000000

-50 Bonus if your code can handle simple expressions, for example 55*96-12. To qualify for this bonus, the code should handle + - / * (addition, subtraction, division, multiplication) operators and enforce order of operations. Division is regular integer division.

The given example (55*96-12) evaluates to 5268. Your code should return the same for either of those inputs - correct answer is 81393.

-10 Bonus if your code qualifies for the -50 bonus and can handle the ^ (exponent) operator.

-100 Bonus if your code qualifies for the -50 bonus and does not use eval or similar to handle expressions.

+300 Penalty if your code relies upon any web resources.

答:
Python 3 + astor, 1017 1007 bytes - (25 + 50 + 100) = Score: 842 834

saved 10 bytes by removing ts and changing p

edit: I am unable to test the ridiculously long integer (1234567891234567891234564789087414984894900000000) [hangs my computer] but from my knowledge, Python 3 supports arbritrarily long integers.

This implementation uses abuses AST. I wouldn't consider abusing AST as "eval or similar".

```<code>from ast import*
from astor import*
nt,bo,m,d,a,s,n,p,ty=NodeTransformer,BinOp,Mult,Div,Add,Sub,Num,map,type
class M(nt):
    def visit_BinOp(t,z):
        if ty(z.left)==bo and ty(z.right)==bo:return bo(t.visit_BinOp(z.left),z.op,t.visit_BinOp(z.right))
        if ty(z.left)==bo:return bo(t.visit_BinOp(z.left),z.op,z.right)
        if ty(z.right)==bo:return bo(z.left,z.op,t.visit_BinOp(z.right))
        if ty(z.op)==m:return n(z.left.n*z.right.n)
        if ty(z.op)==d:return n(z.left.n/z.right.n);return z
class A(nt):
    def visit_BinOp(t,z):
        if ty(z.left)==bo and ty(z.right)==bo:return bo(t.visit_BinOp(z.left),z.op,t.visit_BinOp(z.right))
        if ty(z.left)==bo:return bo(t.visit_BinOp(z.left),z.op,z.right)
        if ty(z.right)==bo:return bo(z.left,z.op,t.visit_BinOp(z.right))
        if ty(z.op)==a:return n(z.left.n+z.right.n)
        if ty(z.op)==s:return n(z.left.n-z.right.n);return z
class S(nt):
    def visit_Num(t,z):return n(sum(p(int,list("".join(p(str,range(1,z.n+1)))))))
print(to_source(S().visit(A().visit(M().visit(parse(input()))))))
</code>```

Too lazy to write ungolfed, so I'll give you an explanation of the classes:

```<code>M(NodeTransformer|nt) - converts multiplication and division into their results.
A(NodeTransformer|nt) - converts addition and subtraction into their results.
S(NodeTransformer|nt) - converts numbers into their sum of digits via the Pythonic (naïve) way.
</code>```

The last line just executes these classes in the appropriate order on the input, to preserve order of operations, and prevent unwanted behavior.

Example usage ($ or > means user input) and by the way, the actual program takes input only once:

```<code>$ python3 summer.py
> 5
15
> 10
46
> 12
51
> 1000000
27000001
> 55*96-12
81393
</code>```

ContentLicense: CC BY-SA 4.0

Title: Count sum of all digits

Body:
Python 3 + astor, 1017 1007 bytes - (25 + 50 + 100) = Score: 842 834

saved 10 bytes by removing ts and changing p

edit: I am unable to test the ridiculously long integer (1234567891234567891234564789087414984894900000000) [hangs my computer] but from my knowledge, Python 3 supports arbritrarily long integers.

This implementation uses abuses AST. I wouldn't consider abusing AST as "eval or similar".

from ast import*
from astor import*
nt,bo,m,d,a,s,n,p,ty=NodeTransformer,BinOp,Mult,Div,Add,Sub,Num,map,type
class M(nt):
    def visit_BinOp(t,z):
        if ty(z.left)==bo and ty(z.right)==bo:return bo(t.visit_BinOp(z.left),z.op,t.visit_BinOp(z.right))
        if ty(z.left)==bo:return bo(t.visit_BinOp(z.left),z.op,z.right)
        if ty(z.right)==bo:return bo(z.left,z.op,t.visit_BinOp(z.right))
        if ty(z.op)==m:return n(z.left.n*z.right.n)
        if ty(z.op)==d:return n(z.left.n/z.right.n);return z
class A(nt):
    def visit_BinOp(t,z):
        if ty(z.left)==bo and ty(z.right)==bo:return bo(t.visit_BinOp(z.left),z.op,t.visit_BinOp(z.right))
        if ty(z.left)==bo:return bo(t.visit_BinOp(z.left),z.op,z.right)
        if ty(z.right)==bo:return bo(z.left,z.op,t.visit_BinOp(z.right))
        if ty(z.op)==a:return n(z.left.n+z.right.n)
        if ty(z.op)==s:return n(z.left.n-z.right.n);return z
class S(nt):
    def visit_Num(t,z):return n(sum(p(int,list("".join(p(str,range(1,z.n+1)))))))
print(to_source(S().visit(A().visit(M().visit(parse(input()))))))

Too lazy to write ungolfed, so I'll give you an explanation of the classes:

M(NodeTransformer|nt) - converts multiplication and division into their results.
A(NodeTransformer|nt) - converts addition and subtraction into their results.
S(NodeTransformer|nt) - converts numbers into their sum of digits via the Pythonic (naïve) way.

The last line just executes these classes in the appropriate order on the input, to preserve order of operations, and prevent unwanted behavior.

Example usage ($ or > means user input) and by the way, the actual program takes input only once:

$ python3 summer.py
> 5
15
> 10
46
> 12
51
> 1000000
27000001
> 55*96-12
81393


问:
Generate a valid sequence of numbers with specific rules

The challenge

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

Rules

x is the size of the sequence;

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

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

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

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

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

Examples

If x=4:

2413 valid

3142 valid

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

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

Still don't get it?
Other example:

If x=8:

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

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

Additional Information

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

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

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

Good, luck. =)

Body:
Python,30:

' 3579'[:(1+x)/2]+'1468'[:x/2]+'2'

http://ideone.com/3csRh