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

答:
Simple Bot, Java 1.4+, 176 + 25 + 1118 + 486 + 10944 + 1847 = 14596 steps

This bot counts and records the number of steps taken to reach each visited cell then, when deciding which direction to move, chooses the direction that has the lowest step count. In the event of a tie, chooses the direction in N,E,S,W order.

I do not have rust installed so I had to implement the controller in java and this was the bot i used to test it. I will be attempting a more clever solver soon.

Deterministic.  Run with java SimpleBot

import java.io.IOException;
import java.io.InputStream;

public class SimpleBot
{
    private static final char[] DIRECTION = {'n','e','s','w'};
    public static void main(String[] args) throws Exception
    {
        int[][] stepMap = new int[100][100];
        int mx=49, my=49;
        int[][] offsets = new int[][]{{0,-1},{1,0},{0,1},{-1,0}};

        String line=readLine(System.in);
        int step=0;
        while (line!=null && !"0000".equals(line))
        {
            stepMap[mx][my]=step++;

            int minStep = Integer.MAX_VALUE;
            int minIndex = -1;
            for (int i=0;i<4;i++)
            {
                if (line.charAt(i) == '+')
                {
                    minIndex=i;
                    break;
                }
                else if (line.charAt(i) == ' ')
                {
                    if (stepMap[mx+offsets[i][0]][my+offsets[i][1]]<minStep)
                    {
                        minStep = stepMap[mx+offsets[i][0]][my+offsets[i][1]];
                        minIndex=i;
                    }
                }
            }
            mx +=offsets[minIndex][0];
            my +=offsets[minIndex][1];

            System.out.println(DIRECTION[minIndex]);
            line=readLine(System.in);
        }
    }

    /**
     * Reads a line of text from the input stream. Blocks until a new line character is read.
     * NOTE: This method is used in favor of BufferedReader.readLine(...) as BufferedReader buffers data before performing
     * text line tokenization. This means that BufferedReader.readLine() will block until sufficient input have been received.
     * @param in a InputStream, nominally System.in
     * @return a line of text or null if end of stream.
     * @throws IOException
     */
    private static String readLine(InputStream in) throws IOException
    {
       StringBuilder sb = new StringBuilder();
       int readByte = in.read();
       while (readByte>-1 && readByte!= '\n')
       {
          sb.append((char) readByte);
          readByte = in.read();
       }
       return readByte==-1?null:sb.toString();
    }

}
```

Title: Find the Cheese


问:
Recursion bracketed; or Dyck words generation
We already have challenges to check if a string of brackets is fully matched and to count the number of balanced strings. It remains for us to generate these strings, but it will not be so easy…

A Dyck word is a string, of length 2n, consisting of n opening and n closing parentheses (( and )) fully matched (that is to say: for all prefixes of the string, the number of opening parentheses is greater than or equal to the number of closing ones).

It is interesting to note that the number of different Dyck words of length 2n is equal to the (n + 1)-th Catalan number.

It’s pretty straightforward to write a program that generates these words with a recursive function. But the goal here is to do the same thing without.

Challenge

Write a full program or function that takes a positive integer, n, using stdin or an acceptable alternative, and outputs all the different Dyck words of length 2n. The words can appear in any order and each must be separated from each other by a line break. Moreover, your program should not use recursive functions (see details below).

Rules

The output of your program should only contain Dyck words of length 2n, separated by line breaks. Each word must appear only once.

Your program must work at minimum for inputs 0 to 15.

You may not write recursive functions, neither direct (a function that calls itself) nor indirect (e.g. a function f that calls another function g that calls function f). That being said, you can still use the standard functions of your language without worry of how they work internally.

Similarly, your program should not call itself.

You may not use non-standard librairies.

Your program may not read or write files.

Your program must be able to run in a reasonable time for 0 ≤ n ≤ 15 (hence, naively generate all arrangements is probably not a good idea). Let’s say less than 20 minutes with a memory limit of 4 GB (my reference implementation in C manages n = 15 in less than 5 seconds).

All standard loopholes are forbidden.

As usual in code-golf, the shortest code in bytes wins. But if you have found an interesting way to achieve this challenge in your language, please do not hesitate.

Test I/O

For this input:

```<code>3
</code>```

The output could be (any other order is correct too):

```<code>((()))
()()()
(()())
(())()
()(())
</code>```

答:
Pyth, <s>26</s> 23 bytes

```<code>jeuaGsMs*VjRL`()_GGQ]]k
</code>```

Try it online

```<code>                    ]]k   starting at G=[['']],
  u                Q      repeat the given number of times:
                _G          reversed G
          jRL`()            parenthesize each level-2 element
        *V        G         take Cartesian products of corresponding
                              elements of that and G
       s                    concatenate, yielding a list of pairs
     sM                     concatenate each resulting pair
   aG                       append the resulting list to G
je                        finally, join the last result on newlines
</code>```

This directly follows the Catalan recurrence (with a non-recursive dynamic programming implementation) and doesn’t use any filtering.  On my laptop, it runs in 55 seconds using 2.67 GiB RAM for n = 15.

Pyth, 33 bytes, O(n) memory

```<code>=S*Q`()Wn2J+3x
Q"(()"=+.<S<QJ1>QJ
</code>```

Try it online

```<code>  *Q`()                  build a string with Q copies of "()"
 S                       sort it
=                        assign it to Q

       W                 while the following is true:
(newline)                  print Q
Q
             x             take the index of the first occurrence of "(()"
 "(()"
           +3              add 3
          J                assign to J
        n2                 is this not equal to 2 (i.e. was "(()" found)?
                         do the following:
           <QJ             take the first J characters of Q
          S                sort them
        .<    1            cyclically shift them left by 1
       +       >QJ         add the remaining characters of Q
      =                    assign to Q
