Code Golf: Rotating Maze

2019-02-01 21:47发布

Code Golf: Rotating Maze


Make a program that takes in a file consisting of a maze. The maze has walls given by #. The maze must include a single ball, given by a o and any number of holes given by a @. The maze file can either be entered via command line or read in as a line through standard input. Please specify which in your solution.

Your program then does the following:

1: If the ball is not directly above a wall, drop it down to the nearest wall.
2: If the ball passes through a hole during step 1, remove the ball.
3: Display the maze in the standard output (followed by a newline).
   Extraneous whitespace should not be displayed.
   Extraneous whitespace is defined to be whitespace outside of a rectangle 
   that fits snugly around the maze.
4: If there is no ball in the maze, exit.
5: Read a line from the standard input. 
   Given a 1, rotate the maze counterclockwise. 
   Given a 2, rotate the maze clockwise. 
   Rotations are done by 90 degrees. 
   It is up to you to decide if extraneous whitespace is allowed.
   If the user enters other inputs, repeat this step.
6: Goto step 1.

You may assume all input mazes are closed. Note: a hole effectively acts as a wall in this regard.

You may assume all input mazes have no extraneous whitespace.

The shortest source code by character count wins.


Example written in javascript: http://trinithis.awardspace.com/rotatingMaze/maze.html


Example mazes:

######
#o  @#
######

###########
#o        #
# ####### #
###@      #
  #########

###########################
#                         #
#       #     @           #
#       #         #      ##
#       #         ####o####
 #      #                 #
  #                       #
   #              #########
    #                     @
     ######################

7条回答
\"骚年 ilove
2楼-- · 2019-02-01 22:14

C# 3.0 - 650 638 characters

(not sure how newlines being counted) (leading whitespace for reading, not counted)

using System.Linq;
using S=System.String;
using C=System.Console;
namespace R
{
class R
{
static void Main(S[]a)
{
S m=S.Join("\n",a);
bool u;
do
{
 m=L(m);
 int b=m.IndexOf('o');
 int h=m.IndexOf('@',b);
 b=m.IndexOf('#',b);
 m=m.Replace('o',' ');
 u=(b!=-1&b<h|h==-1);
 if (u)
  m=m.Insert(b-1,"o").Remove(b,1);
 m=L(L(L(m)));
 C.WriteLine(m);
 if (!u) return;
 do
 {
  int.TryParse(C.ReadLine(),out b);
  u=b==1|b==2;
  m=b==1?L(L(L(m))):u?L(m):m;
 }while(!u);
}while(u);
}
static S L(S s)
{
return S.Join("\n",
 s.Split('\n')
 .SelectMany(z => z.Select((c,i)=>new{c,i}))
 .GroupBy(x =>x.i,x=>x.c)
 .Select(g => new S(g.Reverse().ToArray()))
 .ToArray());
}
}
}

Reads from commandline, here's the test line I used:

"###########" "#o        #" "# ####### #" "###@      #" "  #########"

Relied heavily on mobrule's Perl answer for algorithm.

My Rotation method (L) can probably be improved.

Handles wall-less case.

查看更多
登录 后发表回答