问:
Design and Solve a Maze [on hold while sandboxing]
Your task is to play the roles of both characters in this scene from Inception. In it, Cobb gives Ariadne a challenge:

You have two minutes to design a maze that takes one minute to solve.

Some liberties will be taken on that description. Most importantly, this challenge is not time-based, rather scores are based on the effectiveness of your mazes and maze-solvers.

I apologize for the many edits to this challenge as we iterate towards an easy and fair format..

Part I: Maze format

All mazes are square. A cell in the maze is represented as a zero-indexed tuple row column.

Walls are represented by two binary strings: one for horizontal walls (which block movement between rows) and vertical walls (vice versa). On an NxN maze, there are Nx(N-1) possible walls of each type. Let's take a 3x3 example where the cells are labelled:

```<code>A   B | C
   ---
D | E   F
   ---
G   H | I
</code>```

all possible vertical walls are: AB BC DE EF GH HI. Translated into a string, the walls shown are 011001 for vertical walls and 010010 for horizontal walls. Also, by "binary string" I mean "the characters '0' and '1'".

The full maze format is a string which contains, in this order:

width

start cell tuple

end cell tuple

horizontal walls

vertical walls

For example, this maze:

```<code>   0 1 2 3 4
   _________
0 | |  E|  _|
1 |  _|_|_  |
2 |_ _ _  | |
3 |  _ _  | |
4 |____S|___|
start:(4,2)
end:(0,2)
</code>```

is formatted to this:

```<code>5
4 2
0 2
00001011101110001100
10100110000100010010
</code>```

Part II: The Architect

The Architect program creates the maze. It must play by the rules and provide a valid maze (one where a solution exists, and the end is not on top of the start).

Input: Two positive integers:

```<code>size [random seed]
</code>```

Where size will be in [15, 50]. You are encouraged to make use of the random seed so that matches can be replayed, although it is not required.

Output: A valid size x size (square) maze using the format described in Part I. "valid" means that a solution exists, and the start cell is not equal to the end cell.

The score of an Architect on a given maze is

```<code>   # steps taken to solve
–––––––––––––––––––––––––––––
max(dist(start,end),(# walls))
</code>```