</code>```

This algorithm outputs all Dyck words in a stream, with each word being generated from the previous one and no additional state.  On my laptop, it runs in 170 seconds using basically no RAM for n = 15.

As an example illustrating how it works:

```<code>()()()()((()()(())))(())
         ^^^               becomes
(((((()))))(()(())))(())
</code>```

Similarly computing the words in the reverse of this order also takes 33 bytes:

```<code>=*QK`()WJhx
Q_K=+t.iFc2_<QJ+K>QhJ
</code>```

Try it online

ContentLicense: CC BY-SA 3.0

Body:
Pyth, <s>26</s> 23 bytes

jeuaGsMs*VjRL`()_GGQ]]k

Try it online

                    ]]k   starting at G=[['']],
  u                Q      repeat the given number of times:
                _G          reversed G
          jRL`()            parenthesize each level-2 element
        *V        G         take Cartesian products of corresponding
                              elements of that and G
       s                    concatenate, yielding a list of pairs
     sM                     concatenate each resulting pair
   aG                       append the resulting list to G
je                        finally, join the last result on newlines

This directly follows the Catalan recurrence (with a non-recursive dynamic programming implementation) and doesn’t use any filtering.  On my laptop, it runs in 55 seconds using 2.67 GiB RAM for n = 15.

Pyth, 33 bytes, O(n) memory

=S*Q`()Wn2J+3x
Q"(()"=+.<S<QJ1>QJ

Try it online

  *Q`()                  build a string with Q copies of "()"
 S                       sort it
=                        assign it to Q

       W                 while the following is true:
(newline)                  print Q
Q
             x             take the index of the first occurrence of "(()"
 "(()"
           +3              add 3
          J                assign to J
        n2                 is this not equal to 2 (i.e. was "(()" found)?
                         do the following:
           <QJ             take the first J characters of Q
          S                sort them
        .<    1            cyclically shift them left by 1
       +       >QJ         add the remaining characters of Q
      =                    assign to Q

This algorithm outputs all Dyck words in a stream, with each word being generated from the previous one and no additional state.  On my laptop, it runs in 170 seconds using basically no RAM for n = 15.

As an example illustrating how it works:

()()()()((()()(())))(())
         ^^^               becomes
(((((()))))(()(())))(())

Similarly computing the words in the reverse of this order also takes 33 bytes:

=*QK`()WJhx
Q_K=+t.iFc2_<QJ+K>QhJ

Try it online


问:
bfcat - encode a file as a brainf*** program

Challenge

Write a program or function that given a string, returns a valid Brainfuck program that when compiled and executed as Brainfuck, returns that string..

Assume all inputs are encoded as ASCII.

Assume the outputted BF program will execute in an environment with an infinite tape.

Assume the pointer starts at cell 0 with every cell initialized to a value of zero.

Each example below represent one possible correct output for the given input. In particular, the examples include extra newlines and spaces to help human readability. Solutions are free to format the outputted BF code in any way.

The tape is doubly infinite.

All cells provided by the interpreter are exactly 8-bit cells. Overflow and underflow wrap around in a predictable and sane matter.

Examples

Space string

Given the input  , your program/function could return:

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

Exclamation point

Given the input ! , your program/function could return:

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

Two letters

Given the input hi , your program/function could return:

```<code>+++++ +++++
+++++ +++++
+++++ +++++
+++++ +++++
+++++ +++++

+++++ +++++
+++++ +++++
+++++ +++++
+++++ +++++
+++++ +++++

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

This is code-golf, so the code with the smallest number of bytes wins. Good luck.

答:
CJam, 12 bytes

Converts each character to its ASCII value, and increments the current cell by that number of times before printing it. Since we have infinite tape we can just move to the right after processing each character.

```<code>q{i'+*'.'>}%
</code>```

Try it online!

Body:
CJam, 12 bytes

Converts each character to its ASCII value, and increments the current cell by that number of times before printing it. Since we have infinite tape we can just move to the right after processing each character.