So architects are rewarded for complex mazes, but penalized for each wall built (this is a substitute for Ariadne's time restriction). The dist() function ensures that a maze with no walls does not get an infinite score. The outside borders of the maze do not contribute to the wall count.

Part III: The Solver

The Solver attempts to solve mazes generated by others' architects. There is a sort of fog-of-war: only walls adjacent to visited cells are included (all others are replaced with '?')

input: the same maze format, but with '?' where walls are unknown, an extra line for the current location, and a comma-separated list of valid choices from this location. (This is a big edit that is meant to make it simpler to write a maze-parsing function)

example (same as the above 5x5 maze after taking one step left)

```<code>5
4 2
0 2
???????????????011??
????????????????001?
4 1
4 0,4 2
</code>```

Which corresponds something like this, where ? is fog:

```<code>   0 1 2 3 4
   _________
0 |????E????|
1 |?????????|
2 |?????????|
3 | ?_?_????|
4 |__C_S|_?_|
</code>```

output: One of the tuples from the list of valid choices

Each Solver's score is the inverse of the Architect's score.

Part IV: King of the Hill

Architects and Solvers are given separate scores, so there could potentially be two winners.

Each pair of architects and solvers will have many chances to outwit each other. Scores will be averaged over all tests and opponents. Contrary to code golf conventions, highest average score wins!

I intend for this to be ongoing, but I can't guarantee continued testing forever! Let's say for now that a winner will be declared in one week.

Part V: Submitting

I maintain veto power over all submissions - cleverness is encouraged, but not if it breaks the competition or my computer! (If I can't tell what your code does, I will probably veto it)

Come up with a name for your Architect/Solver pair. Post your code along with instructions on how to run it.

Coming soon: an updated python test kit for the new format. Big changes happened to allow any language submissions.

答:
BuildFun and SolveFun

Well, this took quite a while and I'm not entirely sure if the solver is cheating or not. While it has access to the entire maze all of the time, it only looks at the cell it's in, the walls surrounding it and, if there isn't a wall between them, the cells adjacent to it. If this is against the rules please let me know and I'll try to change it.

Anyway, here's the code:

```<code>#Architect function
def BuildFun(size,seed):
   #Initialise grid and ensure inputs are valid
   if size<15:size=15
   if size>50:size=50
   if seed<4:seed=4
   if seed>size:seed=size
   grid=[]
   for x in range(size):
      gridbuilder=[]
      for y in range(size):gridbuilder.append([0,1,1])
      grid.append(gridbuilder)
   coords=[0,0]
   grid[0][0][0]=1
   #Generate maze
   while 1:
      #Choose a preffered direction based on location in grid and seed
      pref=((((coords[0]+coords[1]+2)*int(size/2))%seed)+(seed%(abs(coords[0]-coords[1])+1)))%4
      #Find legal moves
      opt=[]
      if coords[0]>0:opt+=[0] if grid[coords[0]-1][coords[1]][0]==0 else []
      if coords[1]<size-1:opt+=[1] if grid[coords[0]][coords[1]+1][0]==0 else []
      if coords[0]<size-1:opt+=[2] if grid[coords[0]+1][coords[1]][0]==0 else []
      if coords[1]>0:opt+=[3] if grid[coords[0]][coords[1]-1][0]==0 else []
      #There are legal moves
      if len(opt)>0:
         moved=False
         while not moved:
            #Try to move in preffered direction
            if pref in opt:
               if pref==0:
                  coords[0]-=1
                  grid[coords[0]][coords[1]][0]=1
                  grid[coords[0]][coords[1]][2]=0
               elif pref==1:
                  grid[coords[0]][coords[1]][1]=0
                  coords[1]+=1
                  grid[coords[0]][coords[1]][0]=1
               elif pref==2:
                  grid[coords[0]][coords[1]][2]=0
                  coords[0]+=1
                  grid[coords[0]][coords[1]][0]=1
               else:
                  coords[1]-=1
                  grid[coords[0]][coords[1]][0]=1
                  grid[coords[0]][coords[1]][1]=0
               moved=True
            #Change preferred direction if unable to move
            else:
               pref+=1
               if pref==4:pref=0
      #There aren't legal moves
      else:
         moved=False
         #Return to a previously visited location
         if not moved:
            try:
               if grid[coords[0]-1][coords[1]][0]==1 and grid[coords[0]-1][coords[1]][2]==0:
                  grid[coords[0]][coords[1]][0]=2
                  coords[0]-=1
                  moved=True
            except:pass
         if not moved:
            try:
               if grid[coords[0]][coords[1]+1][0]==1 and grid[coords[0]][coords[1]][1]==0:
                  grid[coords[0]][coords[1]][0]=2
                  coords[1]+=1
                  moved=True
            except:pass
         if not moved:
            try:
               if grid[coords[0]+1][coords[1]][0]==1 and grid[coords[0]][coords[1]][2]==0:
                  grid[coords[0]][coords[1]][0]=2
                  coords[0]+=1
                  moved=True
            except:pass
         if not moved:
            try:
               if grid[coords[0]][coords[1]-1][0]==1 and grid[coords[0]][coords[1]-1][1]==0:
                  grid[coords[0]][coords[1]][0]=2
                  coords[1]-=1
                  moved=True
            except:pass
      #Check if finished
      fin=True
      for x in grid:
         for y in x:
            if y[0]==0:
               fin=False
               break
         if not fin:break
      if fin:break
   for x in grid:
      for y in x:
         y[0]=0
   #Find positions for start and finish such that the route between them is as long as possible
   lsf=[[0,0],[0,0],0]
   for y in range(size):
      for x in range(size):
         #Check all start positions
         lengths=[]
         coords=[[y,x,4,0]]
         while len(coords)>0:
            #Spread tracers out from start to the rest of the maze
            for coord in coords:
               opt=[]
               if coord[0]>0:opt+=[0] if grid[coord[0]-1][coord[1]][2]==0 else []
               opt+=[1] if grid[coord[0]][coord[1]][1]==0 else []
               opt+=[2] if grid[coord[0]][coord[1]][2]==0 else []
               if coord[1]>0:opt+=[3] if grid[coord[0]][coord[1]-1][1]==0 else []
               try:opt.remove(coord[2])
               except:pass
               #Dead end, tracer dies and possible end point is recorded along with length
               if len(opt)==0:
                  lengths.append([coord[0],coord[1],coord[3]])
                  coords.remove(coord)
               else:
                  #Create more tracers at branch points
                  while len(opt)>1:
                     if opt[0]==0:coords.append([coord[0]-1,coord[1],2,coord[3]+1])
                     elif opt[0]==1:coords.append([coord[0],coord[1]+1,3,coord[3]+1])
                     elif opt[0]==2:coords.append([coord[0]+1,coord[1],0,coord[3]+1])
                     else:coords.append([coord[0],coord[1]-1,1,coord[3]+1])
                     del opt[0]
                  if opt[0]==0:
                     coord[0]-=1
                     coord[2]=2
                     coord[3]+=1
                  elif opt[0]==1:
                     coord[1]+=1
                     coord[2]=3
                     coord[3]+=1
                  elif opt[0]==2:
                     coord[0]+=1
                     coord[2]=0
                     coord[3]+=1
                  else:
                     coord[1]-=1
                     coord[2]=1
                     coord[3]+=1
         #Find furthest distance and, if it's longer than the previous one, the start/end positions get updated
         lengths=sorted(lengths,key=lambda x:x[2],reverse=True)
         if lengths[0][2]>lsf[2]:lsf=[[y,x],[lengths[0][0],lengths[0][1]],lengths[0][2]]
   #Find number of walls and output maze
   w=draw(grid,size,lsf[0],lsf[1])
   #Output maze information
   print('Start = '+str(lsf[0]))
   print('End = '+str(lsf[1]))
   print('Distance = '+str(lsf[2]))
   print('Walls = '+str(w))
   print('Score = '+str(float(lsf[2])/float(w))[:5])
   #Convert array grid to binary strings horizontal and vertical
   horizontal=vertical=''
   for y in range(size):
      for x in range(size-1):vertical+=str(grid[y][x][1])
   for y in range(size-1):
      for x in range(size):horizontal+=str(grid[y][x][2])
   #Save maze information to text file for use with SolveFun
   save=open('Maze.txt','w')
   save.write(str(size)+'\n'+str(lsf[0][0])+' '+str(lsf[0][1])+'\n'+str(lsf[1][0])+' '+str(lsf[1][1])+'\n'+horizontal+'\n'+vertical)
   save.close()
#Solver function
def SolveFun():
   try:
      #Get maze information from text file
      save=open('Maze.txt','r')
      data=save.readlines()
      save.close()
      size=int(data[0])
      s=data[1].rsplit(' ')
      start=[int(s[0]),int(s[1])]
      e=data[2].rsplit(' ')
      end=[int(e[0]),int(e[1])]
      horizontal=data[3].rstrip('\n')
      vertical=data[4]
      #Build maze from information
      grid=[]
      for y in range(size):
         grid.append([])
         for x in range(size):
            grid[y].append([0,1,1])
      for y in range(size):
         for x in range(size-1):
            grid[y][x][1]=int(vertical[y*(size-1)+x])
      for y in range(size-1):
          for x in range(size):
            grid[y][x][2]=int(horizontal[y*size+x])
      path=''
      cpath=''
      bs=0
      pos=start[:]
      grid[pos[0]][pos[1]][0]=1
      while pos!=end:
         #Want to move in direction of finish
         if end[0]<pos[0] and pos[0]-end[0]>=abs(pos[1]-end[1]):pref=0
         elif end[1]>pos[1] and end[1]-pos[1]>=abs(pos[0]-end[0]):pref=1
         elif end[0]>pos[0] and end[0]-pos[0]>=abs(pos[1]-end[1]):pref=2
         else:pref=3
         #Find legal moves
         opt=[]
         if pos[0]>0:
            if grid[pos[0]-1][pos[1]][2]==0:opt+=[0]if grid[pos[0]-1][pos[1]][0]==0 else[]
         if pos[1]>0:
            if grid[pos[0]][pos[1]-1][1]==0:opt+=[3]if grid[pos[0]][pos[1]-1][0]==0 else[]
         if grid[pos[0]][pos[1]][2]==0:opt+=[2]if grid[pos[0]+1][pos[1]][0]==0 else[]
         if grid[pos[0]][pos[1]][1]==0:opt+=[1]if grid[pos[0]][pos[1]+1][0]==0 else[]
         if len(opt)>0:
            moved=False
            while not moved:
               #Try to move in preferred direction
               if pref in opt:
                  if pref==0:
                     pos[0]-=1
                     path+='0'
                     cpath+='0'
                  elif pref==1:
                     pos[1]+=1
                     path+='1'
                     cpath+='1'
                  elif pref==2:
                     pos[0]+=1
                     path+='2'
                     cpath+='2'
                  else:
                     pos[1]-=1
                     path+='3'
                     cpath+='3'
                  grid[pos[0]][pos[1]][0]=1
                  moved=True
               #Change preferred direction by 1
               else:
                  pref=(pref+1)%4
         #No legal moves, backtrack
         else:
            bs+=1
            grid[pos[0]][pos[1]][0]=2
            if int(cpath[len(cpath)-1])==0:
               pos[0]+=1
               path+='2'
            elif int(cpath[len(cpath)-1])==1:
               pos[1]-=1
               path+='3'
            elif int(cpath[len(cpath)-1])==2:
               pos[0]-=1
               path+='0'
            else:
               pos[1]+=1
               path+='1'
            cpath=cpath[:len(cpath)-1]
      #Output maze with solution as well as total steps and wasted steps
      draw(grid,size,start,end)
      print('\nPath taken:')
      print(str(len(path))+' steps')
      print(str(bs)+' backsteps')
      print(str(bs*2)+' wasted steps')
   except:print('Could not find maze')
def draw(grid,size,start,end):
   #Build output in string d
   d='   '
   for x in range(size):d+=' '+str(x)[0]
   d+='\n   '
   for x in range(size):d+='  ' if len(str(x))==1 else ' '+str(x)[1]
   d+='\n    '+'_'*(size*2-1)
   w=0
   for y in range(size):
      d+='\n'+str(y)+'  |' if len(str(y))==1 else '\n'+str(y)+' |'
      for x in range(size):
         if grid[y][x][2]:
            if start==[y,x]:d+=UL.S+'S'+UL.E
            elif end==[y,x]:d+=UL.S+'F'+UL.E
            elif grid[y][x][0]==1:d+=UL.S+'*'+UL.E
            else:d+='_'
            w+=1
         else:
            if start==[y,x]:d+='S'
            elif end==[y,x]:d+='F'
            elif grid[y][x][0]==1:d+='*'
            else:d+=' '
         if grid[y][x][1]:
            d+='|'
            w+=1
         else:d+=' '
   #Output maze and return number of walls
   print(d)
   w-=size*2
   return w
#Underlines text
class UL:
   S = '\033[4m'
   E = '\033[0m'
</code>```

I realise that this is ridiculously long and not particularly easy to read, but I'm lazy so this is how it's staying.

BuildFun

The architect, BuildFun, is a fairly simple maze generating program that will always create a 'perfect' maze (one with no loops and where any two points will always have exactly one path between them). It bases its logic off of the seed input meaning that the mazes generated are pseudo-random with what often appear to be repeating patterns and, with the same seed and size, the same maze will be created.

Once the maze is generated, the program will attempt to maximise the maze's score by searching for the start point and end point that result in the longest path between them. To do this, it runs through every start point, spreads out tracers to find the end point furthest from it, and picks the combination with the longest path.

After this, it draws the maze, counts the walls and outputs the maze's information. This is the start point, end point, distance between them, number of walls and score. It also formats this information into the style described above for size, start and end, horizontal walls and vertical walls and saves this into a text file called Maze.txt for use later.

SolveFun

The solver, SolveFun, uses the text file Maze.txt as the input and works in a very similar way to the architect. For every move, it will choose a direction that it wants to go based on its relative position to the end and then it will look at the walls surrounding it. If a wall is not there, it will check to see if it has been in the cell adjacent to it and, if not, it will be added as  possible option. It will then move in the direction closest to its preferred direction provided it has options. If it doesn't have options, it will backtrack until it does. This continues until it reaches the end.

As it moves, it records the path it is taking in the variable path which is used at the end to output the total number of steps. It also records the amount of times it had to backtrack used to calculate wasted steps at the end. When it reaches the end, it will output the maze with the shortest path from start to end marked on with *s.

How to Run

Due to the method of outputting the maze (which includes underlining certain characters), this has to be run from a command line in the form

python -c 'import filename;filename.BuildFun(Size, Seed)'

and

python -c 'import filename;filename.SolveFun()'

where Size is an integer between 15 and 50 (inclusive) and Seed is an integer between 4 and Size (inclusive).

Body:
BuildFun and SolveFun

Well, this took quite a while and I'm not entirely sure if the solver is cheating or not. While it has access to the entire maze all of the time, it only looks at the cell it's in, the walls surrounding it and, if there isn't a wall between them, the cells adjacent to it. If this is against the rules please let me know and I'll try to change it.

Anyway, here's the code:

#Architect function
def BuildFun(size,seed):
   #Initialise grid and ensure inputs are valid
   if size<15:size=15
   if size>50:size=50
   if seed<4:seed=4
   if seed>size:seed=size
   grid=[]
   for x in range(size):
      gridbuilder=[]
      for y in range(size):gridbuilder.append([0,1,1])
      grid.append(gridbuilder)
   coords=[0,0]
   grid[0][0][0]=1
   #Generate maze
   while 1:
      #Choose a preffered direction based on location in grid and seed
      pref=((((coords[0]+coords[1]+2)*int(size/2))%seed)+(seed%(abs(coords[0]-coords[1])+1)))%4
      #Find legal moves
      opt=[]
      if coords[0]>0:opt+=[0] if grid[coords[0]-1][coords[1]][0]==0 else []
      if coords[1]<size-1:opt+=[1] if grid[coords[0]][coords[1]+1][0]==0 else []
      if coords[0]<size-1:opt+=[2] if grid[coords[0]+1][coords[1]][0]==0 else []
      if coords[1]>0:opt+=[3] if grid[coords[0]][coords[1]-1][0]==0 else []
      #There are legal moves
      if len(opt)>0:
         moved=False
         while not moved:
            #Try to move in preffered direction
            if pref in opt:
               if pref==0:
                  coords[0]-=1
                  grid[coords[0]][coords[1]][0]=1
                  grid[coords[0]][coords[1]][2]=0
               elif pref==1:
                  grid[coords[0]][coords[1]][1]=0
                  coords[1]+=1
                  grid[coords[0]][coords[1]][0]=1
               elif pref==2:
                  grid[coords[0]][coords[1]][2]=0
                  coords[0]+=1
                  grid[coords[0]][coords[1]][0]=1
               else:
                  coords[1]-=1
                  grid[coords[0]][coords[1]][0]=1
                  grid[coords[0]][coords[1]][1]=0
               moved=True
            #Change preferred direction if unable to move
            else:
               pref+=1
               if pref==4:pref=0
      #There aren't legal moves
      else:
         moved=False
         #Return to a previously visited location
         if not moved:
            try:
               if grid[coords[0]-1][coords[1]][0]==1 and grid[coords[0]-1][coords[1]][2]==0:
                  grid[coords[0]][coords[1]][0]=2
                  coords[0]-=1
                  moved=True
            except:pass
         if not moved:
            try:
               if grid[coords[0]][coords[1]+1][0]==1 and grid[coords[0]][coords[1]][1]==0:
                  grid[coords[0]][coords[1]][0]=2
                  coords[1]+=1
                  moved=True
            except:pass
         if not moved:
            try:
               if grid[coords[0]+1][coords[1]][0]==1 and grid[coords[0]][coords[1]][2]==0:
                  grid[coords[0]][coords[1]][0]=2
                  coords[0]+=1
                  moved=True
            except:pass
         if not moved:
            try:
               if grid[coords[0]][coords[1]-1][0]==1 and grid[coords[0]][coords[1]-1][1]==0:
                  grid[coords[0]][coords[1]][0]=2
                  coords[1]-=1
                  moved=True
            except:pass
      #Check if finished
      fin=True
      for x in grid:
         for y in x:
            if y[0]==0:
               fin=False
               break
         if not fin:break
      if fin:break
   for x in grid:
      for y in x:
         y[0]=0
   #Find positions for start and finish such that the route between them is as long as possible
   lsf=[[0,0],[0,0],0]
   for y in range(size):
      for x in range(size):
         #Check all start positions
         lengths=[]
         coords=[[y,x,4,0]]
         while len(coords)>0:
            #Spread tracers out from start to the rest of the maze
            for coord in coords:
               opt=[]
               if coord[0]>0:opt+=[0] if grid[coord[0]-1][coord[1]][2]==0 else []
               opt+=[1] if grid[coord[0]][coord[1]][1]==0 else []
               opt+=[2] if grid[coord[0]][coord[1]][2]==0 else []
               if coord[1]>0:opt+=[3] if grid[coord[0]][coord[1]-1][1]==0 else []
               try:opt.remove(coord[2])
               except:pass
               #Dead end, tracer dies and possible end point is recorded along with length
               if len(opt)==0:
                  lengths.append([coord[0],coord[1],coord[3]])
                  coords.remove(coord)
               else:
                  #Create more tracers at branch points
                  while len(opt)>1:
                     if opt[0]==0:coords.append([coord[0]-1,coord[1],2,coord[3]+1])
                     elif opt[0]==1:coords.append([coord[0],coord[1]+1,3,coord[3]+1])
                     elif opt[0]==2:coords.append([coord[0]+1,coord[1],0,coord[3]+1])
                     else:coords.append([coord[0],coord[1]-1,1,coord[3]+1])
                     del opt[0]
                  if opt[0]==0:
                     coord[0]-=1
                     coord[2]=2
                     coord[3]+=1
                  elif opt[0]==1:
                     coord[1]+=1
                     coord[2]=3
                     coord[3]+=1
                  elif opt[0]==2:
                     coord[0]+=1
                     coord[2]=0
                     coord[3]+=1
                  else:
                     coord[1]-=1
                     coord[2]=1
                     coord[3]+=1
         #Find furthest distance and, if it's longer than the previous one, the start/end positions get updated
         lengths=sorted(lengths,key=lambda x:x[2],reverse=True)
         if lengths[0][2]>lsf[2]:lsf=[[y,x],[lengths[0][0],lengths[0][1]],lengths[0][2]]
   #Find number of walls and output maze
   w=draw(grid,size,lsf[0],lsf[1])
   #Output maze information
   print('Start = '+str(lsf[0]))
   print('End = '+str(lsf[1]))
   print('Distance = '+str(lsf[2]))
   print('Walls = '+str(w))
   print('Score = '+str(float(lsf[2])/float(w))[:5])
   #Convert array grid to binary strings horizontal and vertical
   horizontal=vertical=''
   for y in range(size):
      for x in range(size-1):vertical+=str(grid[y][x][1])
   for y in range(size-1):
      for x in range(size):horizontal+=str(grid[y][x][2])
   #Save maze information to text file for use with SolveFun
   save=open('Maze.txt','w')
   save.write(str(size)+'\n'+str(lsf[0][0])+' '+str(lsf[0][1])+'\n'+str(lsf[1][0])+' '+str(lsf[1][1])+'\n'+horizontal+'\n'+vertical)
   save.close()
#Solver function
def SolveFun():
   try:
      #Get maze information from text file
      save=open('Maze.txt','r')
      data=save.readlines()
      save.close()
      size=int(data[0])
      s=data[1].rsplit(' ')
      start=[int(s[0]),int(s[1])]
      e=data[2].rsplit(' ')
      end=[int(e[0]),int(e[1])]
      horizontal=data[3].rstrip('\n')
      vertical=data[4]
      #Build maze from information
      grid=[]
      for y in range(size):
         grid.append([])
         for x in range(size):
            grid[y].append([0,1,1])
      for y in range(size):
         for x in range(size-1):
            grid[y][x][1]=int(vertical[y*(size-1)+x])
      for y in range(size-1):
          for x in range(size):
            grid[y][x][2]=int(horizontal[y*size+x])
      path=''
      cpath=''
      bs=0
      pos=start[:]
      grid[pos[0]][pos[1]][0]=1
      while pos!=end:
         #Want to move in direction of finish
         if end[0]<pos[0] and pos[0]-end[0]>=abs(pos[1]-end[1]):pref=0
         elif end[1]>pos[1] and end[1]-pos[1]>=abs(pos[0]-end[0]):pref=1
         elif end[0]>pos[0] and end[0]-pos[0]>=abs(pos[1]-end[1]):pref=2
         else:pref=3
         #Find legal moves
         opt=[]
         if pos[0]>0:
            if grid[pos[0]-1][pos[1]][2]==0:opt+=[0]if grid[pos[0]-1][pos[1]][0]==0 else[]
         if pos[1]>0:
            if grid[pos[0]][pos[1]-1][1]==0:opt+=[3]if grid[pos[0]][pos[1]-1][0]==0 else[]
         if grid[pos[0]][pos[1]][2]==0:opt+=[2]if grid[pos[0]+1][pos[1]][0]==0 else[]
         if grid[pos[0]][pos[1]][1]==0:opt+=[1]if grid[pos[0]][pos[1]+1][0]==0 else[]
         if len(opt)>0:
            moved=False
            while not moved:
               #Try to move in preferred direction
               if pref in opt:
                  if pref==0:
                     pos[0]-=1
                     path+='0'
                     cpath+='0'
                  elif pref==1:
                     pos[1]+=1
                     path+='1'
                     cpath+='1'
                  elif pref==2:
                     pos[0]+=1
                     path+='2'
                     cpath+='2'
                  else:
                     pos[1]-=1
                     path+='3'
                     cpath+='3'
                  grid[pos[0]][pos[1]][0]=1
                  moved=True
               #Change preferred direction by 1
               else:
                  pref=(pref+1)%4
         #No legal moves, backtrack
         else:
            bs+=1
            grid[pos[0]][pos[1]][0]=2
            if int(cpath[len(cpath)-1])==0:
               pos[0]+=1
               path+='2'
            elif int(cpath[len(cpath)-1])==1:
               pos[1]-=1
               path+='3'
            elif int(cpath[len(cpath)-1])==2:
               pos[0]-=1
               path+='0'
            else:
               pos[1]+=1
               path+='1'
            cpath=cpath[:len(cpath)-1]
      #Output maze with solution as well as total steps and wasted steps
      draw(grid,size,start,end)
      print('\nPath taken:')
      print(str(len(path))+' steps')
      print(str(bs)+' backsteps')
      print(str(bs*2)+' wasted steps')
   except:print('Could not find maze')
def draw(grid,size,start,end):
   #Build output in string d
   d='   '
   for x in range(size):d+=' '+str(x)[0]
   d+='\n   '
   for x in range(size):d+='  ' if len(str(x))==1 else ' '+str(x)[1]
   d+='\n    '+'_'*(size*2-1)
   w=0
   for y in range(size):
      d+='\n'+str(y)+'  |' if len(str(y))==1 else '\n'+str(y)+' |'
      for x in range(size):
         if grid[y][x][2]:
            if start==[y,x]:d+=UL.S+'S'+UL.E
            elif end==[y,x]:d+=UL.S+'F'+UL.E
            elif grid[y][x][0]==1:d+=UL.S+'*'+UL.E
            else:d+='_'
            w+=1
         else:
            if start==[y,x]:d+='S'
            elif end==[y,x]:d+='F'
            elif grid[y][x][0]==1:d+='*'
            else:d+=' '
         if grid[y][x][1]:
            d+='|'
            w+=1
         else:d+=' '
   #Output maze and return number of walls
   print(d)
   w-=size*2
   return w
#Underlines text
class UL:
   S = '\033[4m'
   E = '\033[0m'

I realise that this is ridiculously long and not particularly easy to read, but I'm lazy so this is how it's staying.

BuildFun

The architect, BuildFun, is a fairly simple maze generating program that will always create a 'perfect' maze (one with no loops and where any two points will always have exactly one path between them). It bases its logic off of the seed input meaning that the mazes generated are pseudo-random with what often appear to be repeating patterns and, with the same seed and size, the same maze will be created.

Once the maze is generated, the program will attempt to maximise the maze's score by searching for the start point and end point that result in the longest path between them. To do this, it runs through every start point, spreads out tracers to find the end point furthest from it, and picks the combination with the longest path.

After this, it draws the maze, counts the walls and outputs the maze's information. This is the start point, end point, distance between them, number of walls and score. It also formats this information into the style described above for size, start and end, horizontal walls and vertical walls and saves this into a text file called Maze.txt for use later.

SolveFun

The solver, SolveFun, uses the text file Maze.txt as the input and works in a very similar way to the architect. For every move, it will choose a direction that it wants to go based on its relative position to the end and then it will look at the walls surrounding it. If a wall is not there, it will check to see if it has been in the cell adjacent to it and, if not, it will be added as  possible option. It will then move in the direction closest to its preferred direction provided it has options. If it doesn't have options, it will backtrack until it does. This continues until it reaches the end.

As it moves, it records the path it is taking in the variable path which is used at the end to output the total number of steps. It also records the amount of times it had to backtrack used to calculate wasted steps at the end. When it reaches the end, it will output the maze with the shortest path from start to end marked on with *s.

How to Run

Due to the method of outputting the maze (which includes underlining certain characters), this has to be run from a command line in the form

python -c 'import filename;filename.BuildFun(Size, Seed)'

and

python -c 'import filename;filename.SolveFun()'

where Size is an integer between 15 and 50 (inclusive) and Seed is an integer between 4 and Size (inclusive).


问:
Professor Schwartzman's Acme Canine Decoder 2000

Introduction

We -- especially the geeks among us, who tend to be fans -- all remember this old Far Side cartoon:

Clearly, Professor Schwartzman could have brushed up on his programming skills just a wee bit more before he put his invention to use. But can you replicate it yourself... using as few bytes as possible?

Input Specs

You must create a script that translates dog sounds into appropriately intonated "Hey"s. This is pure code golf; the lowest number of bytes wins.

Your input will consist of some combination of the following tokens:

Bark, Baark, Baaark, Baaaark, ... (that is, B*rk  with at least 1 a replacing the asterisk)

Woof, Wooof, Woooof, ... (W*f with at least 2 os replacing the asterisk)

Grr, Grrr, Grrrr, ..., (G followed by at least 2 rs)

Any number of . (period), ! (exclamation mark) and/or ? (question mark) characters, which may occur anywhere in the input

Note, again, that the Woof-based and Grr-based tokens always require at least two os and rs respectively; Wof and Gr are not valid tokens.

There is no limit on how long a token can be (e.g., how many repeated as there can be in a Bark token); however, your decoder only needs to work correctly for input tokens with up to 10 total as, os, or rs to pass this challenge.

Output Specs

Faithful to Schwartzman's design, your canine decoder program must process it into output text as follows:

Bark, Woof, and Grr become Hey;

Baark, Wooof, and Grrr become Heyy;

Baaark, Woooof, and Grrrr become Heyyy; etc.

For all Bark-based tokens, the number of ys in the output Hey-based token must be equal to the number of as;

For all Woof-based tokens, the number of ys in the output Hey-based token must be one less than the number of os;

For all Grr-based tokens, the number of ys in the output Hey-based token must be one less than the number of rs;

All punctuation (., !, and ?) is left unchanged.

Remember to drop one y from the output for Woofs and Grrs only! The input Baaaaaaaark?, with 8 as, will become Heyyyyyyyy?, with a matching set of 8 ys. However, Woooooooof? becomes only Heyyyyyyy?, with 7 ys.

Again, if you can get your program to work for input tokens of unlimited size, that's great, but for purposes of this challenge, your program will only be checked to ensure that it works properly for input tokens that have no more than 10 repeated letters.

All Bark-, Woof-, and Grr-based tokens in your input are assumed to begin with capital letters. Therefore, there is no need to handle turning Bark grrr into Hey heyy or anything similar.

Example Inputs and Outputs

Input: Bark. Bark! Bark!!

Output: Hey. Hey! Hey!!

Input: Baaaaaark? (six as)

Output: Heyyyyyy? (six ys)

Input: Grrrrrrrr... (eight rs)

Output: Heyyyyyyy... (seven ys)

Input: ?...!

Output: ?...!

Input: Wooof Woof? Grrrr. Baaaark Grr!

Output: Heyy Hey? Heyyy. Heyyyy Hey!

答:
Perl 5, 25 bytes

A Perl copy of Martin Ender's Retina answer. 24 bytes, plus 1 for -pe instead of -e.

```<code>s;\wf?k?;y;g;s;\byy;He;g
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Perl 5, 25 bytes

A Perl copy of Martin Ender's Retina answer. 24 bytes, plus 1 for -pe instead of -e.

s;\wf?k?;y;g;s;\byy;He;g


答:
APL, 16 chars

```<code>{⍵/⍨×⍵|+/¨⍵=,\⍵}
</code>```

In English:

,\⍵: vector of the vector prefixes up to the nth-element of the argument

+/¨⍵=: per prefix vector, count how many are equal to the n-th element itself

×⍵|: signs of the mod's (that is: 0 if the remainder of the division is 0, 1 otherwise)

⍵/⍨: of the argument keep only the element where the mod is 0

Title: Remove every N-th N

Body:
The task

In this challenge, your input is a non-empty list of positive integers, given in the native format of your language.
Your output is that same list, in the same format, with some elements removed.
You shall remove every occurrence of 1, every second occurrence of 2, every third occurrence 3, and so on.
In general, for every positive integer N, you shall remove every Nth occurrence of N from the list, starting with the Nth occurrence.

Example

Consider the input list

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

First, we remove every occurrence of 1:

```<code>[3,2,6,    6,2,3,2,6,6,6,6,  6,6,3,3,7,2]
</code>```

Then every second occurrence of 2:

```<code>[3,2,6,    6,  3,2,6,6,6,6,  6,6,3,3,7  ]
</code>```

Then every third occurrence of 3:

```<code>[3,2,6,    6,  3,2,6,6,6,6,  6,6,  3,7  ]
</code>```

The numbers 4 and 5 don't occur in the input, so they can be skipped.
Next, we remove every sixth occurrence of 6:

```<code>[3,2,6,    6,  3,2,6,6,6,    6,6,  3,7  ]
</code>```

There's only one occurrence of 7, so that can be skipped as well.
Thus the correct output is

```<code>[3,2,6,6,3,2,6,6,6,6,6,3,7]
</code>```

Rules and scoring

You can write either a full program or a function.
The lowest byte count wins, and standard loopholes are disallowed.

Test cases

```<code>[1] -> []
[2] -> [2]
[1,1,1] -> []
[2,2,2] -> [2,2]
[1,1,2,2,2,3,3,3,3] -> [2,2,3,3,3]
[1,2,3,1,2,3,1,2,3,1,2,3] -> [2,3,3,2,3]
[3,2,6,1,1,6,2,3,2,6,6,6,6,1,6,6,3,3,7,2] -> [3,2,6,6,3,2,6,6,6,6,6,3,7]
[5,4,5,4,3,5,4,5,4,5,4,3,5,4,5,3,3,3,4,5,4,5,4,5,4,3,3,3,5,4] -> [5,4,5,4,3,5,4,5,4,3,5,4,5,3,3,4,5,5,4,4,3,3,5,4]
[6,4,5,8,2,9,3,1,8,5,3,5,5,6,3,5,1,2,3,9,3,5,8,7,5,9,1,3,4,8,2,3,4,7,8,5,8,5,3,1] -> [6,4,5,8,2,9,3,8,5,3,5,5,6,3,9,3,5,8,7,5,9,4,8,2,3,4,7,8,5,8,5,3]
[4,4,9,12,9,4,4,4,12,9,12,9,12,4,12,4,4,9,4,9,12,4,12,4,4,12,4,4,9,12,9,12,9,4,9,12,4,9,12,9,12,9,4,9,12,12,4,4,12,4] -> [4,4,9,12,9,4,4,12,9,12,9,12,4,12,4,9,4,9,12,4,12,4,12,4,4,9,12,9,12,4,9,12,9,9,12,9,4,9,12,12,4,4,12]
[2,2,11,11,11,11,6,2,2,6,6,2,2,2,2,6,11,6,11,11,2,11,2,6,6,11,2,11,6,2,6,6,6,6,6,11,2,11,11,6,6,6,11,6,2,6,2,6,6,2,11,2,2,11,11,11,11,2,6,2] -> [2,11,11,11,11,6,2,6,6,2,2,6,11,6,11,11,2,11,6,11,2,11,6,6,6,6,6,2,11,11,6,6,6,11,6,2,6,6,11,2,11,11,11,11,2,6]
[20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102] -> [20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,21,22,100,101,102,20,22,100,101,102,20,21,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,21,22,100,101,102,20,21,22,100,101,102,20,22,100,101,102,20,21,22,100,101,102,20,21,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,21,22,101,102,20,21,22,100,102,20,21,22,100,101,20,21,22,100,101,102,20,21,22,100,101,102,20,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,100,101,102]
</code>```

Leaderboard

Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language.
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 you want to include multiple numbers in your header, 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 leaderboard snippet:

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

var QUESTION_ID=70091,OVERRIDE_USER=32014;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:
APL, 16 chars

{⍵/⍨×⍵|+/¨⍵=,\⍵}

In English:

,\⍵: vector of the vector prefixes up to the nth-element of the argument

+/¨⍵=: per prefix vector, count how many are equal to the n-th element itself

×⍵|: signs of the mod's (that is: 0 if the remainder of the division is 0, 1 otherwise)

⍵/⍨: of the argument keep only the element where the mod is 0


问:
Simplify a square root
Given a positive integer n, simplify the square root √n into the form a√b by extracting all square factors. The outputted a,b should be positive integers with n = a^2 * b with b as small as possible.

You may output a and b in either order in any reasonable format. You may not omit outputs of 1 as implicit.

The outputs for n=1..36 as (a,b):

```<code>1 (1, 1)
2 (1, 2)
3 (1, 3)
4 (2, 1)
5 (1, 5)
6 (1, 6)
7 (1, 7)
8 (2, 2)
9 (3, 1)
10 (1, 10)
11 (1, 11)
12 (2, 3)
13 (1, 13)
14 (1, 14)
15 (1, 15)
16 (4, 1)
17 (1, 17)
18 (3, 2)
19 (1, 19)
20 (2, 5)
21 (1, 21)
22 (1, 22)
23 (1, 23)
24 (2, 6)
25 (5, 1)
26 (1, 26)
27 (3, 3)
28 (2, 7)
29 (1, 29)
30 (1, 30)
31 (1, 31)
32 (4, 2)
33 (1, 33)
34 (1, 34)
35 (1, 35)
36 (6, 1)
</code>```

These are OEIS A000188 and A007913.

Related: A more complex version.

var QUESTION_ID=83814,OVERRIDE_USER=20260;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/83814/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

```

答:
APL, 25 chars

```<code> {(⊢,⍵÷×⍨)1+⍵-0⍳⍨⌽⍵|⍨×⍨⍳⍵}
</code>```

In English:

0⍳⍨⌽⍵|⍨×⍨⍳⍵: index of the largest of the squares up to n that divides completely n;

1+⍵-: the index is in the reversed array, so adjust the index

(⊢,⍵÷×⍨): produce the result: the index itself (a) and the quotient b (that is, n÷a*a)

Test:

```<code>     ↑{(⊢,⍵÷×⍨)⊃z/⍨0=⍵|⍨×⍨z←⌽⍳⍵}¨⍳36
1  1
1  2
1  3
2  1
1  5
1  6
1  7
2  2
3  1
1 10
1 11
2  3
1 13
1 14
1 15
4  1
1 17
3  2
1 19
2  5
1 21
1 22
1 23
2  6
5  1
1 26
3  3
2  7
1 29
1 30
1 31
4  2
1 33
1 34
1 35
6  1
</code>```

Title: Simplify a square root

Body:
APL, 25 chars

 {(⊢,⍵÷×⍨)1+⍵-0⍳⍨⌽⍵|⍨×⍨⍳⍵}

In English:

0⍳⍨⌽⍵|⍨×⍨⍳⍵: index of the largest of the squares up to n that divides completely n;

1+⍵-: the index is in the reversed array, so adjust the index

(⊢,⍵÷×⍨): produce the result: the index itself (a) and the quotient b (that is, n÷a*a)

Test:

     ↑{(⊢,⍵÷×⍨)⊃z/⍨0=⍵|⍨×⍨z←⌽⍳⍵}¨⍳36
1  1
1  2
1  3
2  1
1  5
1  6
1  7
2  2
3  1
1 10
1 11
2  3
1 13
1 14
1 15
4  1
1 17
3  2
1 19
2  5
1 21
1 22
1 23
2  6
5  1
1 26
3  3
2  7
1 29
1 30
1 31
4  2
1 33
1 34
1 35
6  1


问:
Bytes/Character

Task

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

Examples

! → 1

Ciao → 1 1 1 1

tʃaʊ → 1 2 1 2

Adám → 1 1 2 1

ĉaŭ → 2 1 2 (single characters)

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

チャオ → 3 3 3

 (empty input) →  (empty output)

!±≡ → 1 2 3 4

� (a null byte) → 1

Null bytes

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

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

答:
Emacs Lisp, <s>55</s> 49 bytes

```<code>(lambda(s)(mapcar'string-bytes(mapcar'string s)))
</code>```

First dissects the string into a list of characters with (mapcar 'string s). The string function in Emacs Lisp takes a list of characters and builds a string out of them. Due to the way Emacs splits strings with mapcar (i.e. into a list of integers, not characters or strings), this explicit conversion is needed. Then maps the string-bytes function onto that list of strings.

Example:

```<code>(mapcar 'string "abc") ; => ("a" "b" "c")
(mapcar 'string-bytes '("a" "b" "c")) ; => (1 1 1)
</code>```

Testcases:

```<code>(mapcar
 (lambda(s)(mapcar'string-bytes(mapcar'string s)))
 '("!""Ciao""tʃaʊ""Adám""ĉaŭ""ĉaŭ""チャオ""""!±≡""\0"))
;; ((1) (1 1 1 1) (1 2 1 2) (1 1 2 1) (2 1 2) (1 2 1 1 2) (3 3 3) nil (1 2 3 4) (1))
</code>```

<s>Old answer:

```<code>(lambda(s)(mapcar(lambda(s)(string-bytes(string s)))s))
</code>```

Ungolfed:

```<code> (lambda (s)
   (mapcar
    ;; we can't use string-bytes directly,
    ;; since Emacs mapcar yields a list of ints instead of characters
    ;; therefore we need a wrapper function here.
    (lambda (s)
      (string-bytes (string s)))
    s))
</code>```

Testcases:

```<code>(mapcar
 (lambda(s)(mapcar(lambda(s)(string-bytes(string s)))s))
 '("!""Ciao""tʃaʊ""Adám""ĉaŭ""ĉaŭ""チャオ""""!±≡""\0"))
;; ((1) (1 1 1 1) (1 2 1 2) (1 1 2 1) (2 1 2) (1 2 1 1 2) (3 3 3) nil (1 2 3 4) (1))
</code>```

</s>

Title: Bytes/Character

Body:
Emacs Lisp, <s>55</s> 49 bytes

(lambda(s)(mapcar'string-bytes(mapcar'string s)))

First dissects the string into a list of characters with (mapcar 'string s). The string function in Emacs Lisp takes a list of characters and builds a string out of them. Due to the way Emacs splits strings with mapcar (i.e. into a list of integers, not characters or strings), this explicit conversion is needed. Then maps the string-bytes function onto that list of strings.

Example:

(mapcar 'string "abc") ; => ("a" "b" "c")
(mapcar 'string-bytes '("a" "b" "c")) ; => (1 1 1)

Testcases:

(mapcar
 (lambda(s)(mapcar'string-bytes(mapcar'string s)))
 '("!""Ciao""tʃaʊ""Adám""ĉaŭ""ĉaŭ""チャオ""""!±≡""\0"))
;; ((1) (1 1 1 1) (1 2 1 2) (1 1 2 1) (2 1 2) (1 2 1 1 2) (3 3 3) nil (1 2 3 4) (1))

<s>Old answer:

(lambda(s)(mapcar(lambda(s)(string-bytes(string s)))s))

Ungolfed:

 (lambda (s)
   (mapcar
    ;; we can't use string-bytes directly,
    ;; since Emacs mapcar yields a list of ints instead of characters
    ;; therefore we need a wrapper function here.
    (lambda (s)
      (string-bytes (string s)))
    s))

Testcases:

(mapcar
 (lambda(s)(mapcar(lambda(s)(string-bytes(string s)))s))
 '("!""Ciao""tʃaʊ""Adám""ĉaŭ""ĉaŭ""チャオ""""!±≡""\0"))
;; ((1) (1 1 1 1) (1 2 1 2) (1 1 2 1) (2 1 2) (1 2 1 1 2) (3 3 3) nil (1 2 3 4) (1))

</s>


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

答:
Python - 154 chars

```<code>import random as R;L="Andy Barb Carl Didi Earl Fran".split();M=L[:]
while any(map(str.__eq__,L,M)):R.shuffle(M)
for i in zip(L,M):print"%s buys for %s"%i
</code>```

ContentLicense: CC BY-SA 2.5

Title: Holiday Gift Exchange

Body:
Python - 154 chars

import random as R;L="Andy Barb Carl Didi Earl Fran".split();M=L[:]
while any(map(str.__eq__,L,M)):R.shuffle(M)
for i in zip(L,M):print"%s buys for %s"%i


问:
Write a polyglot that prints the language's name
Your task is to write a program that executes in as many languages as possible, with as few characters as you can. To avoid trivial solutions, the program must print the name of the language it was run in.

Scoring

Your program has to work in at least 5 languages. A program's score is given as:

$$\frac {\text{(number of languages)}^{1.5}} {\text{(length of program)}}$$

The highest score wins.

答:
This is a cheap selection of languages, but here goes:

CoffeeScript, JScript, Mozilla Javascript (≈ JavaScript 1.3), ECMAScript Edition 5, ECMAScript Edition 3, 223 chars, score ≈ 0.0501)

```<code>a="undefined"
x="ECMAScript 3"
if(Array.prototype.map)
 x="ECMAScript 5"
if(typeof CoffeeScript!=a)
 x="CoffeeScript"
if(typeof uneval!=a)
 x="Mozilla JavaScript"
if(typeof WScript!=a)
 WScript.echo("JScript")
else alert(x)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
This is a cheap selection of languages, but here goes:

CoffeeScript, JScript, Mozilla Javascript (≈ JavaScript 1.3), ECMAScript Edition 5, ECMAScript Edition 3, 223 chars, score ≈ 0.0501)

a="undefined"
x="ECMAScript 3"
if(Array.prototype.map)
 x="ECMAScript 5"
if(typeof CoffeeScript!=a)
 x="CoffeeScript"
if(typeof uneval!=a)
 x="Mozilla JavaScript"
if(typeof WScript!=a)
 WScript.echo("JScript")
else alert(x)


问:
Remove more than n consecutive vowels from input string
I don't like strings with more than three vowels in a row. Can you write a program that removes all the vowels I don't want from words?

You may write a program or function, taking input via STDIN (or closest alternative), command-line argument or function argument and outputting the result via STDOUT (or closest alternative), function return value or function (out) parameter.

Input is a string containing only printable ASCII character (0x20 to 0x7E, inclusive).

Output is a string containing only runs of at most 3 consecutive vowels. If there is a run of more than 3 consecutive vowels in the input string, your program should produce an output string including the first three vowels encountered in that run, discarding any further consecutive vowels.

Y is not a vowel for the purposes of this challenge.

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

Test Cases

```<code>"Aeiou" => "Aei"
"screeeen" => "screeen"
"We're queueing up for the Hawaiian movie." => "We're queung up for the Hawaiin movie."
"Spaces break runs: aei iou." => "Spaces break runs: aei iou."
</code>```

答:
APL, 40 chars

```<code>{⍵/⍨1↓4≠⊃+/(1-⍳4)⌽¨⊂'aeiouAEIOU'∊⍨' ',⍵}
</code>```

In English:

'aeiouAEIOU'∊⍨' ',⍵: find the vowels (and prepend a space to break on rotation);

(1-⍳4)⌽¨⊂: rotate 0, 1, 2, 3 times (with wrap-around) pushing to the right the boolean vector;

⊃+/ sum: the rotations and unbox

1↓4≠: find the different than 4, and remove the first one (to cather for the space we prepended)

⍵/⍨: in the argument, keep only the element where the sum was different than 4.

Body:
APL, 40 chars

{⍵/⍨1↓4≠⊃+/(1-⍳4)⌽¨⊂'aeiouAEIOU'∊⍨' ',⍵}

In English:

'aeiouAEIOU'∊⍨' ',⍵: find the vowels (and prepend a space to break on rotation);

(1-⍳4)⌽¨⊂: rotate 0, 1, 2, 3 times (with wrap-around) pushing to the right the boolean vector;

⊃+/ sum: the rotations and unbox

1↓4≠: find the different than 4, and remove the first one (to cather for the space we prepended)

⍵/⍨: in the argument, keep only the element where the sum was different than 4.


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

答:
Ruby, 40 38 bytes

```<code>gets.chop.each_byte{|o|puts"+"*o+".>"}
</code>```

Body:
Ruby, 40 38 bytes

gets.chop.each_byte{|o|puts"+"*o+".>"}


问:
Evaluate a Stratego Battle
In the game Stratego, the main game mechanic is when you attack an opponent's piece with yours. In this challenge, you job is to simulate one of these battles and say who survives.

Specs

You will get as input a pair of string representing Stratego pieces. The pieces are one of "S 1 2 3 4 5 6 7 8 9 10 B" (S is the Spy, and B are bombs). The first of the pair will be the attacker, and the second the attacked.

Here are the rules for determining the results of a battle:

The higher number beats the lower number: ["4", "6"] -> ["6"].

If both are the same, then both die: ["7", "7"] -> [].

Spies are at the bottom, underneath even 1: ["S", "2"] -> ["2"].

However, if a spy attacks the 10, then the spy wins: ["S", "10"] -> ["S"].

But the normal rules still apply if the 10 is the one attacking: ["10", "S"] -> ["10"].

If anything attacks a bomb, the bomb wins: ["5", "B"] -> ["B"].

However, a miner (a 3), can defuse a bomb: ["3", "B"] -> ["3"].

A bomb will never be the attacker.

A spotter (a 1), can attack using the normal mechanism, but they can also try to "guess" the rank of the other player, which can be denoted with any sane notation.

If they guess correctly, the other piece dies: ["1(5)", "5"] -> ["1"].

If they guess wrong, nothing happens: ["1(3)", "5"] -> ["1", "5"].

Spotters can spot bombs: ["1(B)", "B"] -> ["1"].

This is code-golf, so shortest code in bytes wins!

(You can use the examples up there as test-cases, because I'm too lazy to put them all together in one list).

Title: Evaluate a Stratego Battle

Body:
Javascript ES6, <s>98</s> 86 bytes

(a,b,g)=>a==1?b==g?a:[a,b]:b=="B"?a==3?a:b:a=="S"?b==10?a:b:b=="S"?a:a==b?[]:+a>+b?a:b

Accepts 3 args (attacker, defender, spotter guess).

Example runs:

f("4","6")     -> "6"
f("7","7")     -> []
f("S","2")     -> "2"
f("S","10")    -> "S"
f("10","S")    -> "10"
f("5","B")     -> "B"
f("3","B")     -> "3"
f("1","5","5") -> "1"
f("1","5","3") -> ["1","5"]
f("1","B","B") -> "1"


问:
Rotate simple ASCII art
This is similar to a previous question on this site, but with much simpler rules, so we should get much shorter results (in bytes):

Input:  ASCII art with only two possible characters: space and '#'.

Output: Input sequence rotated 90 degrees counter-clockwise.

Winner is answer with least number of bytes including length of language name.

答:
Bash <s>(144 + 4)</s> (131 + 4)

Assumes input is in a file with newlines to delimit end of row.

Assumes each row has the same number of characters.

Assumes first argument is path to file.

```<code>t=`sed 's/\(.\)/\1\t/g' $1` n=$(expr $(head -n1 $1|wc -c) \- 1);for i in $(seq 1 $n);do echo "$t"|cut -f$i|tac|tr -d '\n';echo;done
</code>```

Un-golfed:

```<code>t=$(sed 's/\(.\)/\1\t/g' $1) # Add a tab after every character.
n=$(expr $(head -n 1 $1 | wc -c) \- 1) # Count the number of characters in a row.
for i in $(seq 1 $n); do # For each row.
    echo "$t"|cut -f "$i" |tac|tr -d '\n' # Cut the i^th column, print, reverse and delete newline.
    echo # Finished processing i^th row. Emit newline.
done
</code>```

Title: Rotate simple ASCII art

Body:
Bash <s>(144 + 4)</s> (131 + 4)

Assumes input is in a file with newlines to delimit end of row.

Assumes each row has the same number of characters.

Assumes first argument is path to file.

t=`sed 's/\(.\)/\1\t/g' $1` n=$(expr $(head -n1 $1|wc -c) \- 1);for i in $(seq 1 $n);do echo "$t"|cut -f$i|tac|tr -d '\n';echo;done

Un-golfed:

t=$(sed 's/\(.\)/\1\t/g' $1) # Add a tab after every character.
n=$(expr $(head -n 1 $1 | wc -c) \- 1) # Count the number of characters in a row.
for i in $(seq 1 $n); do # For each row.
    echo "$t"|cut -f "$i" |tac|tr -d '\n' # Cut the i^th column, print, reverse and delete newline.
    echo # Finished processing i^th row. Emit newline.
done


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

答:
PowerShell v2+, <s>172</s> <s>153</s> <s>148</s> <s>145</s> <s>142</s> <s>131</s> 123 bytes (81 chars)

```<code>($a=""+0..7)
$b='┌┘'
"│$b$('┌┼─┘'*3)
└┼┐$('│└─┐'*3)
$b$('└┼─┐'*3)│
│ $($b*6)│"
$a
</code>```

I golfed the weaving further, eliminating the need for several variables by using inline code blocks. This is probably within a few bytes of optimal.

We start by setting $a equal to the range 0..7 that's been joined together with spaces. This is because the default $ofs (Output Field Separator) for an array is a space, so when the array is stringified with ""+ (with an operator like this, PowerShell will try to implicitly cast the right-hand object as the left-hand object), the result is the range space-separated.

That's encapsulated in parens, which adds the result onto the pipeline. We then setup a one helper variable $b, followed by four lines of output with the appropriate variable in place (split with literal newlines), and using inline code-blocks for repeat sections, followed by $a again. The four lines and $a are also placed on the pipeline, and output is implicit at the end.

```<code>PS C:\Tools\Scripts\golfing> .\visualize-bit-weaving.ps1
0 1 2 3 4 5 6 7
│┌┘┌┼─┘┌┼─┘┌┼─┘
└┼┐│└─┐│└─┐│└─┐
┌┘└┼─┐└┼─┐└┼─┐│
│ ┌┘┌┘┌┘┌┘┌┘┌┘│
0 1 2 3 4 5 6 7
</code>```

Title: Visualise Bit Weaving

Body:
PowerShell v2+, <s>172</s> <s>153</s> <s>148</s> <s>145</s> <s>142</s> <s>131</s> 123 bytes (81 chars)

($a=""+0..7)
$b='┌┘'
"│$b$('┌┼─┘'*3)
└┼┐$('│└─┐'*3)
$b$('└┼─┐'*3)│
│ $($b*6)│"
$a

I golfed the weaving further, eliminating the need for several variables by using inline code blocks. This is probably within a few bytes of optimal.

We start by setting $a equal to the range 0..7 that's been joined together with spaces. This is because the default $ofs (Output Field Separator) for an array is a space, so when the array is stringified with ""+ (with an operator like this, PowerShell will try to implicitly cast the right-hand object as the left-hand object), the result is the range space-separated.

That's encapsulated in parens, which adds the result onto the pipeline. We then setup a one helper variable $b, followed by four lines of output with the appropriate variable in place (split with literal newlines), and using inline code-blocks for repeat sections, followed by $a again. The four lines and $a are also placed on the pipeline, and output is implicit at the end.

PS C:\Tools\Scripts\golfing> .\visualize-bit-weaving.ps1
0 1 2 3 4 5 6 7
│┌┘┌┼─┘┌┼─┘┌┼─┘
└┼┐│└─┐│└─┐│└─┐
┌┘└┼─┐└┼─┐└┼─┐│
│ ┌┘┌┘┌┘┌┘┌┘┌┘│
0 1 2 3 4 5 6 7


答:
Python3, 209 bytes

```<code>lambda s="0 1 2 3 4 5 6 7\n":s+"│┌┘ │┌┘ │┌┘ │ │\n└┼─┐└┼─┐└┼─┐└┐│\n┌┘┌┼─┘ └┐│┌┼─┼┘\n│ │└┐ ┌─┼┘│└┐└┐\n"+s
</code>```

Returns a string.

Thanks to @Mego for saving 2 bytes!

Credits of the character body go to @TimmyD !

Title: Visualise Bit Weaving

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

Body:
Python3, 209 bytes

lambda s="0 1 2 3 4 5 6 7\n":s+"│┌┘ │┌┘ │┌┘ │ │\n└┼─┐└┼─┐└┼─┐└┐│\n┌┘┌┼─┘ └┐│┌┼─┼┘\n│ │└┐ ┌─┼┘│└┐└┐\n"+s

Returns a string.

Thanks to @Mego for saving 2 bytes!

Credits of the character body go to @TimmyD !


答:
Pyth - <s>119</s> <s>104</s> <s>100</s> 81 bytes

Extremely simple. (Its actually bytes this time).

```<code>js[KjdU8cX."sz¨ú¨ãÆhÆ?\ÕüÓ¼xFNøa"_G"│┌┘└┼─┐ "15K
</code>```

Try it online here.

I also stole @TimmyD's output:

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

Title: Visualise Bit Weaving

Body:
Pyth - <s>119</s> <s>104</s> <s>100</s> 81 bytes

Extremely simple. (Its actually bytes this time).

js[KjdU8cX."sz¨ú¨ãÆhÆ?\ÕüÓ¼xFNøa"_G"│┌┘└┼─┐ "15K

Try it online here.

I also stole @TimmyD's output:

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


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:
Ruby, 26 bytes

gsub(/./){?+*$&.ord+'.>'}

+ 1 byte for the p command line option. To e.g get the brainfuck code for ABC xyz you can run

$ ruby -p -e 'gsub(/./){?+*$&.ord+".>"}' <<< "ABC xyz"

and get

+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.>++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.>+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.>++++++++++++++++++++++++++++++++.>++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.>+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.>++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.>


答:
Javascript ES6, <s>168</s> 167 bytes

Edit: Whoops, turned out I was using the pipe | char instead of U+2502 │ in part of the function, updated byte count.

```<code>_=>((n=`0 1 2 3 4 5 6 7 `)+[...`6452301`].map(i=>`${(d=n=>`│ `.repeat(n))(i)}└┐│ ${r=d(6)}┌┼┘ ${r}│└┐ ${d(6-i)}`).join``+n).match(/.{16}/g).join`
`
</code>```

Returns a string.

Output:

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

Extra: Using @TimmyD's method, I have another 167 byte solution:

```<code>(n=`0 1 2 3 4 5 6 7
`,a=`│┌┘ `,b=`└┼─┐`,d=`┌┼─┘`,f=` │└┐`)=>[n,a,a,a,a,`
`,b,b,b,`└┼┐
┌┘`,d,d,d,`│
│`,f,f,f,` │
`,n].join``
</code>```

Title: Visualise Bit Weaving

Body:
Javascript ES6, <s>168</s> 167 bytes

Edit: Whoops, turned out I was using the pipe | char instead of U+2502 │ in part of the function, updated byte count.

_=>((n=`0 1 2 3 4 5 6 7 `)+[...`6452301`].map(i=>`${(d=n=>`│ `.repeat(n))(i)}└┐│ ${r=d(6)}┌┼┘ ${r}│└┐ ${d(6-i)}`).join``+n).match(/.{16}/g).join`
`

Returns a string.

Output:

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

Extra: Using @TimmyD's method, I have another 167 byte solution:

(n=`0 1 2 3 4 5 6 7
`,a=`│┌┘ `,b=`└┼─┐`,d=`┌┼─┘`,f=` │└┐`)=>[n,a,a,a,a,`
`,b,b,b,`└┼┐
┌┘`,d,d,d,`│
│`,f,f,f,` │
`,n].join``


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

```

答:
Mathematica, 59 bytes

```<code>n_ ±1:=3^n
1 ±m_:=3
n_ ±m_:=((n-1)±m)±(m-1)
Nest[3±#&,4,64]
</code>```

Uses an undefined infix operator ± which requires only 1 byte when encoded in ISO 8859-1. See @Martin's post for more info. Mathematica functions support pattern matching for their arguments, such that the two base cases can be defined separately.

Title: Theoretically output Graham's number

Body:
Mathematica, 59 bytes

n_ ±1:=3^n
1 ±m_:=3
n_ ±m_:=((n-1)±m)±(m-1)
Nest[3±#&,4,64]

Uses an undefined infix operator ± which requires only 1 byte when encoded in ISO 8859-1. See @Martin's post for more info. Mathematica functions support pattern matching for their arguments, such that the two base cases can be defined separately.


Body:
Brainfuck, <s>3513</s> 43 bytes

++[>+<------],[[>.>+<<-]>+++.->[<.>-]<--<,]

This answer makes no assumptions about the interpreter of the output program. Try it online!

For a shorter solution (which works only with some interpreters), see my other answer.

Test run

For input Code Golf, the following output is generated.

+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.-------------------------------------------------------------------+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.---------------------------------------------------------------------------------------------------------------++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.----------------------------------------------------------------------------------------------------+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.-----------------------------------------------------------------------------------------------------++++++++++++++++++++++++++++++++.--------------------------------+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.-----------------------------------------------------------------------+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.---------------------------------------------------------------------------------------------------------------++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.------------------------------------------------------------------------------------------------------------++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.------------------------------------------------------------------------------------------------------+++++++++++++++++++++++++++++++++.---------------------------------

<a href="http://brainfuck.tryitonline.net/#code=KysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKy4tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrLi0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLSsrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysuLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLSsrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrLi0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysuLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0rKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKy4tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLSsrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKy4tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0rKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysuLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrLi0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLSsrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKy4tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0&input=" rel="nofollow noreferrer">Try it online!

How it works

We begin by putting the integer 43 (character code of +) in the second cell of the tape. The following code achieves this.

++         Increment the first cell twice, setting it to 2.
[          While the first cell in non-zero:
  >+         Increment the second cell.
  <------    Decrement the first cell six times.
]

This essentially performs the modular division 2 ÷ 6 (mod 256). Since (2 + 256) ÷ 6 = 258 ÷ 6 = 43, the result is 43, as intended.

Now we're ready to generate output.

,      Read a character from STDIN and put it the first cell.
[        While the first cell is non-zero:
  [        While the first cell is non-zero:
    >.     Print the content of the second cell ('+').
    >+     Increment the third cell.
    <<-    Decrement the first cell.
  ]      If the first cell held n, the above prints n plus signs
         and puts n in the third cell.
  >+++   Add three to the second cell, setting it to 46 ('.').
  .      Print its content ('.').
  -      Decrement, setting it to 45 ('-').
  >      Advance to the third cell.
  [      While the third cell is non-zero:
    <.     Print the content of the second cell ('-').
    >-     Decrement the third cell.
  ]      If the first cell held n, the above prints n minus signs,
         thus negating the plus signs and zeroing the cell of the output program.
  <--    Subtract 2 from the second cell, setting it back to 43.
  <,     Go back to the first cell and read another character from STDIN.
]      Once EOF is reached, ',' will put 0 in the first cell, ending the loop.


Body:
J, 28 bytes

[:;[:('.>',~'+'#~])"0[:]3&u:

Simple enough. 3&u: converts chars to char codes. The rest is just repeat '+' that number of times, then concatenating with .> at the end of each line, and ; flattens the result.

Some results

   bf =: [:;[:('>.',~'+'#~])"0[:]3&u:
   bf 'hi'
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++>. +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++>.
   bf ' !'
++++++++++++++++++++++++++++++++>. +++++++++++++++++++++++++++++++++>.
   bf ' ~'
++++++++++++++++++++++++++++++++>.
                 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++>.


答:
Pyke, 11 bytes

```<code>F.o\+*".>"+
</code>```

Try it here!

Body:
Pyke, 11 bytes

F.o\+*".>"+

Try it here!


答:
Swift 2.2, <s>67</s> <s>52</s> 50 bytes

```<code>for c in i.characters{print(String(c).utf8.count)}
</code>```

Horribly ugly.  There's no way to get the UTF-8 length of a Character in Swift, so I need to iterate through the string by character, convert the Character to a String, and find the count of that single-character String (hey, at least there's a built-in method to do that).  Looking for optimizations, possibly using a scanner.

Revision 1: Saved 15 bytes by using count instead of underestimateCount().

Revisions 2: Saved another 2 character by using a for-in loop instead of a for each closure.

Title: Bytes/Character

Body:
Task

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

Examples

! → 1

Ciao → 1 1 1 1

tʃaʊ → 1 2 1 2

Adám → 1 1 2 1

ĉaŭ → 2 1 2 (single characters)

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

チャオ → 3 3 3

 (empty input) →  (empty output)

!±≡ → 1 2 3 4

� (a null byte) → 1

Null bytes

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

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

Body:
Swift 2.2, <s>67</s> <s>52</s> 50 bytes

for c in i.characters{print(String(c).utf8.count)}

Horribly ugly.  There's no way to get the UTF-8 length of a Character in Swift, so I need to iterate through the string by character, convert the Character to a String, and find the count of that single-character String (hey, at least there's a built-in method to do that).  Looking for optimizations, possibly using a scanner.

Revision 1: Saved 15 bytes by using count instead of underestimateCount().

Revisions 2: Saved another 2 character by using a for-in loop instead of a for each closure.


答:
Actually, 13 bytes

```<code>O`'+*".>"@`MΣ
</code>```

Try it online!

The strategy used here is the same as in many of the other solutions - for each character, output enough +s to increment a zero-initialized cell to the proper ASCII ordinal, output it with ., and move to the next cell with >.

Explanation:

```<code>O`'+*".>"@`MΣ
O              list of ordinals (technically this is Unicode code points, but code points 0-127 are the same for Unicode and ASCII)
 `'+*".>"@`M   for each ordinal:
  '+*            push a string containing that many +s
     ".>"@       push ".>" and swap (putting it before the +s)
            Σ  concatenate all the strings (if "[", "]", and "," weren't meaningful characters in BF, this technically wouldn't be necessary)
</code>```

Body:
Actually, 13 bytes

O`'+*".>"@`MΣ

Try it online!

The strategy used here is the same as in many of the other solutions - for each character, output enough +s to increment a zero-initialized cell to the proper ASCII ordinal, output it with ., and move to the next cell with >.

Explanation:

O`'+*".>"@`MΣ
O              list of ordinals (technically this is Unicode code points, but code points 0-127 are the same for Unicode and ASCII)
 `'+*".>"@`M   for each ordinal:
  '+*            push a string containing that many +s
     ".>"@       push ".>" and swap (putting it before the +s)
            Σ  concatenate all the strings (if "[", "]", and "," weren't meaningful characters in BF, this technically wouldn't be necessary)


答:
C, <s>72</s> <s>64</s> 60 bytes

main(c){for(;c=~getchar();)for(;printf(~c++?"+":".>")^2;);}
```
<p>Ungolfed version:</p>
<pre class="lang-c prettyprint-override"><code>main( c )
{
    for ( ; c = ~getchar( ); )
        for ( ; printf( ~c++ ? "+" : ".>" ) ^ 2; );
}
</code>```

Compile and test with:

gcc -o bfcat bfcatgolf.c && cat 1.txt | ./bfcat > o.txt && beef o.txt

Results

hi - http://paste.ubuntu.com/17995958/

quick brown fox jumps over the lazy dog - http://paste.ubuntu.com/17996059/

source code - http://paste.ubuntu.com/18000808/

Body:
C, <s>72</s> <s>64</s> 60 bytes

main(c){for(;c=~getchar();)for(;printf(~c++?"+":".>")^2;);}

Ungolfed version:

main( c )
{
    for ( ; c = ~getchar( ); )
        for ( ; printf( ~c++ ? "+" : ".>" ) ^ 2; );
}

Compile and test with:

gcc -o bfcat bfcatgolf.c && cat 1.txt | ./bfcat > o.txt && beef o.txt

Results

hi - http://paste.ubuntu.com/17995958/

quick brown fox jumps over the lazy dog - http://paste.ubuntu.com/17996059/

source code - http://paste.ubuntu.com/18000808/


答:
JavaScript (ES6), 83

f=(s,o=[],a='')=>/./.test(s)?f(s.replace(/^./gm,x=>(a=x+a)&&''),[...o,a]):o.join`\n`

G.onclick=g=>X.innerHTML=f(X.innerHTML)```
<pre class="snippet-code-css lang-css prettyprint-override"><code>textarea{
  height:100px;
  line-height:7px;
}</code>```

<button id=G>Rotate</button>
<textarea id=X>
#
# #
#   #
#     #
#       #
#         #
#       #
#     #
#   #
# #
#
</textarea>```

Title: Rotate simple ASCII art

Body:
This is similar to a previous question on this site, but with much simpler rules, so we should get much shorter results (in bytes):

Input:  ASCII art with only two possible characters: space and '#'.

Output: Input sequence rotated 90 degrees counter-clockwise.

Winner is answer with least number of bytes including length of language name.

Body:
JavaScript (ES6), 83

f=(s,o=[],a='')=>/./.test(s)?f(s.replace(/^./gm,x=>(a=x+a)&&''),[...o,a]):o.join`\n`

G.onclick=g=>X.innerHTML=f(X.innerHTML)

textarea{
  height:100px;
  line-height:7px;
}

<button id=G>Rotate</button>
<textarea id=X>
#
# #
#   #
#     #
#       #
#         #
#       #
#     #
#   #
# #
#
</textarea>


答:
Caramel, 38 bytes

```<code>(64 ((f->(f,1)),(n f->(3 (n f))),3) 4)
</code>```

This is syntactic sugar for the lambda calculus expression 64 (λm. m (λf. λn. n f 1) (λn. λf. 3 (n f)) 3) 4, where all numbers are represented as Church numerals.

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:
Caramel, 38 bytes

(64 ((f->(f,1)),(n f->(3 (n f))),3) 4)

This is syntactic sugar for the lambda calculus expression 64 (λm. m (λf. λn. n f 1) (λn. λf. 3 (n f)) 3) 4, where all numbers are represented as Church numerals.


问:
Given a number, program must return the alphabet letter correspondent

The program

Given a number, program must return the alphabet letter correspondent.

Rules

The challenge here is to make it as short as possible, everyone knows it is a very easy program to do.

The number is not zero-based, it means 1 is A, 2 is B, 3 is C and so it goes...

Any language will be accepted.

答:
Perl, 20 characters

```<code>chr(($ARGV[0] + 64))
</code>```

Verification :

```<code>risk@skynet:~/perl$ for x in {1..26}; do perl ./ord.pl $x; done;
ABCDEFGHIJKLMNOPQRSTUVWXYZrisk@skynet:~/perl$
</code>```

Body:
Perl, 20 characters

chr(($ARGV[0] + 64))

Verification :

risk@skynet:~/perl$ for x in {1..26}; do perl ./ord.pl $x; done;
ABCDEFGHIJKLMNOPQRSTUVWXYZrisk@skynet:~/perl$