q{i'+*'.'>}%

Try it online!


问:
Visualise Bit Weaving
The esoteric programming language evil has an interesting operation on byte values which it calls "weaving". It is essentially a permutation of the eight bits of the byte (it doesn't matter which end we start counting from, as the pattern is symmetric):

Bit 0 is moved to bit 2

Bit 1 is moved to bit 0

Bit 2 is moved to bit 4

Bit 3 is moved to bit 1

Bit 4 is moved to bit 6

Bit 5 is moved to bit 3

Bit 6 is moved to bit 7

Bit 7 is moved to bit 5

For convenience, here are two other representations of the permutation. As a cycle:

```<code>(02467531)
</code>```

And as a list of pairs of the mapping:

```<code>[[0,2], [1,0], [2,4], [3,1], [4,6], [5,3], [6,7], [7,5]]
</code>```

Your task is to visualise this permutation, using the box-drawing characters ─, │, ┌, ┐, └, ┘, ┼ (Unicode code points: U+2500, U+2502, U+250C, U+2510, U+2514, U+2518, U+253C). This visualisation should satisfy the following constraints:

The first and last line are exactly:

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

Between those, you can use as many lines as you want of up to 15 characters each to fit your box drawing characters (you will need at least 4 lines). The lines should start vertically beneath one of the digits on the first row and end vertically above the corresponding digit on the last row. The eight lines must be connected, and may only cross via ┼ (which is always a crossing, never two turning lines which are touching). The exact paths of the lines are up to you (and finding a particularly golfable layout is the core of this challenge). One valid output would be:

```<code>0 1 2 3 4 5 6 7
│ │ └─┼┐│ │ └┐│
└─┼─┐ ││└─┼─┐││
┌─┘ │ ││  │ │││
│ ┌─┼─┘│  │ │││
│ │ │ ┌┼──┘ │││
│ │ │ │└┐ ┌─┼┼┘
│ │ │ │ │ │ │└┐
0 1 2 3 4 5 6 7
</code>```

However, any other layout that correctly connects the right digits is fine too. Please show your chosen output in your answer.

You may write a program or function and will not take any input. Output the diagram either to STDOUT (or closest alternative) or as a function return value in the form of a string or a list of strings (each representing one line).

Standard code-golf rules apply, so the shortest code (in bytes) wins.

答:
MATLAB / Octave, <s>112</s> 109 bytes

a='0 1 2 3 4 5 6 7';d=['└┐│ ';'┌┼┘ ';'│└┐ '];e=repmat('│ ',3,1);[a;d d d d;e d d d e;a]
```

<p>Output:</p>

```0 1 2 3 4 5 6 7
└┐│ └┐│ └┐│ └┐│
┌┼┘ ┌┼┘ ┌┼┘ ┌┼┘
│└┐ │└┐ │└┐ │└┐
│ └┐│ └┐│ └┐│ │
│ ┌┼┘ ┌┼┘ ┌┼┘ │
│ │└┐ │└┐ │└┐ │
0 1 2 3 4 5 6 7
```

My code is based on the ouputs of @Dendrobium and @Neil.

Title: Visualise Bit Weaving

Body:
MATLAB / Octave, <s>112</s> 109 bytes

a='0 1 2 3 4 5 6 7';d=['└┐│ ';'┌┼┘ ';'│└┐ '];e=repmat('│ ',3,1);[a;d d d d;e d d d e;a]

Output:

0 1 2 3 4 5 6 7
└┐│ └┐│ └┐│ └┐│
┌┼┘ ┌┼┘ ┌┼┘ ┌┼┘
│└┐ │└┐ │└┐ │└┐
│ └┐│ └┐│ └┐│ │
│ ┌┼┘ ┌┼┘ ┌┼┘ │
│ │└┐ │└┐ │└┐ │
0 1 2 3 4 5 6 7

My code is based on the ouputs of @Dendrobium and @Neil.


答:
Sidef, 38 bytes

Hey, the same length as Ruby! just that Sidef isn't Ruby :D

```<code>read().bytes.each{|c|say"+"*c;say".>"}
</code>```

Read some chars, then for each byte do that thing.

Title: bfcat - encode a file as a brainf*** program

Body:
Challenge

Write a program or function that given a string, returns a valid Brainfuck program that when compiled and executed as Brainfuck, returns that string..

Assume all inputs are encoded as ASCII.

Assume the outputted BF program will execute in an environment with an infinite tape.

Assume the pointer starts at cell 0 with every cell initialized to a value of zero.

Each example below represent one possible correct output for the given input. In particular, the examples include extra newlines and spaces to help human readability. Solutions are free to format the outputted BF code in any way.

The tape is doubly infinite.

All cells provided by the interpreter are exactly 8-bit cells. Overflow and underflow wrap around in a predictable and sane matter.

Examples

Space string

Given the input  , your program/function could return:

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

Exclamation point

Given the input ! , your program/function could return:

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

Two letters

Given the input hi , your program/function could return:

```<code>+++++ +++++
+++++ +++++
+++++ +++++
+++++ +++++
+++++ +++++

+++++ +++++
+++++ +++++
+++++ +++++
+++++ +++++
+++++ +++++

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

This is code-golf, so the code with the smallest number of bytes wins. Good luck.

Body:
Sidef, 38 bytes

Hey, the same length as Ruby! just that Sidef isn't Ruby :D

read().bytes.each{|c|say"+"*c;say".>"}

Read some chars, then for each byte do that thing.


答:
Python 2, <s>117</s> 116 bytes

def f(n):r='',;exec"r=[s+c for s in r for t in[s.count('(')]for c in')('[t+t==len(s):2-t/n]];"*2*n;print'\n'.join(r)
```

This builds the strings character by character, without filtering.

With piped output and input n = 15, this takes roughly 39 seconds with CPython and 7.5 seconds with PyPy on my machine. Memory consumption is 1.6 GB with CPython and 2.5 GB with PyPy.

Test it on Ideone.

Title: Recursion bracketed; or Dyck words generation

Body:
We already have challenges to check if a string of brackets is fully matched and to count the number of balanced strings. It remains for us to generate these strings, but it will not be so easy…

A Dyck word is a string, of length 2n, consisting of n opening and n closing parentheses (( and )) fully matched (that is to say: for all prefixes of the string, the number of opening parentheses is greater than or equal to the number of closing ones).

It is interesting to note that the number of different Dyck words of length 2n is equal to the (n + 1)-th Catalan number.

It’s pretty straightforward to write a program that generates these words with a recursive function. But the goal here is to do the same thing without.

Challenge

Write a full program or function that takes a positive integer, n, using stdin or an acceptable alternative, and outputs all the different Dyck words of length 2n. The words can appear in any order and each must be separated from each other by a line break. Moreover, your program should not use recursive functions (see details below).

Rules

The output of your program should only contain Dyck words of length 2n, separated by line breaks. Each word must appear only once.

Your program must work at minimum for inputs 0 to 15.

You may not write recursive functions, neither direct (a function that calls itself) nor indirect (e.g. a function f that calls another function g that calls function f). That being said, you can still use the standard functions of your language without worry of how they work internally.

Similarly, your program should not call itself.

You may not use non-standard librairies.

Your program may not read or write files.

Your program must be able to run in a reasonable time for 0 ≤ n ≤ 15 (hence, naively generate all arrangements is probably not a good idea). Let’s say less than 20 minutes with a memory limit of 4 GB (my reference implementation in C manages n = 15 in less than 5 seconds).

All standard loopholes are forbidden.

As usual in code-golf, the shortest code in bytes wins. But if you have found an interesting way to achieve this challenge in your language, please do not hesitate.

Test I/O

For this input:

```<code>3
</code>```

The output could be (any other order is correct too):

```<code>((()))
()()()
(()())
(())()
()(())
</code>```

Body:
Python 2, <s>117</s> 116 bytes

def f(n):r='',;exec"r=[s+c for s in r for t in[s.count('(')]for c in')('[t+t==len(s):2-t/n]];"*2*n;print'\n'.join(r)

This builds the strings character by character, without filtering.

With piped output and input n = 15, this takes roughly 39 seconds with CPython and 7.5 seconds with PyPy on my machine. Memory consumption is 1.6 GB with CPython and 2.5 GB with PyPy.

Test it on Ideone.


问:
Knight on the Rim is Grim

Introduction

Aron Nimzowitsch was a leading chess master and a influential chess writer.

In his book 'My System', the first chapter deals about the importance of the center and why you should dominate it. The simple reason is that your pieces have more possible direct next moves when being in the center which again gives the player more power.

This gets very clear when looking at different positions of a knight and its potential next moves (shown in pink) on an empty board:

Objective

Evaluate the number of potential direct next moves of a knight on an empty board based on its position.

Input Specs

The position of the knight.

First the x (column) and then the y (row). 0 0 is the left bottom corner.

For simplicity, I changed the labels of a chess board to numbers only. For our examples and test cases we use a 0-based index, you are free to use a 1-based index though.

You can use any type of possible input formats, an array, function arguments, etc.

Output Specs

The number of potential direct next moves for a knight on an empty board.

Test Cases

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

Test cases are employing a 0-based index. The full grid of values is:

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

答:
Actually, 18 bytes

```<code>`;7-2km`MΣ8-:50\¬¬
</code>```

Try it online!

This implements the same formula that many other answers have been using: 50/(8-x*(7-x)//5+y*(7-y))//5)-4. Input is taken as a list: [x,y] (or any iterable literal in Python, like (x,y) or x,y).

Explanation:

```<code>`;7-2km`MΣ8-:50\¬¬
`;7-2km`M           for each value in input:
 ;7-                  make a copy, subtract from 7
    2                 push 2
     km               minimum of the three values (x, 7-x, 2)
         Σ          sum
          8-        subtract from 8
            :50\    integer divide 50 by the value
                ¬¬  subtract 2 twice
</code>```

Title: Knight on the Rim is Grim

Body:
Actually, 18 bytes

`;7-2km`MΣ8-:50\¬¬

Try it online!

This implements the same formula that many other answers have been using: 50/(8-x*(7-x)//5+y*(7-y))//5)-4. Input is taken as a list: [x,y] (or any iterable literal in Python, like (x,y) or x,y).

Explanation:

`;7-2km`MΣ8-:50\¬¬
`;7-2km`M           for each value in input:
 ;7-                  make a copy, subtract from 7
    2                 push 2
     km               minimum of the three values (x, 7-x, 2)
         Σ          sum
          8-        subtract from 8
            :50\    integer divide 50 by the value
                ¬¬  subtract 2 twice


问:
It's Life, Jim, but not as we know it
You probably know Conway's Game of Life, the famous cellular automaton invented by mathematician John Conway. Life is a set of rules that, together, allow you to simulate a two-dimensional board of cells. The rules decide which cells on the board live and  which ones die. With some imagination, you could say that Life is a zero-player game: a game with the objective to find patterns with interesting behavior, like the famous glider.

A zero-player game... Until today. You are to write a program that plays the Game of Life - and plays it to win, King of the Hill-style. Your opponent (singular) of course tries to do the same. The winner is either the last bot with any live cells, or the player with the most live cells after 10000 generations.

Game rules

The rules are almost the same as normal (B3/S23) Life:

A live cell with fewer than two friendly neighbors dies from starvation.

A live cell with two or three friendly neighbors survives.

A live cell with more than three friendly neighbors dies from overpopulation.

A dead cell with exactly three neighbors of the same player comes alive to fight for that player provided there are no enemy neighbors.

...but after each generation, both you and your opponent get the opportunity to intervene. You can awake up to a maximum of 30 cells to fight for you. (Who goes first is decided by the server.)

The board is a (x,y) cells square. All squares are initially dead. The borders do not wrap around (this is not a torus-shaped world) and are permanently dead.

This is is a contest in the spirit of Battlebots and Core Wars. There is a central server that will run bots and it can be found here

Protocol

The arena server speaks a simple JSON protocol communicated through argv

Where Values is a JSON encoded string

y_size: the maximum y coords of tiles before they vanish

x_size: the maximum x coords of tiles before they vanish

tick_id: the current tick number

board: a dictionary with keys in the form '(y,x)' and values in the form bot_id (int)

bot_id: tiles in the board with this id are yours

Example:

```<code> {"y_size":2000,"x_size":2000,"board":{},"bot_id":1,"tick_id":1}

</code>```

Telling the server your choice:

Send the server a list of tiles to turn to your colour.

Only those that are empty will be changed

Nested coords list format

[[0,0], [0,1], [100,22]...]

NOTE: Your bot doesn't have to update the tiles at all - the server does the updating itself

Competition rules

If your implementation fails to follow the protocol, the turn it does will be forfeited; The server will assume no change in state

You are not allowed to willfully take advantage of a fault in the arena server.

Have your AI decide on moves in a sane time. Please send your next move as  fast as reasonably possible.

Finally, please be nice to the server. It's there for your enjoyment.

Not following these rules can lead to disqualification.

In the event of a tie, both players have 1 win added to their total

Running the controller yourself

The source for the controller can be found here. There are 2 ways of running the controller:

Competition mode (terminal)

Setup with python3 get_answers.py

Run an all v all competition with each bot pitting it against every other.

Testing mode (GUI)

Run python3 nice_gui.py

Click Pull Answers

If you want to add your own answer to try it before posting, click File -> Add manual answer and find the file and choose the language it's written in.

If your language isn't present ping me and I'll try to get it installed on the server I will run it on (installation and running instructions would be nice too!)

Choose 2 bots to pit against each other

Click Run

Watch the game...

Installation

Requires python3

get_answers requires bs4 and html5lib

controller requires a way of running .sh files (MinGW on windows)

Scoring

The bot with the most wins starting from <s>12/07/2016 (12th July)</s>   14/07/2016 (14th July, couldn't work out how to run a bot) wins.

Help with the controller/gui can be asked in this chat room

This question has been in development since 2014 and was the most upvoted question in the sandbox. Special Thanks goes to Wander Nauta (original author and concept), PPCG Chat (comments and help) and anyone who commented in the sandbox post (more comments).

答:
Ruby, InterruptingBlockMaker

Instead of initializing gliders like the TrainingBot, it tries to create a 5x5 block-making switch machine as mentioned on Wikipedia at a random point in the maze. Then, with its remaining activations, it just finds enemy points and tries to pepper the nearby area with your cells in an attempt to interrupt them from growing and possibly messing up their patterns. Your cells will die in the next generation, but maybe they also stopped some growth to slow down your opponent!

v2: Optimized slightly (?) to try to minimize timeouts.

v3: Optimized interruption code to pre-sample a subset of active blocks before rejecting our own cell locations, to prevent timeouts further at the cost of some effectiveness in the interrupt cell attacks.

```<code>require 'json'

class Range
  def product range2
    self.to_a.product range2.to_a
  end
end

args = JSON.parse(ARGV[0])
bot_id = args["bot_id"]
width  = args["x_size"]
height = args["y_size"]
board  = args["board"]

generator = [[2,2], [2,3], [2,6], [3,2], [3,5], [4,2], [4,5], [4,6], [5,4], [6,2], [6,4], [6,5], [6,6]]

targets = []

iterations = 50
gen_location = nil
while !gen_location && iterations > 0
  y = rand height - 9
  x = rand width  - 9
  temp = (0...9).product(0...9).map{|_y, _x| [y + _y, x + _x]}
  if temp.all?{|_y,_x| !board["(#{y},#{x})"]}
    gen_location = temp
    targets += generator.map{|_y, _x| [y + _y, x + _x]}
  end

  iterations -= 1
end

enemies = board.keys.sample(100).reject {|k| board[k] == bot_id}
interrupts = []
enemies.each do |location|
  y, x = location.scan(/\d+/).map &:to_i
  interrupts |= ((y-1)..(y+1)).product((x-1)..(x+1)).reject{|y, x| gen_location.include?([y,x]) || board["(#{y},#{x})"]}
end

targets += interrupts.sample(30 - targets.size)

puts JSON.dump(targets)
</code>```

Title: It's Life, Jim, but not as we know it

Body:
Ruby, InterruptingBlockMaker

Instead of initializing gliders like the TrainingBot, it tries to create a 5x5 block-making switch machine as mentioned on Wikipedia at a random point in the maze. Then, with its remaining activations, it just finds enemy points and tries to pepper the nearby area with your cells in an attempt to interrupt them from growing and possibly messing up their patterns. Your cells will die in the next generation, but maybe they also stopped some growth to slow down your opponent!

v2: Optimized slightly (?) to try to minimize timeouts.

v3: Optimized interruption code to pre-sample a subset of active blocks before rejecting our own cell locations, to prevent timeouts further at the cost of some effectiveness in the interrupt cell attacks.

require 'json'

class Range
  def product range2
    self.to_a.product range2.to_a
  end
end

args = JSON.parse(ARGV[0])
bot_id = args["bot_id"]
width  = args["x_size"]
height = args["y_size"]
board  = args["board"]

generator = [[2,2], [2,3], [2,6], [3,2], [3,5], [4,2], [4,5], [4,6], [5,4], [6,2], [6,4], [6,5], [6,6]]

targets = []

iterations = 50
gen_location = nil
while !gen_location && iterations > 0
  y = rand height - 9
  x = rand width  - 9
  temp = (0...9).product(0...9).map{|_y, _x| [y + _y, x + _x]}
  if temp.all?{|_y,_x| !board["(#{y},#{x})"]}
    gen_location = temp
    targets += generator.map{|_y, _x| [y + _y, x + _x]}
  end

  iterations -= 1
end

enemies = board.keys.sample(100).reject {|k| board[k] == bot_id}
interrupts = []
enemies.each do |location|
  y, x = location.scan(/\d+/).map &:to_i
  interrupts |= ((y-1)..(y+1)).product((x-1)..(x+1)).reject{|y, x| gen_location.include?([y,x]) || board["(#{y},#{x})"]}
end

targets += interrupts.sample(30 - targets.size)

puts JSON.dump(targets)


问:
Theoretically output Graham's number
Graham's number G is defined in this way:

```<code>u(3,n,1) = 3^n
u(3,1,m) = 3
u(3,n,m) = u(3,u(3,n-1,m),m-1)
[Knuth's up-arrow notation]
[Conway chained arrow notation]

THEN

g1 = u(3,3,4)
g2 = u(3,3,g1)
g3 = u(3,3,g2)
...
G = u(3,3,g63)
</code>```

You are given that u(3,3,2)=7625597484987 to check your code.

Your task is to write a program/function that will output the value of G deterministically, given enough integer size and enough time.

References

Graham's number

Knuth's up-arrow notation

Conway chained arrow notation

Leaderboard

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

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

```

答:
Python, 85 bytes

v=lambda n,m:n*m and v(v(n-1,m)-1,m-1)or 3**-~n
g=lambda n=63:v(2,n and g(n-1)-1or 3)
```

The v function defines the same function as the one found in Dennis's answer: v(n,m) = u(3,n+1,m+1). The g function is a zero-indexed version of the traditional iteration: g(0) = v(2,3), g(n) = v(2,g(n-1)). Thus, g(63) is Graham's number. By setting the default value of the n parameter of the g function to 63, the required output can be obtained by calling g() (with no parameters), thus meeting our requirements for a function submission which takes no input.

Verify the v(2,1) = u(3,3,2) and v(4,0) = u(3,5,1) test cases online: Python 2, Python 3

Title: Theoretically output Graham's number

Body:
Python, 85 bytes

v=lambda n,m:n*m and v(v(n-1,m)-1,m-1)or 3**-~n
g=lambda n=63:v(2,n and g(n-1)-1or 3)

The v function defines the same function as the one found in Dennis's answer: v(n,m) = u(3,n+1,m+1). The g function is a zero-indexed version of the traditional iteration: g(0) = v(2,3), g(n) = v(2,g(n-1)). Thus, g(63) is Graham's number. By setting the default value of the n parameter of the g function to 63, the required output can be obtained by calling g() (with no parameters), thus meeting our requirements for a function submission which takes no input.

Verify the v(2,1) = u(3,3,2) and v(4,0) = u(3,5,1) test cases online: Python 2, Python 3


答:
C, 161 bytes

```<code>u(int a, int b){if(a==1)return 3;if(b==1)return pow(3,a);return u(u(a-1,b),b-1);}
g(int a){if(a==1)return u(3,4);return u(3,g(a-1));}
main(){printf("%d",g(64));}
</code>```

EDIT: saved 11 bytes by removing tabs and newlines.
EDIT: thx auhmann saved another byte and fixed my program

Title: Theoretically output Graham's number

Body:
Graham's number G is defined in this way:

```<code>u(3,n,1) = 3^n
u(3,1,m) = 3
u(3,n,m) = u(3,u(3,n-1,m),m-1)
[Knuth's up-arrow notation]
[Conway chained arrow notation]

THEN

g1 = u(3,3,4)
g2 = u(3,3,g1)
g3 = u(3,3,g2)
...
G = u(3,3,g63)
</code>```

You are given that u(3,3,2)=7625597484987 to check your code.

Your task is to write a program/function that will output the value of G deterministically, given enough integer size and enough time.

References

Graham's number

Knuth's up-arrow notation

Conway chained arrow notation

Leaderboard

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

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

```

Body:
C, 161 bytes

u(int a, int b){if(a==1)return 3;if(b==1)return pow(3,a);return u(u(a-1,b),b-1);}
g(int a){if(a==1)return u(3,4);return u(3,g(a-1));}
main(){printf("%d",g(64));}

EDIT: saved 11 bytes by removing tabs and newlines.
EDIT: thx auhmann saved another byte and fixed my program


问:
Holiday Gift Exchange
Another problem from our internal golfing...this one around the holidays last year.

PROBLEM

Andy, Barb, Carl, Didi, Earl, and Fran are buying gifts for each other. Draw names for a gift exchange.

Each person buys one gift and receives one gift.

Nobody buys their own gift.

Running the solution multiple times should produce different results (giver-receiver pair should not be predictable or identical from run to run).

INPUT

None.

OUTPUT

Formatted as in this example:

Andy buys for Barb

  Barb buys for Carl

  Carl buys for Didi

  Didi buys for Earl

  Earl buys for Fran

  Fran buys for Andy

答:
C#, 210 183 characters

```<code>using System;class a{static void Main(){var n="Andy Barb Carl Didi Earl Fran".Split();var c=0,i=new Random().Next(1,6);for(;c<6;c++)Console.WriteLine(n[c]+" buys for "+n[(c+i)%6]);}}
</code>```

Heaps of boilerplate :(

This solution isn't totally random - there are always one or more "loops" of people e.g. A->C->E->A, and the offsets are always the same in the loops. However, it is not possible to predict the output of a particular run unless you have part of that output.

ContentLicense: CC BY-SA 2.5

Title: Holiday Gift Exchange

Body:
C#, 210 183 characters

using System;class a{static void Main(){var n="Andy Barb Carl Didi Earl Fran".Split();var c=0,i=new Random().Next(1,6);for(;c<6;c++)Console.WriteLine(n[c]+" buys for "+n[(c+i)%6]);}}

Heaps of boilerplate :(

This solution isn't totally random - there are always one or more "loops" of people e.g. A->C->E->A, and the offsets are always the same in the loops. However, it is not possible to predict the output of a particular run unless you have part of that output.


答:
Java, 81 characters (113 bytes)

```<code>int r(int a,int b){return "⍄䐲㑦晃䚈衤䚈衤䚈衤䚈衤㑦晃⍄䐲".codePointAt(a*2+b/4)>>(3-b%4)*4&15;}
</code>```

Encode the whole result table as unicode table and then get appropriate bytes doing bitwise operations.

You can see it online here: https://ideone.com/K9BojC

Title: Knight on the Rim is Grim

Body:
Introduction

Aron Nimzowitsch was a leading chess master and a influential chess writer.

In his book 'My System', the first chapter deals about the importance of the center and why you should dominate it. The simple reason is that your pieces have more possible direct next moves when being in the center which again gives the player more power.

This gets very clear when looking at different positions of a knight and its potential next moves (shown in pink) on an empty board:

Objective

Evaluate the number of potential direct next moves of a knight on an empty board based on its position.

Input Specs

The position of the knight.

First the x (column) and then the y (row). 0 0 is the left bottom corner.

For simplicity, I changed the labels of a chess board to numbers only. For our examples and test cases we use a 0-based index, you are free to use a 1-based index though.

You can use any type of possible input formats, an array, function arguments, etc.

Output Specs

The number of potential direct next moves for a knight on an empty board.

Test Cases

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

Test cases are employing a 0-based index. The full grid of values is:

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

Body:
Java, 81 characters (113 bytes)

int r(int a,int b){return "⍄䐲㑦晃䚈衤䚈衤䚈衤䚈衤㑦晃⍄䐲".codePointAt(a*2+b/4)>>(3-b%4)*4&15;}

Encode the whole result table as unicode table and then get appropriate bytes doing bitwise operations.

You can see it online here: https://ideone.com/K9BojC


问:
Product over a range
Your task is simple: given two integers \$a\$ and \$b\$, output \$\Pi[a,b]\$; that is, the product of the range between \$a\$ and \$b\$. You may take \$a\$ and \$b\$ in any reasonable format, whether that be arguments to a function, a list input, STDIN, et cetera. You may output in any reasonable format, such as a return value (for functions) or STDOUT. \$a\$ will always be less than \$b\$.

Note that the end may be exclusive or inclusive of \$b\$. I'm not picky. ^_^

Test cases

```<code>[a,b) => result
[2,5) => 24
[5,10) => 15120
[-4,3) => 0
[0,3) => 0
[-4,0) => 24

[a,b] => result
[2,5] => 120
[5,10] => 151200
[-4,3] => 0
[0,3] => 0
[-4,-1] => 24
</code>```

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

Leaderboard

The Stack Snippet at the bottom of this post generates the catalog 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>```

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

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

```

答:
><>, 33 bytes

```<code> 1&:@$:@)?\&n;
:$@:+1&*&:/?@@$@)@
</code>```

My first fish attempt.

Inclusive range

Assumes a and b are on the stack.

ContentLicense: CC BY-SA 4.0

Title: Product over a range

Body:
><>, 33 bytes

 1&:@$:@)?\&n;
:$@:+1&*&:/?@@$@)@

My first fish attempt.

Inclusive range

Assumes a and b are on the stack.


答:
Swift, <s>26</s> 58 bytes

```<code>func p(a:Int,b:Int)->Int{return(a+1..<b).reduce(a){$0*$1}}
</code>```

Title: Product over a range

Body:
Your task is simple: given two integers \$a\$ and \$b\$, output \$\Pi[a,b]\$; that is, the product of the range between \$a\$ and \$b\$. You may take \$a\$ and \$b\$ in any reasonable format, whether that be arguments to a function, a list input, STDIN, et cetera. You may output in any reasonable format, such as a return value (for functions) or STDOUT. \$a\$ will always be less than \$b\$.

Note that the end may be exclusive or inclusive of \$b\$. I'm not picky. ^_^

Test cases

```<code>[a,b) => result
[2,5) => 24
[5,10) => 15120
[-4,3) => 0
[0,3) => 0
[-4,0) => 24

[a,b] => result
[2,5] => 120
[5,10] => 151200
[-4,3] => 0
[0,3] => 0
[-4,-1] => 24
</code>```

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

Leaderboard

The Stack Snippet at the bottom of this post generates the catalog 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>```

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

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

```

Body:
Swift, <s>26</s> 58 bytes

func p(a:Int,b:Int)->Int{return(a+1..<b).reduce(a){$0*$1}}


问:
Autonest an array
Everybody loves nested lists! However, sometimes it's hard to make a nested list. You have to decide if you want to nest it deeper, or if you need to nest it shallower. So for your challenge, you must "Autonest" a list. To autonest a list, compare every pair of items in the list.

If the second item is smaller, separate the two elements by inserting closing and opening brackets between them, like this:

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

For example, {2, 1} becomes {2}, {1}, and {3, 2, 1} becomes {3}, {2}, {1}

If the second item is the same, then change nothing. For example, {1, 1, 1} stays the same, and {2, 1, 1, 1} would become {2}, {1, 1, 1}.

If the second item is larger, then nest every following item one level deeper. For example, {1, 2} would become {1, {2}} and {1, 2, 3} would become {1, {2, {3}}}

The Challenge

You must write a program or function that takes in a list of numbers, and returns the same list after being autonested. Take this input in your languages native list format (or the closest alternative) or as a string. You do not have to use curly braces like I did in my examples. You can use whichever type of brackets are most natural in your language, as long as this is consistent. You can safely assume the list will only contain integers. You can also assume the list will have at least 2 numbers in it. Here is some sample IO:

```<code>{1, 3, 2}                         -->   {1, {3}, {2}}
{1, 2, 3, 4, 5, 6}                -->   {1, {2, {3, {4, {5, {6}}}}}}
{6, 5, 4, 3, 2, 1}                -->   {6}, {5}, {4}, {3}, {2}, {1}
{7, 3, 3, 2, 6, 4}                -->   {7}, {3, 3}, {2, {6}, {4}}
{7, 3, 1, -8, 4, 8, 2, -9, 2, 8}  -->   {7}, {3}, {1}, {-8, {4, {8}, {2}, {-9, {2, {8}}}}}
</code>```

Standard loopholes apply, and the shortest answer in bytes wins!

答:
JavaScript (ES6), 73 bytes

```<code>a=>a.map(r=>l-r?(n=l<r?m:n).push(m=[l=r]):m.push(l),l=a[0],o=n=[m=[]])&&o
</code>```

Explanation: The case of consecutive equal items is easy; the item is just added to the innermost array (here represented by the m variable; n is the array that contains m as its last element, while o is the output). For the case of different items, the item always goes in a new innermost array, the only difference being whether that array is a sibling or a child of the previous innermost array. For extra golfiness I set up the arrays so that the initial item counts as a consecutive equal item.

Title: Autonest an array

Body:
JavaScript (ES6), 73 bytes

a=>a.map(r=>l-r?(n=l<r?m:n).push(m=[l=r]):m.push(l),l=a[0],o=n=[m=[]])&&o

Explanation: The case of consecutive equal items is easy; the item is just added to the innermost array (here represented by the m variable; n is the array that contains m as its last element, while o is the output). For the case of different items, the item always goes in a new innermost array, the only difference being whether that array is a sibling or a child of the previous innermost array. For extra golfiness I set up the arrays so that the initial item counts as a consecutive equal item.


答:
Haskell, <s>140</s> 132 bytes

Thanks @nimi for saving a few bytes!

import Data.List
h s|m<-length s=nub[k|l<-s!!0,k<-('(':l++")"):[u++v|n<-[0..m-2],u<-s!!n,v<-s!!(m-2-n)]]:s
f n=iterate h[[""]]!!n!!0
```

First of all: iterate does create a recursion sequecnce of h, but this is a builtin, and by the rules we may use builtins that use recursion.

This is just a very simple recursive approach, we can generate the n-Dyck-words by putting (n-1)-Dyck-words between paranthesis, or by concatenating from shorter Dyck words. This approach however does generate duplicates, that is why we filter for unique elements using nub.

As Haskell is a functional language, it is almost impossible to do this without recursion. There is an even more direct approach, but that one is banned under the current rules.

Body:
Haskell, <s>140</s> 132 bytes

Thanks @nimi for saving a few bytes!

import Data.List
h s|m<-length s=nub[k|l<-s!!0,k<-('(':l++")"):[u++v|n<-[0..m-2],u<-s!!n,v<-s!!(m-2-n)]]:s
f n=iterate h[[""]]!!n!!0

First of all: iterate does create a recursion sequecnce of h, but this is a builtin, and by the rules we may use builtins that use recursion.

This is just a very simple recursive approach, we can generate the n-Dyck-words by putting (n-1)-Dyck-words between paranthesis, or by concatenating from shorter Dyck words. This approach however does generate duplicates, that is why we filter for unique elements using nub.

As Haskell is a functional language, it is almost impossible to do this without recursion. There is an even more direct approach, but that one is banned under the current rules.


答:
J, <s>97</s> <s>70</s> <s>69</s> <s>68</s> <s>60</s> 59 bytes

```<code>'()'{~(,:'')((((>:#-+/)*(]#>:2*+/))"1#]),.&0,,.&1)^:(2*[)~]
</code>```

Now tacit!

This is a monad that uses binary digits to create pairs of parentheses. In order to meet the requirements, a non-recursive approach is used along with optimization by use of certain primitives to ensure that mostly boolean (1 byte) values are used to keep memory requirements low.

On my computer, using an i7-4770k, it takes about 50 seconds to compute the result for n = 15 and uses about 1.5 GB of memory.

In the interests of maximizing speed, this version with 70 bytes computes the result for n = 15 in 0.5 seconds while using about 800 MB of memory. It's also tacit!

```<code>'()'{~[:;@(<@([:,/],"1/0=|."1)/.~+/"1)<:1&(],(+/<:#-+/)"1@,.~#,.~)1$0:
</code>```

Usage

```<code>   f =: '()'{~(,:'')((((>:#-+/)*(]#>:2*+/))"1#]),.&0,,.&1)^:(2*[)~]
   timer =: 6!:2
   f 3
()()()
(())()
()(())
(()())
((()))
   10 timer 'r =: f 15'  NB. Average time over 10 runs
49.9951
   # r
9694845
</code>```

Body:
J, <s>97</s> <s>70</s> <s>69</s> <s>68</s> <s>60</s> 59 bytes

'()'{~(,:'')((((>:#-+/)*(]#>:2*+/))"1#]),.&0,,.&1)^:(2*[)~]

Now tacit!

This is a monad that uses binary digits to create pairs of parentheses. In order to meet the requirements, a non-recursive approach is used along with optimization by use of certain primitives to ensure that mostly boolean (1 byte) values are used to keep memory requirements low.

On my computer, using an i7-4770k, it takes about 50 seconds to compute the result for n = 15 and uses about 1.5 GB of memory.

In the interests of maximizing speed, this version with 70 bytes computes the result for n = 15 in 0.5 seconds while using about 800 MB of memory. It's also tacit!

'()'{~[:;@(<@([:,/],"1/0=|."1)/.~+/"1)<:1&(],(+/<:#-+/)"1@,.~#,.~)1$0:

Usage

   f =: '()'{~(,:'')((((>:#-+/)*(]#>:2*+/))"1#]),.&0,,.&1)^:(2*[)~]
   timer =: 6!:2
   f 3
()()()
(())()
()(())
(()())
((()))
   10 timer 'r =: f 15'  NB. Average time over 10 runs
49.9951
   # r
9694845