问:
KOTH: TNT Run Challenge
This was inspired by a Minecraft mini-game. The rules are pretty simple: you run and jump around, and every block you step on disappears once you've stepped on it. The goal is to be the last one left.

Your bot should be a complete program. It should accept input as a command line argument. The input will be a map of the "world"; here is an example:

```<code>xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxx xxxxxxxxxxxxxxxxxxxxxxxxxxx
xxx xxxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxx x xxxxxxxxxxxxx@xxxxxxxxxxx
xxxxxx1xxxxxxxxxxxxx xxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxx xxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxx xxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxx xxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxx xxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxx xxxxxxxxxxx
xxxxxxxxxx           xxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxx xxxxxxxxxxxx
xxxxxxxxxxxxxxxxx x x xxxxxxxxxx
xxxxxxxxxxxxxxxxxxxx xxxxxxxxxxx
xxxxxxxxxxxxxx xxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxx xxx xx3xxxxxxxxxx
xxxxxxxxxxxxxxxxxxx xxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxxxxx  x
xxxxxxxxxxxxxxxxxxxxxxxxxxx   xx
xxxxxxxxxxxxxxxxxxxxxxxxx      2
xxxxxxxxxxxxxxxxxxxxxxx
</code>```

The legend is as follows:

x: solid block

 : empty air

@: your bot

1,2,3,4,5,6,7,8,9,0: other bots

Your bot should output your move as a pair of integers. Example: -1, 2 will move 1 block to the left and 2 blocks down (coordinates origin is in the top left corner).

You may move up to four blocks, manhattan distance, from your current location. If you try to move further than that, the move is invalid. Any move that would move you past the edge will put you on the edge instead. Invalid moves will be ignored.

Once you land on a block it is removed; if you remain on the same block next turn you will fall. Two bots may land on the same block on the same turn and both survive; if this happens, both bots will only see themselves and not the other bot.

If you need to store files for persistence, please do so in a folder with the name of your bot. You may not read other bots' persistent data if any exists.

The match controller is available at https://paste.ee/p/Xf65d.

Please use languages that can be run on a standard Linux or OSX install.

Current results (100 rounds):

```<code>JumpBot                   31
LookBot                   27
ShyBot                    26
Slow Bot                  15
KnightBot                 2
Moat Builder              0
UpBot                     0
Random Bot                0
</code>```

答:
Monte (Python)

Sorry, that pun just had to be made.

Anyway, this bot works by doing a Monte Carlo Tree Search on all of the possible move sets. Think of JumpBot, only more in-depth.

To run, it needs an extra command line argument (can be specified in the controller). It controls how much time the bot should search for (in ms); I used 750-1500 in testing.

Code:

```<code>import sys
import math
import copy
#from profilestats import profile
pmap = sys.argv[2].split("\n")
pmap = [list(r) for r in pmap]

#find a player
#@profile
def find(tmap,bot):
   r,c=-1,-1
   for row in range(len(tmap)):
      for col in range(len(tmap[row])):
         if tmap[row][col]==bot:
            r,c=row,col
   return r,c

mer,mec=find(pmap,'@')
bots=[(mer,mec)]

#find all the other players
for b in range(10):
   r,c=find(pmap,str(b))
   if r != -1:
      bots.append((r,c))

#getter function, treats oob as spaces
def get(tmap,r,c):
   if r<0 or r>=len(tmap) or c<0 or c>=len(tmap[r]):
      return ' '
   return tmap[r][c]

#returns manhattan distance between 2 positions
def dist(r1,c1,r2,c2):
   return abs(r1-r2)+abs(c1-c2)

#gets all possible moves from a map
#@profile
def moves(tmap,ther=-1,thec=-1):
   if ther==-1: ther,thec = find(tmap,'@')
   pos=[]
   for r in range(-4,5):
      for c in range(-4,5):
         if abs(r)+abs(c)<=4 and get(tmap,ther+r,thec+c)=='x':
            pos.append((r,c))
   return pos

ttlmoves = 40
#monte-carlo tree node
class MCNode:
   def __init__(self):
      self.wins=0
      self.simu=0
      self.chld=[]
      self.cmap=[[]]
      self.prnt=None
      self.r=-1
      self.c=-1
   def add(self, cnode):
      self.chld.append(cnode)
      cnode.prnt = self
   #used to balance exploitation and exploration
   #@profile
   def param(self,cin):
      return self.chld[cin].wins/self.chld[cin].simu\
             + 1.414 * math.sqrt( math.log(self.simu) / \
             self.chld[cin].simu )
   #finds the child with the highest param
   #@profile
   def best(self):
      vals = [self.param(x) for x in range(len(self.chld))]
      binx = 0
      bval = vals[0]
      for x in range(len(vals)):
         if vals[x]>bval:
            binx=x
            bval=vals[x]
      return self.chld[binx]

#update all the parents
#@profile
def backprog(leaf):
   par = leaf.prnt
   if not (par is None):
      par.wins+=leaf.wins
      par.simu+=leaf.simu
      backprog(par)

#expand all the moves from a position
#@profile
def expand(rootn):
   ther,thec = rootn.r,rootn.c
   for r,c in moves(rootn.cmap,rootn.r,rootn.c):
      nmap = copy.deepcopy(rootn.cmap)
      nmap[ther+r][thec+c] = '@'
      nmap[ther][thec]=' '
      nnode = MCNode()
      nm = moves(nmap,ther+r,ther+c)
      nnode.wins = len(nm)
      nnode.simu = ttlmoves
      nnode.r=ther+r
      nnode.c=thec+c
      nnode.cmap = nmap
      rootn.add(nnode)
      backprog(nnode)

root = MCNode()
m = moves(pmap,mer,mec)
root.wins = len(m)
root.simu = ttlmoves
root.cmap=copy.deepcopy(pmap)
root.r=mer
root.c=mec
expand(root)

#simulate a bunch of outcomes
import time
curt  = lambda: int(round(time.time() * 1000))
strt = curt()
ttme = int(sys.argv[1])
while curt()-strt < ttme:
   tnode=root
   while tnode.chld:
      tnode=tnode.best()
   expand(tnode)

#choose the most explored one
bnode = max(root.chld,key=lambda n:n.simu)

#output
print("{} {}".format((bnode.c-mec),(bnode.r-mer)))
</code>```

Trials

25 rounds:

```<code>MonteBot            14
JumpBot             6
ShyBot              5
LookBot             1
KnightBot           0
SlowBot             0
</code>```

100 rounds:

```<code>JumpBot             38
MonteBot            36
ShyBot              15
LookBot             14
SlowBot             2
KnightBot           0
</code>```

200 rounds:

```<code>MonteBot            87
JumpBot             64
LookBot             33
ShyBot              21
SlowBot             5
KnightBot           0
</code>```

All of the simulations above used search time 750. This bot would probably be even better with a longer search time (I don't know what the max allowed is).

Improvements

This bot still needs improvements in:

Performance: it needs the entire time to search.

Prediction: it won't account for other bot's moves.

Balance: I'm not sure if the UCT formula I am using to calculate which node I should explore is optimal.

Title: KOTH: TNT Run Challenge

Body:
Monte (Python)

Sorry, that pun just had to be made.

Anyway, this bot works by doing a Monte Carlo Tree Search on all of the possible move sets. Think of JumpBot, only more in-depth.

To run, it needs an extra command line argument (can be specified in the controller). It controls how much time the bot should search for (in ms); I used 750-1500 in testing.

Code:

import sys
import math
import copy
#from profilestats import profile
pmap = sys.argv[2].split("\n")
pmap = [list(r) for r in pmap]

#find a player
#@profile
def find(tmap,bot):
   r,c=-1,-1
   for row in range(len(tmap)):
      for col in range(len(tmap[row])):
         if tmap[row][col]==bot:
            r,c=row,col
   return r,c

mer,mec=find(pmap,'@')
bots=[(mer,mec)]

#find all the other players
for b in range(10):
   r,c=find(pmap,str(b))
   if r != -1:
      bots.append((r,c))

#getter function, treats oob as spaces
def get(tmap,r,c):
   if r<0 or r>=len(tmap) or c<0 or c>=len(tmap[r]):
      return ' '
   return tmap[r][c]

#returns manhattan distance between 2 positions
def dist(r1,c1,r2,c2):
   return abs(r1-r2)+abs(c1-c2)

#gets all possible moves from a map
#@profile
def moves(tmap,ther=-1,thec=-1):
   if ther==-1: ther,thec = find(tmap,'@')
   pos=[]
   for r in range(-4,5):
      for c in range(-4,5):
         if abs(r)+abs(c)<=4 and get(tmap,ther+r,thec+c)=='x':
            pos.append((r,c))
   return pos

ttlmoves = 40
#monte-carlo tree node
class MCNode:
   def __init__(self):
      self.wins=0
      self.simu=0
      self.chld=[]
      self.cmap=[[]]
      self.prnt=None
      self.r=-1
      self.c=-1
   def add(self, cnode):
      self.chld.append(cnode)
      cnode.prnt = self
   #used to balance exploitation and exploration
   #@profile
   def param(self,cin):
      return self.chld[cin].wins/self.chld[cin].simu\
             + 1.414 * math.sqrt( math.log(self.simu) / \
             self.chld[cin].simu )
   #finds the child with the highest param
   #@profile
   def best(self):
      vals = [self.param(x) for x in range(len(self.chld))]
      binx = 0
      bval = vals[0]
      for x in range(len(vals)):
         if vals[x]>bval:
            binx=x
            bval=vals[x]
      return self.chld[binx]

#update all the parents
#@profile
def backprog(leaf):
   par = leaf.prnt
   if not (par is None):
      par.wins+=leaf.wins
      par.simu+=leaf.simu
      backprog(par)

#expand all the moves from a position
#@profile
def expand(rootn):
   ther,thec = rootn.r,rootn.c
   for r,c in moves(rootn.cmap,rootn.r,rootn.c):
      nmap = copy.deepcopy(rootn.cmap)
      nmap[ther+r][thec+c] = '@'
      nmap[ther][thec]=' '
      nnode = MCNode()
      nm = moves(nmap,ther+r,ther+c)
      nnode.wins = len(nm)
      nnode.simu = ttlmoves
      nnode.r=ther+r
      nnode.c=thec+c
      nnode.cmap = nmap
      rootn.add(nnode)
      backprog(nnode)

root = MCNode()
m = moves(pmap,mer,mec)
root.wins = len(m)
root.simu = ttlmoves
root.cmap=copy.deepcopy(pmap)
root.r=mer
root.c=mec
expand(root)

#simulate a bunch of outcomes
import time
curt  = lambda: int(round(time.time() * 1000))
strt = curt()
ttme = int(sys.argv[1])
while curt()-strt < ttme:
   tnode=root
   while tnode.chld:
      tnode=tnode.best()
   expand(tnode)

#choose the most explored one
bnode = max(root.chld,key=lambda n:n.simu)

#output
print("{} {}".format((bnode.c-mec),(bnode.r-mer)))

Trials

25 rounds:

MonteBot            14
JumpBot             6
ShyBot              5
LookBot             1
KnightBot           0
SlowBot             0

100 rounds:

JumpBot             38
MonteBot            36
ShyBot              15
LookBot             14
SlowBot             2
KnightBot           0

200 rounds:

MonteBot            87
JumpBot             64
LookBot             33
ShyBot              21
SlowBot             5
KnightBot           0

All of the simulations above used search time 750. This bot would probably be even better with a longer search time (I don't know what the max allowed is).

Improvements

This bot still needs improvements in:

Performance: it needs the entire time to search.

Prediction: it won't account for other bot's moves.

Balance: I'm not sure if the UCT formula I am using to calculate which node I should explore is optimal.


问:
Fix my Basic Orthography

Fix my Basic Orthography

While I am excellent at following the English capitalisation rules when writing, when I am typing I have a habit a capitalising almost everything (as you will see from the titles of my challenges). I need a program to fix that, but because I use so many capitals, and capitals are big letters, your program must be as short as possible.

Requirements

Your program should take each word, and if it is the first alphanumeric set of characters after a full stop or the beginning of the input, capitalize the first letter. All the rest of the letters until the next full stop will be lowercase.  At the full stop, capitalize the first letter and continue.

Punctuation must be preserved.

In a sentence without a full stop at the end, that should be added.

Spaces, where missing, should be inserted. A space is 'missing' if there is nothing between a full stop and the character following it.

(Note for americanish speakers: full stop = period = .)

Test Cases

```<code>tHIS SenteNce HAS veRy bAd GrammAr. ==> This sentence has very bad grammar.

-----

PuncTuation must-be PReserved. ==> Punctuation must-be preserved.

-----

full StOps ShoulD Be inserted ==> Full stops should be inserted.

-----

MultiPLe sEntEnceS Are possible. thEY Are, yoU KNOW. ==> Multiple sentences are possible. They are, you know.

-----

spaces. are.inserted. ==> Spaces. Are. Inserted.
</code>```

Rules

Your program should take input as an argument or from STDIN (or the closest alternative in your language).

Standard loopholes are forbidden.

Scoring

When code-golf is the tag, it's the least bytes to win!

Submissions

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

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

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

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

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

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

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

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

Leaderboard

/* Configuration */

var QUESTION_ID = 79842; // Obtain this from the url
// It will be like https://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page
var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";
var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk";
var OVERRIDE_USER = 53406; // This should be the user ID of the challenge author.

/* App */

var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page;

function answersUrl(index) {
  return "https://api.stackexchange.com/2.2/questions/" +  QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER;
}

function commentUrl(index, answers) {
  return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER;
}

function getAnswers() {
  jQuery.ajax({
    url: answersUrl(answer_page++),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      answers.push.apply(answers, data.items);
      answers_hash = [];
      answer_ids = [];
      data.items.forEach(function(a) {
        a.comments = [];
        var id = +a.share_link.match(/\d+/);
        answer_ids.push(id);
        answers_hash[id] = a;
      });
      if (!data.has_more) more_answers = false;
      comment_page = 1;
      getComments();
    }
  });
}

function getComments() {
  jQuery.ajax({
    url: commentUrl(comment_page++, answer_ids),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      data.items.forEach(function(c) {
        if (c.owner.user_id === OVERRIDE_USER)
          answers_hash[c.post_id].comments.push©;
      });
      if (data.has_more) getComments();
      else if (more_answers) getAnswers();
      else process();
    }
  });
}

getAnswers();

var SCORE_REG = /<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/;

var OVERRIDE_REG = /^Override\s*header:\s*/i;

function getAuthorName(a) {
  return a.owner.display_name;
}

function process() {
  var valid = [];

  answers.forEach(function(a) {
    var body = a.body;
    a.comments.forEach(function(c) {
      if(OVERRIDE_REG.test(c.body))
        body = '
' + c.body.replace(OVERRIDE_REG, '') + '
';
    });

    var match = body.match(SCORE_REG);
    if (match)
      valid.push({
        user: getAuthorName(a),
        size: +match[2],
        language: match[1],
        link: a.share_link,
      });

  });

  valid.sort(function (a, b) {
    var aB = a.size,
        bB = b.size;
    return aB - bB
  });

  var languages = {};
  var place = 1;
  var lastSize = null;
  var lastPlace = 1;
  valid.forEach(function (a) {
    if (a.size != lastSize)
      lastPlace = place;
    lastSize = a.size;
    ++place;

    var answer = jQuery("#answer-template").html();
    answer = answer.replace("{{PLACE}}", lastPlace + ".")
                   .replace("{{NAME}}", a.user)
                   .replace("{{LANGUAGE}}", a.language)
                   .replace("{{SIZE}}", a.size)
                   .replace("{{LINK}}", a.link);
    answer = jQuery(answer);
    jQuery("#answers").append(answer);

    var lang = a.language;
    if (/ b.lang) return 1;
    if (a.lang < b.lang) return -1;
    return 0;
  });

  for (var i = 0; i < langs.length; ++i)
  {
    var language = jQuery("#language-template").html();
    var lang = langs[i];
    language = language.replace("{{LANGUAGE}}", lang.lang)
                       .replace("{{NAME}}", lang.user)
                       .replace("{{SIZE}}", lang.size)
                       .replace("{{LINK}}", lang.link);
    language = jQuery(language);
    jQuery("#languages").append(language);
  }

}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body { text-align: left !important}

#answer-list {
  padding: 10px;
  width: 290px;
  float: left;
}

#language-list {
  padding: 10px;
  width: 290px;
  float: left;
}

table thead {
  font-weight: bold;
}

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

```

答:
Q 78 Bytes

(76 if anonymous function)

```<code>f:{(". "/:{{@[(" "=*x)_x;0;"c"$-32+"i"$]}'"."\:_-1_x}x),$["."=u:*|x;u;u,"."]}
</code>```

Test

```<code>f"tHIS SenteNce HAS veRy bAd GrammAr."                  /This sentence has very bad grammar.
f"PuncTuation must-be PReserved."                       /Punctuation must-be preserved.
f"full StOps ShoulD Be inserted"                        /Full stops should be inserted.
f"MultiPLe sEntEnceS Are possible. thEY Are, yoU KNOW." /Multiple sentences are possible. They are, you know.
f"spaces. are.inserted."                                /Spaces. Are. Inserted.
</code>```

Q has lower and upper functions (conversion to lowercase and to uppercase), but more primitive sub-language k (concise, used in the example) only has lower (operator _), so part of the text (12 bytes "c"$-32+"i"$) implements upper.

Split the original string using ". " as separator, processes each line, and join again

For each line we discard first character if is a blank (join inserts a blanck after each .), and capitalice first character.

Finally, insert a final "." if last char is not "."

ContentLicense: CC BY-SA 3.0

Title: Fix my Basic Orthography

Body:
Q 78 Bytes

(76 if anonymous function)

f:{(". "/:{{@[(" "=*x)_x;0;"c"$-32+"i"$]}'"."\:_-1_x}x),$["."=u:*|x;u;u,"."]}

Test

f"tHIS SenteNce HAS veRy bAd GrammAr."                  /This sentence has very bad grammar.
f"PuncTuation must-be PReserved."                       /Punctuation must-be preserved.
f"full StOps ShoulD Be inserted"                        /Full stops should be inserted.
f"MultiPLe sEntEnceS Are possible. thEY Are, yoU KNOW." /Multiple sentences are possible. They are, you know.
f"spaces. are.inserted."                                /Spaces. Are. Inserted.

Q has lower and upper functions (conversion to lowercase and to uppercase), but more primitive sub-language k (concise, used in the example) only has lower (operator _), so part of the text (12 bytes "c"$-32+"i"$) implements upper.

Split the original string using ". " as separator, processes each line, and join again

For each line we discard first character if is a blank (join inserts a blanck after each .), and capitalice first character.

Finally, insert a final "." if last char is not "."


问:
The confused twister
The basic idea is to write a program that twists itself, and the twisted version untwists itself. The first program will just be the twisting algorithm described here, and when given its own source code as input, outputs a program that reverses the twisting algorithm.

How strings are twisted

The twisting algorithm is very simple. Each column is shifted down by its index (col 0 moves down 0, col 1 moves 1, ...). The column shift wraps to the top. It kinda looks like this:

```<code>a
ba
cba
----
 cba
  cb
   c
</code>```

With everything under the line wrapping to the top. Real example:

```<code>Original:
\\\\\\\\\\\\
............
............
............

Twisted:
\...\...\...
.\...\...\..
..\...\...\.
...\...\...\
</code>```

(Further examples are here)

Input

Input is either an array of strings, or a multi-line string. All lines have the same length.

Output

The (un)twisted string, multi-line output to std-out (or closest alternative).

Example

I'm not quite sure what this is written in but oh well ;)

```<code>Twisting:
magic  TwistingAlgo
magic ntwistingAlgo
magicU twistingAlgo

Untwisting:
magic  twistingAlgo
magicUnTwistingAlgo
magic  twistingAlgo
</code>```

Other notes

Your first and second program must be in the same language.

The programs must work for any input, not just itself.

Your program must have at least 2 rows and 2 columns.

答:
Haskell, 235 bytes

```<code>main=interact$unlines.g.lines;g l@("":_)=l; g l|t<-tail<$>l,n<-length t=zipWith(:)(head<$>l)$ g$take n$drop(n-1)$t++t
maim=interact$unlines.h.lines;h l@("":_)=l; h l|t<-tail<$>l,n<-length t=zipWith(:)(head<$>l)$ h$take n$drop(2-1)$t++t
</code>```

and twisted by itself:

```<code>maim=interact$unlines.g.lines;g l@("":_)=l; g l|t<-tail<$>l,n<-length t=zipWith(:)(head<$>l)$ g$take n$drop(n-1)$t++t
main=interact$unlines.h.lines;h l@("":_)=l; h l|t<-tail<$>l,n<-length t=zipWith(:)(head<$>l)$ h$take n$drop(2-1)$t++t
</code>```

This is a full program. Both lines are mostly the same so that they are not messed up. The differences are:

```<code>normal  twisted
=================================
main=   maim=     -- after twisting the second lines defines the main function
maim=   main=     -- the other defines an unused function maim

g       g         -- As I cannot define a function (say f) multiple times,
h       h         -- I need different names for the function in both lines

n-1     n-1       -- this is for the different functionalities (twisting up /
2-1     2-1       -- twisting down). When calling g/h recursively I go with the
                  -- rest of each input line. To twist down, I drop (length n) -1
                  -- chars of two copies of the line. To twist up, I drop 2-1 chars
                  -- Then cut to the original length.
                  --
                  -- e.g.  2222    two     2222    twist   4444    twist   3333
                           3333    copies  3333    down    2222    up      4444
                           4444            4444    ->      3333    ->      2222
                                           2222    drop 2          drop 1
                                           3333
                                           4444
</code>```

Title: The confused twister

Body:
Haskell, 235 bytes

main=interact$unlines.g.lines;g l@("":_)=l; g l|t<-tail<$>l,n<-length t=zipWith(:)(head<$>l)$ g$take n$drop(n-1)$t++t
maim=interact$unlines.h.lines;h l@("":_)=l; h l|t<-tail<$>l,n<-length t=zipWith(:)(head<$>l)$ h$take n$drop(2-1)$t++t

and twisted by itself:

maim=interact$unlines.g.lines;g l@("":_)=l; g l|t<-tail<$>l,n<-length t=zipWith(:)(head<$>l)$ g$take n$drop(n-1)$t++t
main=interact$unlines.h.lines;h l@("":_)=l; h l|t<-tail<$>l,n<-length t=zipWith(:)(head<$>l)$ h$take n$drop(2-1)$t++t

This is a full program. Both lines are mostly the same so that they are not messed up. The differences are:

normal  twisted
=================================
main=   maim=     -- after twisting the second lines defines the main function
maim=   main=     -- the other defines an unused function maim

g       g         -- As I cannot define a function (say f) multiple times,
h       h         -- I need different names for the function in both lines

n-1     n-1       -- this is for the different functionalities (twisting up /
2-1     2-1       -- twisting down). When calling g/h recursively I go with the
                  -- rest of each input line. To twist down, I drop (length n) -1
                  -- chars of two copies of the line. To twist up, I drop 2-1 chars
                  -- Then cut to the original length.
                  --
                  -- e.g.  2222    two     2222    twist   4444    twist   3333
                           3333    copies  3333    down    2222    up      4444
                           4444            4444    ->      3333    ->      2222
                                           2222    drop 2          drop 1
                                           3333
                                           4444


问:
Golf a string twister

How strings are twisted

The twisting algorithm is very simple. Each column is shifted down by its index (col 0 moves down 0, col 1 moves 1, ...). The column shift wraps to the top. It works like this:

```<code>aaaa
bbbb
cccc
</code>```

Becomes:

```<code>a
ba
cba
----
 cba
  cb
   c
</code>```

With everything under the line wrapping to the top. Real example:

```<code>Original:
\\\\\\\\\\\\
............
............
............

Twisted:
\...\...\...
.\...\...\..
..\...\...\.
...\...\...\
</code>```

Input

Input is either an array of strings, or a multi-line string. All lines have the same length.

Output

The twisted string, multi-line output to std-out (or closest alternative).

Examples:

(> denotes input, trailing space is important)

```<code>>Hello, world!
>I am another
>string to be
>twisted!

Hwrmoe oo br!
Ieii ,dttr e
s lsna !ohl
ttaltgnw  ed

>\\\\\\\\\\\\
>............
>............
>............

\...\...\...
.\...\...\..
..\...\...\.
...\...\...\

>abcdefg
>.......

a.c.e.g
.b.d.f.

>abcdefghij
>..........
>..........

a..d..g..j
.b..e..h..
..c..f..i.

>\\\\.....././
>...../.......
>........././.
>..../.^\\....

\.........../
.\....^..../.
..\../.\../..
...\/...\/...

>cdeab
>deabc
>eabcd
>abcde

cbbbb
ddccc
eeedd
aaaae

>aeimquy37
>bfjnrvz48
>cgkosw159
>dhlptx260

ahknqx147
beloru258
cfipsvy69
dgjmtwz30

>abcdefghi
>jklmnopqr
>stuvwxyz1
>234567890

a3ume7yqi
jb4vnf8zr
skc5wog91
2tld6xph0
</code>```

Title: Golf a string twister

Body:
Haskell, 65 bytes

g l@("":_)=l;g l|t<-tail<$>l=zipWith(:)(head<$>l)$g$last t:init t

Usage example: g ["1111","2222","3333"] -> ["1321","2132","3213"].


问:
Judge Some Titrations
In chemistry class, we were learning about titrations, and attempting one as a lab. We were using phenolphthalein as the indicator for the titration, so on top of grading the lab normally, my teacher held a little contest to see who had the lightest shade of pink, and thus the most accurate transition.

Your task is to write a program that acts like the teacher and judges the titrations.

Specs

As input, you take a list of RGB triples in any sane format representing the titration of each student. ex: ["D966FF", "ECB3FF", "AC00E6"]. You will be guaranteed that if converted to HSL, the hue is 285 and the saturation is 100.

The conversion for RGB to HSL lightness is the average of the max and min of the normalized RGB components (*100 for a percentage).

Now the teacher is a human being and therefore cannot measure the lightness of the solution perfectly, so before you do any of the things described below, randomly change the lightness value of each of the titrations by ±3, uniformly distributed.

If a titration has a lightness value greater than 94, it is too light to  visibly see that all the acid has neutralized. Therefore, the first output is a list, sorted in descending order, of all the titrations whose RGB triples, when converted to HSL, yield a lightness value less than 94. This represents the results of the contest.

The other output is a list of all the people who have failed the lab. This includes the people with the lightness values greater than 94, but also people whose lightness values are less than or equal to 65 because these people's titrations are too inaccurate.

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

Test Cases

These test cases all assume that the error is always 0 for ease in checking if your program is correct. The results from your program should be different each time you run it.

```<code>["D966FF", "ECB3FF", "AC00E6"] -> ["ECB3FF", "D966FF", "AC00E6"], ["AC00E6"]
["EDB8FF", "D761FF", "9100C2", "FBEFFF"] -> ["EDB8FF", "D761FF", "9100C2"], ["FBEFFF", "9100C2"]
["F5D6FF"] -> ["F5D6FF"], []
</code>```

答:
Pyth, <s>35</s> 34 bytes

Input already converted to decimal.

```<code>L+O32+eSbhSbf<yTJ495Qf|gyTJ<yT347Q
</code>```

Test suite.

Previous 35-byte version:

Input already converted to decimal.

```<code>L+O32+eSbhSbf<yT495Qf|gyT495<yT347Q
</code>```

Test suite.

Verify that the third testcase is not the same for each run.

Sample input/output:

```<code>input:
[[217, 102, 255], [236, 179, 255], [172, 0, 230]]
output:
[[217, 102, 255], [236, 179, 255], [172, 0, 230]]
[[172, 0, 230]]
</code>```

Explanation

```<code>(max/255 + min/255)/2 + random[-0.03 .. 0.03] >= 0.94
(max/255 + min/255) + random[-0.06 .. 0.06] >= 1.88
max + min + random[-15 .. 15] >= 479.4
max + min + random[0 .. 31] >= 494.4
max + min + random[0 .. 31] >= 495

(max/255 + min/255)/2 + random[-0.03 .. 0.03] <= 0.65
(max/255 + min/255) + random[-0.06 .. 0.06] <= 1.30
max + min + random[-15 .. 15] <= 331.5
max + min + random[0 .. 31] <= 346.4
max + min + random[0 .. 31] < 347

L+O32+eSbhSbf<yT495Qf|gyT495<yT347Q
                                     @memoized
L                                    def y(b):
 +O32                                    return random(range(32)) +
     +eSb                                b.sort[-1] +
         hSb                             b.sort[0]
            f      Q                 filter for elements in Q as T:
             <yT495                      y(T) < 495
                                     (implicitly printed)
                    f             Q  filter for elements in Q as T
                     |gyT495             y(T) >= 495 or
                            <yT347       y(T) < 347
                                     (implicitly printed)
</code>```

Before you complain that it calls random three times, hence having inconsistent outputs from the function, note that the function is memoized.

Before you complain that different students with the same colour always produce the same outcome, note that the question never said that the random generator must be independent. It must only be uniform.

Title: Judge Some Titrations

Body:
Pyth, <s>35</s> 34 bytes

Input already converted to decimal.

L+O32+eSbhSbf<yTJ495Qf|gyTJ<yT347Q

Test suite.

Previous 35-byte version:

Input already converted to decimal.

L+O32+eSbhSbf<yT495Qf|gyT495<yT347Q

Test suite.

Verify that the third testcase is not the same for each run.

Sample input/output:

input:
[[217, 102, 255], [236, 179, 255], [172, 0, 230]]
output:
[[217, 102, 255], [236, 179, 255], [172, 0, 230]]
[[172, 0, 230]]

Explanation

(max/255 + min/255)/2 + random[-0.03 .. 0.03] >= 0.94
(max/255 + min/255) + random[-0.06 .. 0.06] >= 1.88
max + min + random[-15 .. 15] >= 479.4
max + min + random[0 .. 31] >= 494.4
max + min + random[0 .. 31] >= 495

(max/255 + min/255)/2 + random[-0.03 .. 0.03] <= 0.65
(max/255 + min/255) + random[-0.06 .. 0.06] <= 1.30
max + min + random[-15 .. 15] <= 331.5
max + min + random[0 .. 31] <= 346.4
max + min + random[0 .. 31] < 347

L+O32+eSbhSbf<yT495Qf|gyT495<yT347Q
                                     @memoized
L                                    def y(b):
 +O32                                    return random(range(32)) +
     +eSb                                b.sort[-1] +
         hSb                             b.sort[0]
            f      Q                 filter for elements in Q as T:
             <yT495                      y(T) < 495
                                     (implicitly printed)
                    f             Q  filter for elements in Q as T
                     |gyT495             y(T) >= 495 or
                            <yT347       y(T) < 347
                                     (implicitly printed)

Before you complain that it calls random three times, hence having inconsistent outputs from the function, note that the function is memoized.

Before you complain that different students with the same colour always produce the same outcome, note that the question never said that the random generator must be independent. It must only be uniform.


问:
Columnar Transposition Cipher

Columnar Transposition Cipher

While I have plenty of programs I have written for more advanced ciphers, I just realised I don't actually have one for one of the simplest: Columnar Transposition. The cipher, in case you don't know, works as follows:

First, you take the key, and write it as numbers. The numbers are made by replacing the letter which comes first in the alphabet with 1, the letter that comes next 2 and so on, ignoring duplicates (the key GOAT would become 2314). These numbers are the headers of the columns.

```<code>2314
----
</code>```

Next, you write your message under the columns.

```<code>2314
----
Hell
o Wo
rld!
</code>```

Finally, rearrange the columns into the numerical order in which they would fall, and read the ciphertext across.

```<code>1234
----
lHel
Wo o
drl!
</code>```

Which will result in your encoded text: lHelWo odrl!

Rules

Each submission should be either a full program or function. If it is a function, it must be runnable by only needing to add the function call to the bottom of the program. Anything else (e.g. headers in C), must be included.

There must be a free interpreter/compiler available for your language.

If it is possible, provide a link to a site where your program can be tested.

Your program must not write anything to STDERR.

Your program should take input as an argument or from STDIN (or the closest alternative in your language).

Standard loopholes are forbidden.

Requirements

Case must be preserved.

Your cipher should be 'irregular', that is, if there are any spaces left after you have written out your message, it is treated as if it were a normal space character.

Only encryption is required, decryption may come in a later challenge.

Input should be taken from STDIN with the key on the first line, and the plaintext on the second. If you are taking input as an argument, please specify how this is done for your language.

The key can be in any case.

Duplicates in the key should be ignored - that is, ABCDB would become ABCD. Duplicates also apply in any case.

Trailing whitespace is included.

Test Cases

```<code>CBABD, Duplicates are ignored. ==> puDlacit sea eriongr.de
bDaEc, Key can be in multicase! ==> yKce  aenbn mi tucliea s!
</code>```

Full example, with 'surplus space' rule.

```<code>ADCB
----
"Goo
d Mo
rnin
g!"
he c
alle
d.

ABCD
----
"ooG
dom
rnin
g "!
hc e
aell
d  .

Message: "ooGdom rning "!hc eaelld  .
</code>```

Scoring

code-golf is how we score this challenge!

Submissions

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

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

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

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

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

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

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

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

Leaderboard

Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language.

/* Configuration */

var QUESTION_ID = 79810; // Obtain this from the url
// It will be like https://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page
var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";
var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk";
var OVERRIDE_USER = 53406; // This should be the user ID of the challenge author.

/* App */

var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page;

function answersUrl(index) {
  return "https://api.stackexchange.com/2.2/questions/" +  QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER;
}

function commentUrl(index, answers) {
  return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER;
}

function getAnswers() {
  jQuery.ajax({
    url: answersUrl(answer_page++),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      answers.push.apply(answers, data.items);
      answers_hash = [];
      answer_ids = [];
      data.items.forEach(function(a) {
        a.comments = [];
        var id = +a.share_link.match(/\d+/);
        answer_ids.push(id);
        answers_hash[id] = a;
      });
      if (!data.has_more) more_answers = false;
      comment_page = 1;
      getComments();
    }
  });
}

function getComments() {
  jQuery.ajax({
    url: commentUrl(comment_page++, answer_ids),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      data.items.forEach(function(c) {
        if (c.owner.user_id === OVERRIDE_USER)
          answers_hash[c.post_id].comments.push(c);
      });
      if (data.has_more) getComments();
      else if (more_answers) getAnswers();
      else process();
    }
  });
}

getAnswers();

var SCORE_REG = /<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/;

var OVERRIDE_REG = /^Override\s*header:\s*/i;

function getAuthorName(a) {
  return a.owner.display_name;
}

function process() {
  var valid = [];

  answers.forEach(function(a) {
    var body = a.body;
    a.comments.forEach(function(c) {
      if(OVERRIDE_REG.test(c.body))
        body = '
' + c.body.replace(OVERRIDE_REG, '') + '
';
    });

    var match = body.match(SCORE_REG);
    if (match)
      valid.push({
        user: getAuthorName(a),
        size: +match[2],
        language: match[1],
        link: a.share_link,
      });

  });

  valid.sort(function (a, b) {
    var aB = a.size,
        bB = b.size;
    return aB - bB
  });

  var languages = {};
  var place = 1;
  var lastSize = null;
  var lastPlace = 1;
  valid.forEach(function (a) {
    if (a.size != lastSize)
      lastPlace = place;
    lastSize = a.size;
    ++place;

    var answer = jQuery("#answer-template").html();
    answer = answer.replace("{{PLACE}}", lastPlace + ".")
                   .replace("{{NAME}}", a.user)
                   .replace("{{LANGUAGE}}", a.language)
                   .replace("{{SIZE}}", a.size)
                   .replace("{{LINK}}", a.link);
    answer = jQuery(answer);
    jQuery("#answers").append(answer);

    var lang = a.language;
    if (/ b.lang) return 1;
    if (a.lang < b.lang) return -1;
    return 0;
  });

  for (var i = 0; i < langs.length; ++i)
  {
    var language = jQuery("#language-template").html();
    var lang = langs[i];
    language = language.replace("{{LANGUAGE}}", lang.lang)
                       .replace("{{NAME}}", lang.user)
                       .replace("{{SIZE}}", lang.size)
                       .replace("{{LINK}}", lang.link);
    language = jQuery(language);
    jQuery("#languages").append(language);
  }

}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body { text-align: left !important}

#answer-list {
  padding: 10px;
  width: 290px;
  float: left;
}

#language-list {
  padding: 10px;
  width: 290px;
  float: left;
}

table thead {
  font-weight: bold;
}

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

```

答:
Q, 52 Bytes

```<code>f:{n:#u::?_x;,/+(+(0N;n)#(n*-_-(#y)%n)#y,n#" ")@<u}
</code>```

NOTE.- defined as function named f to facilitate tests. As an anonymous function we delete chars f: (50 Bytes)

Test

Interpreter (evaluation but unrestricted) downloadable by not fee at kc.com (windows/linux/mac versions)

```<code>f["CBABD"]"Duplicates are ignored."     /"puDlacit sea eriongr.de"
f["bDaEc"]"Key can be in multicase!"    /"yKce  aenbn mi tucliea s!"
</code>```

Explanation

n:#u:?_x u is unique chars in lowercase key, and n its length

(n*-_-(#y)%n)#y,n#" " appends blanks to accomplish 'space surplus' rule.

% is division
-_- implements ceil as negate floor negate, so (n*-_-(#y)%n) is the length required by space surplus. y,n#" " append n blank spaces to end of text, and then take length of that extended text

```<code>(0N;n)#.. takes items of sequence .. to fill a matrix of n columns by row
</code>```

+(..) flip that matrix (traspose) to work by rows

@<u selects row indexes by ascending index order of u

```<code>,/(..) concatenates the resulting matrix to obtain a text
</code>```

Title: Columnar Transposition Cipher

Body:
Q, 52 Bytes

f:{n:#u::?_x;,/+(+(0N;n)#(n*-_-(#y)%n)#y,n#" ")@<u}

NOTE.- defined as function named f to facilitate tests. As an anonymous function we delete chars f: (50 Bytes)

Test

Interpreter (evaluation but unrestricted) downloadable by not fee at kc.com (windows/linux/mac versions)

f["CBABD"]"Duplicates are ignored."     /"puDlacit sea eriongr.de"
f["bDaEc"]"Key can be in multicase!"    /"yKce  aenbn mi tucliea s!"

Explanation

n:#u:?_x u is unique chars in lowercase key, and n its length

(n*-_-(#y)%n)#y,n#" " appends blanks to accomplish 'space surplus' rule.

% is division
-_- implements ceil as negate floor negate, so (n*-_-(#y)%n) is the length required by space surplus. y,n#" " append n blank spaces to end of text, and then take length of that extended text

(0N;n)#.. takes items of sequence .. to fill a matrix of n columns by row

+(..) flip that matrix (traspose) to work by rows

@<u selects row indexes by ascending index order of u

,/(..) concatenates the resulting matrix to obtain a text


问:
Will the beam hit?
A laser shoots a straight beam in one of the four orthogonal directions, indicated by <>^v. Determine whether it will hit the target O on a rectangular grid.

Each of these will hit (True):

```<code>.....
...O.
.....
...^.
.....

>O.
...

v....
O....

...........
...........
O.........<
...........
</code>```

These will miss (False):

```<code>......
......
.^..O.

......
.....>
O.....
......
......

.O.
...
.v.

.....<.
..O....
</code>```

Input: A rectangular grid of ., sized at least 2x2, with exactly one target O and one laser that's one of <>^v. The lines can be a list of strings, a 2D array or nested list of characters, or a single newline-separated string with an optional trailing newline.

Output: A consistent truthy value if the laser beam hits the target, and a consistent falsy value if it misses.

I'll consider submissions that don't use regular expressions (or built-in pattern-based string matching) as a separate category. If you put (no regex) after the language name, your answer will appear separately in the leaderboard.

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

```

答:
Python (no regex), 105 bytes

```<code>def f(s):t=s.strip('.\n');return not['\n'in t,len(t)%(s.find('\n')+1)!=1,1]['>O<vO^'.find(t[0]+t[-1])//3]
</code>```

returns True or False

First, strips '.' and '\n' from the ends so that the characters of interest, '0<>v^', are the first and last characters.

'>O<vO^'.find(t[0]+t[-1])//3 - checks if the characters are a potentially valid arrangement. Evaluates to 0 for '>O' or 'O<', to 1 for 'vO' or 'O^', and to -1 for anything else.

'\n'in t - checks if the characters are in different rows,

len(t)%(s.find('\n')+1)!=1 - checks if they are in different columns, and

1 - is the default

The not inverts the result selected from the list, so the return expression is equivalent to:

```<code>t[0]+t[-1] in '>0<' and '\n' not in t or t[0]+t[-1] in 'vO^' and len(t)%(s.find('\n')+1)==1
</code>```

Title: Will the beam hit?

Body:
Python (no regex), 105 bytes

def f(s):t=s.strip('.\n');return not['\n'in t,len(t)%(s.find('\n')+1)!=1,1]['>O<vO^'.find(t[0]+t[-1])//3]

returns True or False

First, strips '.' and '\n' from the ends so that the characters of interest, '0<>v^', are the first and last characters.

'>O<vO^'.find(t[0]+t[-1])//3 - checks if the characters are a potentially valid arrangement. Evaluates to 0 for '>O' or 'O<', to 1 for 'vO' or 'O^', and to -1 for anything else.

'\n'in t - checks if the characters are in different rows,

len(t)%(s.find('\n')+1)!=1 - checks if they are in different columns, and

1 - is the default

The not inverts the result selected from the list, so the return expression is equivalent to:

t[0]+t[-1] in '>0<' and '\n' not in t or t[0]+t[-1] in 'vO^' and len(t)%(s.find('\n')+1)==1


问:
Determine whether strings are anagrams

Challenge

Given two strings, work out if they both have exactly the same characters in them.

Example

Input

word, wrdo

This returns true because they are the same but just scrambled.

Input

word, wwro

This returns false.

Input

boat, toba

This returns true

Rules

Here are the rules!

Assume input will be at least 1 char long, and no longer than 8 chars.

No special characters, only a–z

All inputs can be assumed to be lowercase

Test Cases

```<code>boat, boat = true
toab, boat = true
oabt, toab = true
a, aa = false
zzz, zzzzzzzz = false
zyyyzzzz, yyzzzzzy = true
sleepy, pyels = false
p,p = true
</code>```

答:
Q, 15 Bytes

```<code>f:{~/{x@<x}'x}
</code>```

f is the name of the function

Test

```<code>f("boat";"boat")            /1b
f("toab";"boat")            /1b
f("oabt";"toab")            /1b
f(,"a";"aa")                /0b
f("zzz";"zzzzzzzz")         /0b
f("zyyyzzzz";"yyzzzzzy")    /1b
f("sleepy";"pyels")         /0b
f(,"p";,"p")                /1b
</code>```

Explanation

Argument of the function is a sequence with both words. At each word applies {x@<x}, that sorts x (take from x in ascending index ordering). ~/ reads as "match over", and compares both transformed words

Title: Determine whether strings are anagrams

Body:
Q, 15 Bytes

f:{~/{x@<x}'x}

f is the name of the function

Test

f("boat";"boat")            /1b
f("toab";"boat")            /1b
f("oabt";"toab")            /1b
f(,"a";"aa")                /0b
f("zzz";"zzzzzzzz")         /0b
f("zyyyzzzz";"yyzzzzzy")    /1b
f("sleepy";"pyels")         /0b
f(,"p";,"p")                /1b

Explanation

Argument of the function is a sequence with both words. At each word applies {x@<x}, that sorts x (take from x in ascending index ordering). ~/ reads as "match over", and compares both transformed words


问:
Output the alphabet using the alphabet
The title is pretty self-explanatory, isn't it?

Your task is to output the alphabet (the string "abcdefghijklmnopqrstuvwxyz") to STDOUT, using each and every letter of the alphabet in your program once and only once.

Oh, and for a bit of extra fun?

The letters "g", "o", "l" and "f" must be in order (just for the code to be a bit more code-y).

Rules:

Only standard letters of the alphabet from ASCII count as letters (ë != e).

Both uppercase and lowercase characters count as letters (if you have E, you are not allowed to have e).

You are allowed to use comments, but every character in the comment is equal to 2 bytes.

Your final score will be the byte-count of your program, subtracted by 26.

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

答:
Jolf, 27 - 26 = 1 byte

```<code>goΔaplfbcdehijkmnqrstuvwxyz
</code>```

o assigns Δ to apl, which alerts pl, which is the lowercase alphabet. I take it that "in order" does not mean "adjacent to". You can see that f follows l which follows o which follows g. Try it out here!

Title: Output the alphabet using the alphabet

Body:
Jolf, 27 - 26 = 1 byte

goΔaplfbcdehijkmnqrstuvwxyz

o assigns Δ to apl, which alerts pl, which is the lowercase alphabet. I take it that "in order" does not mean "adjacent to". You can see that f follows l which follows o which follows g. Try it out here!


问:
Let's play ASCII mini-golf
Let's play code golf... by playing golf.

Input

Your input will be a string consisting of #'s, an o, an @, and .'s. For example:

```<code>......@..
.....##..
.........
......o..
</code>```

. - playable golf course (all shots must end on one of these)

# - a barrier (shots cannot go through this)

o - the starting position of your golf ball

@ - the hole

How to Play ASCII Golf

You start at the o. Here is a valid shot from point A to point B:

1) This shot is straight line that can be drawn between A and B (no curved shots).

```<code>A....
....B
</code>```

2) The line AB may not intersect with a # (barrier), e.g.:

```<code>A.#.B
</code>```

It may, however, be tangent to a barrier:

```<code>A#
.B
</code>```

3) (For clarity) You may not bounce shots off barriers or the edge of the golf course.

Output

Print to stdout (or an acceptable equivalent) the minimum number of shots to get the ball into the hole @. If it is not possible, print -1.

Examples

```<code>o....@
</code>```

=> 1

```<code>o.#.@
</code>```

=> -1

```<code>o..#
..#@
</code>```

=> 2 (you can pass through the vertices of a #, but not the edges)

```<code>o#...#
.#.#.#
...#.@
</code>```

=> 4

答:
Python 2, 469

Pretty long, but it's a start:

R=range
def l(c,x,y,z,t):
 f=abs(z-x);g=1-2*(z<x);p=abs(t-y);q=1-2*(t<y);v=r=0
 for i in R(f):
  w=f+(2*i+1)*p
  for j in R(v,(w-1)/2/f+1):r|='.'>c[x+g*i][y+q*j]
  v=w/2/f
 for j in R(v,p+1):r|='.'>c[z][y+q*j]
 return r
def f(c):
 a="".join(c);n=len(c[0]);b=len(a);d=[[9**9*l(c,i/n,i%n,j/n,j%n)+1for i in R(b)]for j in R(b)]
 for k in R(b):
  for i in R(b):
   for j in R(b):
    t=d[i][j]=min(d[i][j],d[i][k]+d[k][j])
    if"o@"==a[i]+a[j]:r=t
 return-1if r>9**9else r
```
<p>Function f takes a list of strings and returns the number of shots.</p>
<p>Test suite:</p>
<pre class="lang-python prettyprint-override"><code>def test(s,r):
 print"ok"if f(s.split())==r else"fail"

test("o # @", -1)
test("......@.. .....##.. ......... ......o..", 2)
test("o....@", 1)
test("o.#.@", -1)
test("o..# ..#@", 2)
test("o#...# .#.#.# ...#.@", 4)
test("o### #..# ###@", 3)
test("o.## ##.@", 1)
test("...o .@#.", 2)
</code>```

Title: Let's play ASCII mini-golf

Body:
Python 2, 469

Pretty long, but it's a start:

R=range
def l(c,x,y,z,t):
 f=abs(z-x);g=1-2*(z<x);p=abs(t-y);q=1-2*(t<y);v=r=0
 for i in R(f):
  w=f+(2*i+1)*p
  for j in R(v,(w-1)/2/f+1):r|='.'>c[x+g*i][y+q*j]
  v=w/2/f
 for j in R(v,p+1):r|='.'>c[z][y+q*j]
 return r
def f(c):
 a="".join(c);n=len(c[0]);b=len(a);d=[[9**9*l(c,i/n,i%n,j/n,j%n)+1for i in R(b)]for j in R(b)]
 for k in R(b):
  for i in R(b):
   for j in R(b):
    t=d[i][j]=min(d[i][j],d[i][k]+d[k][j])
    if"o@"==a[i]+a[j]:r=t
 return-1if r>9**9else r

Function f takes a list of strings and returns the number of shots.

Test suite:

def test(s,r):
 print"ok"if f(s.split())==r else"fail"

test("o # @", -1)
test("......@.. .....##.. ......... ......o..", 2)
test("o....@", 1)
test("o.#.@", -1)
test("o..# ..#@", 2)
test("o#...# .#.#.# ...#.@", 4)
test("o### #..# ###@", 3)
test("o.## ##.@", 1)
test("...o .@#.", 2)


问:
The game of Sevens! Who said what?
The game of Sevens is played as follows: n players sit in a circle, and start counting up from 1, passing to the left (or from player A to player B).

When a number p that has a 7 in it OR is divisible by 7 is reached, then the player who spoke the number p-1, after the next player says p, must say p+1 and the order of people speaking reverses. For example, if player B speaks 6, player C says 7, B says 8, and player A says 9.

Note: For those who want to play in real life, if a person forgets a number (or in the version where sevens are not said, accidentally says a seven), they are eliminated from the circle, but we will omit this detail from this challenge.

The challenge itself is to print which numbers each player should say in a perfect game of Sevens up to an input m for an input n players.

As an example, where five people, A, B, C, D, and E, are to play till they reach 30. They play in this manner

```<code>A: 1 6 8 13    15 19       23    30
B: 2 7*  12    16 18       24
C: 3     11    17*         25
D: 4     10          21*   26 28*
E: 5      9 14*      20 22 27*29
</code>```

where sevens are marked with *. Note that at 27 and 28, we're reversing twice, and play continues "as normal" from D to E.

Please note that the output does not have to be in the above format. I simply printed it that way for some clarity.

Rules

The input is two integers in any order, m representing the last number to say, n representing the number of players.

The output can be several arrays or several strings, one for each player. If you use strings, you do not have to use separators (though, if you could add some in your code tests, we would appreciate the readability). If you can actually print them in a circle somehow, that is acceptable as well, and it would be pretty cool too.

The output does not have to designate which players are which (it's fairly obvious that the first player is the one who says 1), though if the output isn't sorted for whatever reason, you should make clear which player is speaking which set of numbers. Omitting players who do not say anything is also allowed if you make it clear which players are speaking. I will add some more examples of possible outputs below.

This is code golf, so the smallest number of bytes wins.

As always, if the problem is unclear, please let me know. Good luck and good golfing!

Examples

```<code>>>> sevens_string(30, 5, " ")
'1 6 8 13 15 19 23 30'
'2 7 12 16 18 24'
'3 11 17 25'
'4 10 21 26 28'
'5 9 14 20 22 27 29'
>>> sevens_string(42, 5)
'16813151923303539'
'27121618243140'
'31117253241'
'410212628333742'
'591420222729343638'
>>> sevens_array(20, 3)
[1, 4, 7, 10, 13, 15, 19]
[2, 5, 9, 12, 16, 18]
[3, 6, 8, 11, 14, 17, 20]
>>> sevens_array(18, 10)
[1, 13, 15]
[2, 12, 16, 18]
[3, 11, 17]
[4, 10]
[5, 9]
[6, 8]
[7]
[]
[]
[14]
</code>```

答:
JavaScript (ES6) 100

Returning result as a string array, no separators

(m,n)=>(d=>{for(r=[],p=i=0;i++<m;d=i%7&&!~(i+'').search(7)?d:n-d,p=(p+d)%n)r[p]=(r[p]||'')+i})(1)||r
```

<p>Or more readable, for 3 bytes more, returning result as an array of arrays</p>

<pre class="lang-js prettyprint-override"><code>(m,n)=>(d=>{for(r=[],p=i=0;i++<m;d=i%7&&!~(i+'').search(7)?d:n-d,p=(p+d)%n)r[p]=[...r[p]||[],i]})(1)||r
</code>```

Test Using the new wonderful console feature of the Stack Snippets

S=(m,n)=>(d=>{for(r=[],p=i=0;i++<m;d=i%7&&!~(i+'').search(7)?d:n-d,p=(p+d)%n)r[p]=(r[p]||'')+i})(1)||r

A=(m,n)=>(d=>{for(r=[],p=i=0;i++<m;d=i%7&&!~(i+'').search(7)?d:n-d,p=(p+d)%n)r[p]=[...r[p]||[],i]})(1)||r

console.log(S(42,5))
console.log(A(20,3))```

Title: The game of Sevens! Who said what?

Body:
JavaScript (ES6) 100

Returning result as a string array, no separators

(m,n)=>(d=>{for(r=[],p=i=0;i++<m;d=i%7&&!~(i+'').search(7)?d:n-d,p=(p+d)%n)r[p]=(r[p]||'')+i})(1)||r

Or more readable, for 3 bytes more, returning result as an array of arrays

(m,n)=>(d=>{for(r=[],p=i=0;i++<m;d=i%7&&!~(i+'').search(7)?d:n-d,p=(p+d)%n)r[p]=[...r[p]||[],i]})(1)||r

Test Using the new wonderful console feature of the Stack Snippets

S=(m,n)=>(d=>{for(r=[],p=i=0;i++<m;d=i%7&&!~(i+'').search(7)?d:n-d,p=(p+d)%n)r[p]=(r[p]||'')+i})(1)||r

A=(m,n)=>(d=>{for(r=[],p=i=0;i++<m;d=i%7&&!~(i+'').search(7)?d:n-d,p=(p+d)%n)r[p]=[...r[p]||[],i]})(1)||r

console.log(S(42,5))
console.log(A(20,3))


答:
Python 2, <s>91</s> <s>90</s> 87 bytes

```<code>def f(m,n):a=d=i=0;r=[()]*n;exec"i+=1;r[a%n]+=i,;d^='7'[:i%7]in`i`;a+=1-2*d;"*m;print r
</code>```

Prints a list of tuples. Test it on Ideone.

Title: The game of Sevens! Who said what?

Body:
The game of Sevens is played as follows: n players sit in a circle, and start counting up from 1, passing to the left (or from player A to player B).

When a number p that has a 7 in it OR is divisible by 7 is reached, then the player who spoke the number p-1, after the next player says p, must say p+1 and the order of people speaking reverses. For example, if player B speaks 6, player C says 7, B says 8, and player A says 9.

Note: For those who want to play in real life, if a person forgets a number (or in the version where sevens are not said, accidentally says a seven), they are eliminated from the circle, but we will omit this detail from this challenge.

The challenge itself is to print which numbers each player should say in a perfect game of Sevens up to an input m for an input n players.

As an example, where five people, A, B, C, D, and E, are to play till they reach 30. They play in this manner

```<code>A: 1 6 8 13    15 19       23    30
B: 2 7*  12    16 18       24
C: 3     11    17*         25
D: 4     10          21*   26 28*
E: 5      9 14*      20 22 27*29
</code>```

where sevens are marked with *. Note that at 27 and 28, we're reversing twice, and play continues "as normal" from D to E.

Please note that the output does not have to be in the above format. I simply printed it that way for some clarity.

Rules

The input is two integers in any order, m representing the last number to say, n representing the number of players.

The output can be several arrays or several strings, one for each player. If you use strings, you do not have to use separators (though, if you could add some in your code tests, we would appreciate the readability). If you can actually print them in a circle somehow, that is acceptable as well, and it would be pretty cool too.

The output does not have to designate which players are which (it's fairly obvious that the first player is the one who says 1), though if the output isn't sorted for whatever reason, you should make clear which player is speaking which set of numbers. Omitting players who do not say anything is also allowed if you make it clear which players are speaking. I will add some more examples of possible outputs below.

This is code golf, so the smallest number of bytes wins.

As always, if the problem is unclear, please let me know. Good luck and good golfing!

Examples

```<code>>>> sevens_string(30, 5, " ")
'1 6 8 13 15 19 23 30'
'2 7 12 16 18 24'
'3 11 17 25'
'4 10 21 26 28'
'5 9 14 20 22 27 29'
>>> sevens_string(42, 5)
'16813151923303539'
'27121618243140'
'31117253241'
'410212628333742'
'591420222729343638'
>>> sevens_array(20, 3)
[1, 4, 7, 10, 13, 15, 19]
[2, 5, 9, 12, 16, 18]
[3, 6, 8, 11, 14, 17, 20]
>>> sevens_array(18, 10)
[1, 13, 15]
[2, 12, 16, 18]
[3, 11, 17]
[4, 10]
[5, 9]
[6, 8]
[7]
[]
[]
[14]
</code>```

Body:
Python 2, <s>91</s> <s>90</s> 87 bytes

def f(m,n):a=d=i=0;r=[()]*n;exec"i+=1;r[a%n]+=i,;d^='7'[:i%7]in`i`;a+=1-2*d;"*m;print r

Prints a list of tuples. Test it on Ideone.


问:
Calculate the Numpad Taxicab
Credit goes where credit is due

Given two digits, x, and y, calculate the shortest number of horizontal or vertical jumps to get from x to y on a standard numpad, e.g.

```<code>789
456
123
00
</code>```

You can safely assume that all inputs will be 0-9, and you do not have to handle invalid inputs. The input may be the same number twice, which has a distance of 0.

IO can be in any reasonable format, and standard loopholes are forbidden. Shortest answer in bytes wins!

Sample IO:

```<code>1, 4: 1
1, 8: 3
3, 7: 4
8, 2: 2
6, 1: 3
0, 9: 4
4, 4: 0
0, 4: 2
</code>```

Title: Calculate the Numpad Taxicab

Body:
Pyth, <s>22</s> <s>21</s> 19 bytes

FGITW.

L.D?b+2b.5 3ssaMCyM

Test suite.

Conversion table:

0: [0.0, 0.5]
1: [1, 0]
2: [1, 1]
3: [1, 2]
4: [2, 0]
5: [2, 1]
6: [2, 2]
7: [3, 0]
8: [3, 1]
9: [3, 2]


答:
Jelly, <s>27</s> 25 bytes

```<code>D;Æf7e
R’Ç€^\ḤC+\_'R}⁹ḍT€
</code>```

Try it online! or verify all test cases.

Title: The game of Sevens! Who said what?

Body:
Jelly, <s>27</s> 25 bytes

D;Æf7e
R’Ç€^\ḤC+\_'R}⁹ḍT€

Try it online! or verify all test cases.

ContentLicense: CC BY-SA 4.0


答:
Jelly, 11 bytes

```<code>o-1.’d3ạ/ḞS
</code>```

Try it online! or verify all test cases.

How it works

```<code>o-1.’d3ạ/ḞS  Main link. Argument: [a, b] (list of integers)

 -1.         Yield -1.5.
o            Take the logical OR of a and b with -1.5.
             This maps 0 to -1.5, and all other integers to themselves.
    ’        Decrement the results.
     d3      Divmod; compute quotient and remainder of each result divided by 3.
       ạ/    Reduce by absolute difference across columns.
         Ḟ   Floor; round all differences down to the nearest integer.
          S  Sum; add the rounded absolute differences.
</code>```

Title: Calculate the Numpad Taxicab

Body:
Credit goes where credit is due

Given two digits, x, and y, calculate the shortest number of horizontal or vertical jumps to get from x to y on a standard numpad, e.g.

```<code>789
456
123
00
</code>```

You can safely assume that all inputs will be 0-9, and you do not have to handle invalid inputs. The input may be the same number twice, which has a distance of 0.

IO can be in any reasonable format, and standard loopholes are forbidden. Shortest answer in bytes wins!

Sample IO:

```<code>1, 4: 1
1, 8: 3
3, 7: 4
8, 2: 2
6, 1: 3
0, 9: 4
4, 4: 0
0, 4: 2
</code>```

Body:
Jelly, 11 bytes

o-1.’d3ạ/ḞS

Try it online! or verify all test cases.

How it works

o-1.’d3ạ/ḞS  Main link. Argument: [a, b] (list of integers)

 -1.         Yield -1.5.
o            Take the logical OR of a and b with -1.5.
             This maps 0 to -1.5, and all other integers to themselves.
    ’        Decrement the results.
     d3      Divmod; compute quotient and remainder of each result divided by 3.
       ạ/    Reduce by absolute difference across columns.
         Ḟ   Floor; round all differences down to the nearest integer.
          S  Sum; add the rounded absolute differences.


答:
Jelly, 13 bytes

```<code>+2$.¹?€d3ạ/SḞ
</code>```

Try it online!

Port of my Pyth answer.

Test suite.

Title: Calculate the Numpad Taxicab

Body:
Jelly, 13 bytes

+2$.¹?€d3ạ/SḞ

Try it online!

Port of my Pyth answer.

Test suite.


答:
JavaScript (ES6), 59

Unfortunately, no divmod in javascript. In fact, no integer div, and no mod either: the % is not exactly mod. But for once, the weird behaviour of % with negative numbers is useful.

```<code>(a,b,A=Math.abs)=>A(~(--a/3)-~(--b/3))+A(a%3-b%3)-(a*b%3<0)
</code>```

Test

f=(a,b,A=Math.abs)=>A(~(--a/3)-~(--b/3))+A(a%3-b%3)-(a*b%3<0)

for(i=0;i<10;console.log(r),i++)
  for(r='',j=0;j<10;j++)
    r+=[i,j,f(i,j)]+' '```

Title: Calculate the Numpad Taxicab

Body:
JavaScript (ES6), 59

Unfortunately, no divmod in javascript. In fact, no integer div, and no mod either: the % is not exactly mod. But for once, the weird behaviour of % with negative numbers is useful.

(a,b,A=Math.abs)=>A(~(--a/3)-~(--b/3))+A(a%3-b%3)-(a*b%3<0)

Test

f=(a,b,A=Math.abs)=>A(~(--a/3)-~(--b/3))+A(a%3-b%3)-(a*b%3<0)

for(i=0;i<10;console.log(r),i++)
  for(r='',j=0;j<10;j++)
    r+=[i,j,f(i,j)]+' '


Title: The game of Sevens! Who said what?

Body:
J, <s>63</s> <s>60</s> <s>59</s> <s>58</s> 56 bytes

4 :'>:@I.(i.y)=/y|+/\0,_1^+/\(7 e."1 q:,.10#.inv])}.i.x'

Verification

   f =: 4 :'>:@I.(i.y)=/y|+/\0,_1^+/\(7 e."1 q:,.10#.inv])}.i.x'
   30 f 5
1  6  8 13 15 19 23 30
2  7 12 16 18 24  0  0
3 11 17 25  0  0  0  0
4 10 21 26 28  0  0  0
5  9 14 20 22 27 29  0
   42 f 5
1  6  8 13 15 19 23 30 35 39
2  7 12 16 18 24 31 40  0  0
3 11 17 25 32 41  0  0  0  0
4 10 21 26 28 33 37 42  0  0
5  9 14 20 22 27 29 34 36 38
   20 f 3
1 4 7 10 13 15 19
2 5 9 12 16 18  0
3 6 8 11 14 17 20
   14 f 10
 1 13
 2 12
 3 11
 4 10
 5  9
 6  8
 7  0
 0  0
 0  0
14  0


问:
Chaining Words Together
Given two words and a list as input, your program must (in as few characters as possible, of course) find the shortest way to "chain" the first word to the last using the ones in the list. Two words are "chained" if their first and last letters are the same, e.g. "Food" and "Door".

Your program will take input as a string with words separated by spaces, and output a list (in whatever format is most convenient: string, array/list type, etc) of the completed chain.

Examples:

Input: joke corn tan disc need eat

Output: joke eat tan need disc corn

The first two words in the input list are the first and last words in the chain, and the rest are the constituent words.

Input: best fry easy elf mean tame yam nice

Output: best tame elf fry

NOT: best tame easy yam mean nice elf fry

Input: rug gunned orange purple gains pore soup emo ending

Output: rug gunned

Input: %3gioxl? 6699-4 !f!!&+ ?4; ;78! +6

Output: %3gioxl? ?4; ;78! !f!!&+ +6 6699-4

The "words" don't have to be real words; for the purpose of the challenge, any ASCII character except the space will count as part of a word.

Input: mouth rich frame inspire item sold

Output when the first and last word are impossible to chain is undefined, so handle it however's shortest.

答:
Pyth, <s>51</s> 48 bytes

FGITW.

```<code>=cQdMqeGhHL++hQb@Q1holN{+Fmf.AgVTtTyM+]Y._d.p>Q2
</code>```

Test suite.

Title: Chaining Words Together

Body:
Pyth, <s>51</s> 48 bytes

FGITW.

=cQdMqeGhHL++hQb@Q1holN{+Fmf.AgVTtTyM+]Y._d.p>Q2

Test suite.


答:
Python, 140 114 bytes

I am a first timer, so please help. Here's my code.

```<code>def f(x,y):x,y,k=x-1,y-1,abs;return x!=-1 and y!=-1 and k(y//3-x//3)+k(y%3-x%3) or k(y//3-x//3)+int(max(x,y)%3==2)
</code>```

Title: Calculate the Numpad Taxicab

Body:
Python, 140 114 bytes

I am a first timer, so please help. Here's my code.

def f(x,y):x,y,k=x-1,y-1,abs;return x!=-1 and y!=-1 and k(y//3-x//3)+k(y%3-x%3) or k(y//3-x//3)+int(max(x,y)%3==2)


问:
How slow is Python really? (Or how fast is your language?)
I have this code which I have written in Python/NumPy

from __future__ import division
import numpy as np
import itertools

n = 6
iters = 1000
firstzero = 0
bothzero = 0
""" The next line iterates over arrays of length n+1 which contain only -1s and 1s """
for S in itertools.product([-1, 1], repeat=n+1):
    """For i from 0 to iters -1 """
    for i in xrange(iters):
        """ Choose a random array of length n.
            Prob 1/4 of being -1, prob 1/4 of being 1 and prob 1/2 of being 0. """
        F = np.random.choice(np.array([-1, 0, 0, 1], dtype=np.int8), size=n)
        """The next loop just makes sure that F is not all zeros."""
        while np.all(F == 0):
            F = np.random.choice(np.array([-1, 0, 0, 1], dtype=np.int8), size=n)
        """np.convolve(F, S, 'valid') computes two inner products between
        F and the two successive windows of S of length n."""
        FS = np.convolve(F, S, 'valid')
        if FS[0] == 0:
            firstzero += 1
        if np.all(FS == 0):
            bothzero += 1

print("firstzero: %i" % firstzero)
print("bothzero: %i" % bothzero)
```

It is counting the number of times the convolution of two random arrays, one which is one longer than the other, with a particular probability distribution, has a 0 at the first position or a 0 in both positions.

I had a bet with a friend who says Python is a terrible language to write code in that needs to be fast.  It takes 9s on my computer.  He says it could be made 100 times faster if written in a "proper language".

The challenge is to see if this code can indeed by made 100 times faster in any language of your choice.  I will test your code and the fastest one week from now will win.  If anyone gets below 0.09s then they automatically win and I lose.

Status

Python. 30 times speed up by Alistair Buxon! Although not the fastest solution it is in fact my favourite.

Octave. 100 times speed up by @Thethos.

Rust. 500 times speed up by @dbaupp.

C++. 570 times speed up by Guy Sirton.

C. 727 times speed up by @ace.

C++. Unbelievably fast by @Stefan.

The fastest solutions are now too fast to sensibly time.  I have therefore increased n to 10 and set iters = 100000 to compare the best ones. Under this measure the fastest are.

C. 7.5s by @ace.

C++. 1s by @Stefan.

My Machine The timings will be run on my machine. This is a standard ubuntu install on an AMD FX-8350 Eight-Core Processor.  This also means I need to be able to run your code.

Follow up posted As this competition was rather too easy to get a x100 speedup, I have posted a followup for those who want to exercise their speed guru expertise. See How Slow Is Python Really (Part II)?

答:
Q, 0.296 seg

```<code>n:6; iter:1000  /parametrization (constants)
c:n#0           /auxiliar constant (sequence 0 0.. 0 (n))
A:B:();         /A and B accumulates results of inner product (firstresult, secondresult)

/S=sequence with all arrays of length n+1 with values -1 and 1
S:+(2**m)#/:{,/x#/:-1 1}'m:|n(2*)\1

f:{do[iter; F:c; while[F~c; F:n?-1 0 0 1]; A,:+/F*-1_x; B,:+/F*1_x];} /hard work
f'S               /map(S,f)
N:~A; +/'(N;N&~B) / ~A is not A (or A=0) ->bitmap.  +/ is sum (population over a bitmap)
                  / +/'(N;N&~B) = count firstResult=0, count firstResult=0 and secondResult=0
</code>```

Q is a collection oriented language (kx.com)

Code rewrited to explote idiomatic Q, but no other clever optimizations

Scripting languages optimize programmer time, not execution time

Q is not the best tool for this problem

First coding attempt = not a winner, but reasonable time (approx. 30x speedup)

quite competitive among interpreters

stop and choose another problem

NOTES.-

program uses default seed (repeteable execs)    To choose another
seed for random generator use    \S seed

Result is given as a squence of two ints, so there is a final i-suffix at second value
27421 12133i  -> read as (27241, 12133)

Time not counting interpreter startup. \t sentence    mesures time
consumed by that sentence

Body:
Q, 0.296 seg

n:6; iter:1000  /parametrization (constants)
c:n#0           /auxiliar constant (sequence 0 0.. 0 (n))
A:B:();         /A and B accumulates results of inner product (firstresult, secondresult)

/S=sequence with all arrays of length n+1 with values -1 and 1
S:+(2**m)#/:{,/x#/:-1 1}'m:|n(2*)\1

f:{do[iter; F:c; while[F~c; F:n?-1 0 0 1]; A,:+/F*-1_x; B,:+/F*1_x];} /hard work
f'S               /map(S,f)
N:~A; +/'(N;N&~B) / ~A is not A (or A=0) ->bitmap.  +/ is sum (population over a bitmap)
                  / +/'(N;N&~B) = count firstResult=0, count firstResult=0 and secondResult=0

Q is a collection oriented language (kx.com)

Code rewrited to explote idiomatic Q, but no other clever optimizations

Scripting languages optimize programmer time, not execution time

Q is not the best tool for this problem

First coding attempt = not a winner, but reasonable time (approx. 30x speedup)

quite competitive among interpreters

stop and choose another problem

NOTES.-

program uses default seed (repeteable execs)    To choose another
seed for random generator use    \S seed

Result is given as a squence of two ints, so there is a final i-suffix at second value
27421 12133i  -> read as (27241, 12133)

Time not counting interpreter startup. \t sentence    mesures time
consumed by that sentence


问:
Get the most dominant color!
In this challenge, your task is to write a program that takes in an image and returns the most dominant color in it. Dominant color here means the color with which most of the image is covered (see the test cases for a better understanding).

Input

An image's path. You'll have to load that image in your program. You can take the input as STDIN, function argument or whatever suits your language. You may assume that the image will have only .png extension.

Output

The most dominant color in any format. (But it should be accurate, you can't return Red for #f88379). The type of output depends on you. If there is an equal distribution of colors in the image or there are more than one dominant color, then your program should return "Equal". You can show the output by printing on screen, logging on command line or console, or whatever suits you.

Test Cases

=> Red/#ff0000/rgba(255,0,0)

.

=> "Equal"

=> White (or the same color in any other format)

In these test cases, I have posted images rather than image paths, but you'll be given image paths only as input.

Note If your language contains a built-in for this, then you must NOT use it. Please add a screenshot or a link to a screenshot to prove that your program works.

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

答:
Pyth, 18 bytes

FGITW.

```<code>?tJeM.MhZrS'Q8\=hJ
</code>```

This is how it would theoretically work offline.

This is a proof that it works.

The two links differ by whether there is a "read file command" ' (single-quote).

Title: Get the most dominant color!

Body:
Pyth, 18 bytes

FGITW.

?tJeM.MhZrS'Q8\=hJ

This is how it would theoretically work offline.

This is a proof that it works.

The two links differ by whether there is a "read file command" ' (single-quote).


问:
Count up folks!

Introduction

It may sound strange, but we haven't got ONE challenge for counting from 1 to n, inclusive.

This is not the same thing. That one is a (closed) not well-explained challenge.

This is not the same thing. That one is about counting up indefinitely.

Challenge

Write a program or function that prints every integer from 1 to n inclusive.

Rules

You can get n any way.

You can assume that n will always be a positive integer.

You can get n in any base, but you should always output in decimal.

Output must be separated by any character (or pattern) not in 0123456789. Non-decimal leading or trailing characters are allowed (for example when using arrays such as [1, 2, 3, 4, 5, 6]).

Standard loopholes are denied.

We want to find the shortest approach in each language, not the shortest language, so I will not accept any answer.

You must update your answer(s) after this edit, answers posted before the last edit must comply with the change rule about standard loopholes (I didn't want to deny them, but I didn't want to make the community roar, so I denied them).

You can use any post-dating language version (or language). You cannot use any language or language version made just for this challenge.

Bonuses

20%

Your program must be able to count at least up to 18446744073709551615 (2^64-1). For example, if a new datatype is the only way to support big integers, you must construct it. If your language does not have any way to support huge integers up to 2^64-1, the upper limit of that particular language must be supported instead.

EDIT: I've changed the limit from 2^64 to 2^64-1 to allow more answers.

EDIT: I made the 2^64-1 rule a bonus, since there has not been much interest in this challenge. If your answer supports 2^64-1, you can now edit it to include the bonus. Also, you can post an answer not supporting it, if it is shorter.

答:
Tellurium, 6 bytes

```<code>[I|+^]
</code>```

This code runs a loop for an amount of times specified by the user (I). + adds one to the cell's value and ^ outputs the value.

Title: Count up folks!

Body:
Tellurium, 6 bytes

[I|+^]

This code runs a loop for an amount of times specified by the user (I). + adds one to the cell's value and ^ outputs the value.


问:
Toggle a string

The challenge involve simply toggling a string within another string.

Explanation

If the toggle string is a substring of the main string, remove all instances of the toggle string from the main string; otherwise, append the toggle string at the end of the main string.

Rules

All string are composed of printable ASCII characters

The function should take two parameters: the main string and the toggle string.

The main string can be empty.

The toggle string cannot be empty.

The result should be a string, which can be empty.

The shortest answer wins.

Examples

```<code>function toggle(main_string, toggle_string){ ... }

toggle('this string has 6 words ', 'now')
=> 'this string has 6 words now'

toggle('this string has 5 words now', ' now')
=> 'this string has 5 words'
</code>```

Tests cases

```<code>'','a'          => 'a'
'a','a'         => ''

'b','a'         => 'ba'
'ab','a'        => 'b'

'aba','a'       => 'b'
'ababa', 'aba'  => 'ba'
</code>```

答:
k (23 bytes)

```<code>{$[#x ss y;,/y\:x;x,y]}
</code>```

Examples:

```<code>k){$[#x ss y;,/y\:x;x,y]}["aba";"a"]
,"b"
k){$[#x ss y;,/y\:x;x,y]}["this string has 6 words ";"now"]
"this string has 6 words now"
k){$[#x ss y;,/y\:x;x,y]}["this string has 5 words now";"now"]
"this string has 5 words "
k){$[#x ss y;,/y\:x;x,y]}["ababa";"ba"]
,"a"
k){$[#x ss y;,/y\:x;x,y]}["";"a"]
,"a"
</code>```

Title: Toggle a string

Body:
k (23 bytes)

{$[#x ss y;,/y\:x;x,y]}

Examples:

k){$[#x ss y;,/y\:x;x,y]}["aba";"a"]
,"b"
k){$[#x ss y;,/y\:x;x,y]}["this string has 6 words ";"now"]
"this string has 6 words now"
k){$[#x ss y;,/y\:x;x,y]}["this string has 5 words now";"now"]
"this string has 5 words "
k){$[#x ss y;,/y\:x;x,y]}["ababa";"ba"]
,"a"
k){$[#x ss y;,/y\:x;x,y]}["";"a"]
,"a"


问:
Define a function f such that f(f(n)) = -n for all non-zero integers n

This challenge was inspired by a programming blog I frequent. Please see the original post here: A Programming Puzzle

Challenge

Define a function \$f:\mathbb{Q}\to\mathbb{Q}\$ such that \$f(f(n)) = -n\$ for all non-zero integers \$n\$, and where \$\mathbb{Q}\$ is the set of rational numbers.

Details

In whatever language you prefer, please define one function or program \$f\$ that accepts as parameter one number \$n\$ and returns or outputs one number \$f(n)\$.

Input may be provided through whichever mechanism is most natural for your language: function argument, read from STDIN, command-line argument, stack position, voice input, gang signs, etc.

Output should be a return value from a function/program or printed to STDOUT.

I would like to restrict answers to functions that do not take advantage of program state or global memory/data that is visible from outside of the function \$f\$. For example, keeping a counter outside of \$f\$ that counts how many times \$f\$ was called and just doing a negation based on this count isn't very challenging or interesting for anyone. The decisions \$f\$ makes should rely only on data within \$f\$'s lexical scope.

However, this restriction is probably inappropriate for some stack-oriented languages or other types of languages that do not distinguish these types of data or scopes. Please use your best judgement to keep with the spirit of this challenge.

Scoring

Standard code golf rules apply - your score is the number of bytes in your source code.

The minimal answer requires the domain and codomain of \$f\$ to be a subset of the rationals \$\mathbb{Q}\$. If you restrict your domain and codomain of \$f\$ to the integers \$\mathbb{Z}\$, then your score is the ceiling of 90% of the number of bytes in your source code.

Tiebreak

In the event of a tie, the following will be used in order:

Fewest number of printable non-whitespace symbols in your source code

Earliest date and time of answer submission

You are not required to support arbitrarily sized numbers. Please interpret the sets \$\mathbb{Z}\$ and \$\mathbb{Q}\$ as datatypes in your chosen language (typically integer and floating point, respectively).

If your solution relies entirely on the underlying structure or bit pattern of a data type, please describe its limitations and how it is being used.

答:
Julia, 21

```<code>f(x)=(1-2(1>x>-1))/2x
</code>```

Then

```<code>julia> f(f(12//1))
-12//1
</code>```

p//q is julia's literal notation of rational numbers.

Body:
Julia, 21

f(x)=(1-2(1>x>-1))/2x

Then

julia> f(f(12//1))
-12//1

p//q is julia's literal notation of rational numbers.


答:
J, 36 - 26 = 10 bytes

```<code>'golfabcdehjkmnpqrstvwxyz']u:97+i.26
</code>```

Not a comment, just a string that's discarded. u: converts numbers to ASCII chars, and 97+i.26 is a range from 0..25 with vectorized addition over 97, the char code of a. Here's an alternative (albeit longer) solution using a.:

```<code>'golfbcdehjkmnpqrstvwxyz']a.{~97+i.26
</code>```

Title: Output the alphabet using the alphabet

Body:
The title is pretty self-explanatory, isn't it?

Your task is to output the alphabet (the string "abcdefghijklmnopqrstuvwxyz") to STDOUT, using each and every letter of the alphabet in your program once and only once.

Oh, and for a bit of extra fun?

The letters "g", "o", "l" and "f" must be in order (just for the code to be a bit more code-y).

Rules:

Only standard letters of the alphabet from ASCII count as letters (ë != e).

Both uppercase and lowercase characters count as letters (if you have E, you are not allowed to have e).

You are allowed to use comments, but every character in the comment is equal to 2 bytes.

Your final score will be the byte-count of your program, subtracted by 26.

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

Body:
J, 36 - 26 = 10 bytes

'golfabcdehjkmnpqrstvwxyz']u:97+i.26

Not a comment, just a string that's discarded. u: converts numbers to ASCII chars, and 97+i.26 is a range from 0..25 with vectorized addition over 97, the char code of a. Here's an alternative (albeit longer) solution using a.:

'golfbcdehjkmnpqrstvwxyz']a.{~97+i.26


答:
Pyth - 42 bytes

Complete brute force. Surprisingly fast, finishes all possible the test cases in seconds. Will run forever with impossible inputs.

```<code>Acczd]2.VZIJf.Amqhedehd,VTtTm++hGdeG^HbhJB
</code>```

Test Suite.

Title: Chaining Words Together

Body:
Given two words and a list as input, your program must (in as few characters as possible, of course) find the shortest way to "chain" the first word to the last using the ones in the list. Two words are "chained" if their first and last letters are the same, e.g. "Food" and "Door".

Your program will take input as a string with words separated by spaces, and output a list (in whatever format is most convenient: string, array/list type, etc) of the completed chain.

Examples:

Input: joke corn tan disc need eat

Output: joke eat tan need disc corn

The first two words in the input list are the first and last words in the chain, and the rest are the constituent words.

Input: best fry easy elf mean tame yam nice

Output: best tame elf fry

NOT: best tame easy yam mean nice elf fry

Input: rug gunned orange purple gains pore soup emo ending

Output: rug gunned

Input: %3gioxl? 6699-4 !f!!&+ ?4; ;78! +6

Output: %3gioxl? ?4; ;78! !f!!&+ +6 6699-4

The "words" don't have to be real words; for the purpose of the challenge, any ASCII character except the space will count as part of a word.

Input: mouth rich frame inspire item sold

Output when the first and last word are impossible to chain is undefined, so handle it however's shortest.

Body:
Pyth - 42 bytes

Complete brute force. Surprisingly fast, finishes all possible the test cases in seconds. Will run forever with impossible inputs.

Acczd]2.VZIJf.Amqhedehd,VTtTm++hGdeG^HbhJB

Test Suite.


问:
Print the nth prime that contains n
This question will be a twist on finding the nth prime number.

Challenge

You must write a program that will take one input n, and output the nth prime number whose decimal representation contains the decimal representation of n as a subtring.

Confused? Here are some examples.

```<code>n=1
Primes: 2, 3, 5, 7, 11
                    ^1 first prime that contains a 1
Output: 11

n=2
Primes: 2, 3, 5, 7, 11, 13, 17, 19, 23
        ^1                          ^2 second prime that contains a 2
Output: 23

n=3
Primes: 2, 3, 5, 7, 11, 13, 17, 19, 23
           ^1           ^2          ^3 third prime that contains a 3
Output: 23

n=10
Primes: 2, 3, 5, 7, 11, ..., 97, 101, 103, 107, 109, ..., 997, 1009, 1013, 1019, 1021, 1031, 1033
                                 ^1   ^2   ^3   ^4             ^5    ^6    ^7    ^8    ^9    ^10 tenth prime that contains a 10
Output: 1033
</code>```

This is code-golf, so lowest byte count wins.

If something is confusing, please leave a comment.

答:
Pyth - 11 bytes

```<code>e.f&P_Z}`Q`
</code>```

Test Suite.

Title: Print the nth prime that contains n

Body:
Pyth - 11 bytes

e.f&P_Z}`Q`

Test Suite.


答:
MATL, 18 bytes

```<code>`@YqVGVXf?3M]NG<]&
</code>```

Try it online!

Explanation

This generates primes in order using a do...while loop. For each prime, the condition is tested (and the prime is consumed). If satisfied, that prime is pushed to the stack again. The number of elements in the stack is used as count of how many qualifying primes we have found. When there are enough of them, the last one is displayed.

```<code>`         % Do...while
  @       %   Push iteration index, k. Starts at 1
  YqV     %   k-th prime. Convert to string
  GV      %   Push input, n. Convert to string
  Xf      %   Find string within another
  ?       %   If non-empty
    3M    %     Push k-th prime again (increase stack size by 1)
  ]       %   End if
  NG<     %   Is stack size less than input number? If so proceeed with
          %   a new iteration; else exit do...while loop
]         % End do...while
&         % Implicitly display only top number in the stack
</code>```

Title: Print the nth prime that contains n

Body:
This question will be a twist on finding the nth prime number.

Challenge

You must write a program that will take one input n, and output the nth prime number whose decimal representation contains the decimal representation of n as a subtring.

Confused? Here are some examples.

```<code>n=1
Primes: 2, 3, 5, 7, 11
                    ^1 first prime that contains a 1
Output: 11

n=2
Primes: 2, 3, 5, 7, 11, 13, 17, 19, 23
        ^1                          ^2 second prime that contains a 2
Output: 23

n=3
Primes: 2, 3, 5, 7, 11, 13, 17, 19, 23
           ^1           ^2          ^3 third prime that contains a 3
Output: 23

n=10
Primes: 2, 3, 5, 7, 11, ..., 97, 101, 103, 107, 109, ..., 997, 1009, 1013, 1019, 1021, 1031, 1033
                                 ^1   ^2   ^3   ^4             ^5    ^6    ^7    ^8    ^9    ^10 tenth prime that contains a 10
Output: 1033
</code>```

This is code-golf, so lowest byte count wins.

If something is confusing, please leave a comment.

Body:
MATL, 18 bytes

`@YqVGVXf?3M]NG<]&

Try it online!

Explanation

This generates primes in order using a do...while loop. For each prime, the condition is tested (and the prime is consumed). If satisfied, that prime is pushed to the stack again. The number of elements in the stack is used as count of how many qualifying primes we have found. When there are enough of them, the last one is displayed.

`         % Do...while
  @       %   Push iteration index, k. Starts at 1
  YqV     %   k-th prime. Convert to string
  GV      %   Push input, n. Convert to string
  Xf      %   Find string within another
  ?       %   If non-empty
    3M    %     Push k-th prime again (increase stack size by 1)
  ]       %   End if
  NG<     %   Is stack size less than input number? If so proceeed with
          %   a new iteration; else exit do...while loop
]         % End do...while
&         % Implicitly display only top number in the stack


答:
Ruby, <s>62</s> 61 bytes

->i{Prime.lazy.map(&:to_s).grep(/#{i}/).first(i)[-1]}
```

<p>Requires the <code>-rprime</code> flag (+8 bytes).</p>

<pre class="lang-ruby prettyprint-override"><code>->i{            # lambda with one argument
Prime           # iterator over all primes
.lazy           # make the iterator lazy (can't evaluate infinite primes)
.map(&:x.to_s)  # convert the primes to strings
.grep(/#{i}/)   # find primes that regex match on the input (contain it)
.first(i)       # take the first (input) primes that satisfy this
[-1]            # take the last of those
}
</code>```

Title: Print the nth prime that contains n

Body:
Ruby, <s>62</s> 61 bytes

->i{Prime.lazy.map(&:to_s).grep(/#{i}/).first(i)[-1]}

Requires the -rprime flag (+8 bytes).

->i{            # lambda with one argument
Prime           # iterator over all primes
.lazy           # make the iterator lazy (can't evaluate infinite primes)
.map(&:x.to_s)  # convert the primes to strings
.grep(/#{i}/)   # find primes that regex match on the input (contain it)
.first(i)       # take the first (input) primes that satisfy this
[-1]            # take the last of those
}


答:
Pyke, 15 bytes

```<code>Q.fD_P.I`Q`R{(e
</code>```

Try it here!

Title: Print the nth prime that contains n

Body:
Pyke, 15 bytes

Q.fD_P.I`Q`R{(e

Try it here!


答:
Bash, 27 bytes

```<code>primes 0|grep $1|sed $1q\;d
</code>```

primes comes from bsdgames.

Takes input as a command line argument, and outputs on STDOUT.

Title: Print the nth prime that contains n

Body:
Bash, 27 bytes

primes 0|grep $1|sed $1q\;d

primes comes from bsdgames.

Takes input as a command line argument, and outputs on STDOUT.


答:
Jelly, 13 bytes

```<code>×ÆP,³Dœṣ/Ṗµ#Ṫ
</code>```

Try it online!

Title: Print the nth prime that contains n

Body:
Jelly, 13 bytes

×ÆP,³Dœṣ/Ṗµ#Ṫ

Try it online!


答:
05AB1E, 8 bytes

Code:

```<code>µN¹åNp*½
</code>```

Explanation:

```<code>µ          # Run this until the counting variable has reached the input value.
 N¹å       # Check if the input number is in the range variable.
    Np     # Check if the range variable is prime.
      *    # Multiply those two numbers (which is basically an AND operator).
       ½   # If true, increment the counting variable.
           # After the loop, the stack is empty and implicitly prints N.
</code>```

Uses CP-1252 encoding. Try it online!.

Title: Print the nth prime that contains n

Body:
05AB1E, 8 bytes

Code:

µN¹åNp*½

Explanation:

µ          # Run this until the counting variable has reached the input value.
 N¹å       # Check if the input number is in the range variable.
    Np     # Check if the range variable is prime.
      *    # Multiply those two numbers (which is basically an AND operator).
       ½   # If true, increment the counting variable.
           # After the loop, the stack is empty and implicitly prints N.

Uses CP-1252 encoding. Try it online!.


答:
Python 2, <s>67</s> <s>65</s> 62 bytes

f=lambda n,k=0,m=2,p=1:k/n or-~f(n,k+p%m*(`n`in`m`),m+1,p*m*m)
```

Test it on Ideone.

How it works

We use a corollary of Wilson's theorem:

At all times, the variable p is equal to the square of the factorial of m - 1.

If k < n, k/n will yield 0 and f is called recursively. m is incremented, p is updated, and k is incremented if and only if m is a prime that contains n.

The latter is achieved by adding the result of p%m*(`n`in`m`) to k. By the corollary of Wilson's theorem if m is prime, p%m returns 1, and if not, it returns 0.

Once k reaches n, we found q, the nth prime that contains n.

We're in the next call during the check, so m = q + 1. k/n will return 1, and the bitwise operators -~ will increment that number once for every function call. Since it takes q - 1 calls to f to increment m from 2 to q + 1, the outmost call to f will return 1 + q - 1 = q, as intended.

Title: Print the nth prime that contains n

Body:
Python 2, <s>67</s> <s>65</s> 62 bytes

f=lambda n,k=0,m=2,p=1:k/n or-~f(n,k+p%m*(`n`in`m`),m+1,p*m*m)

Test it on Ideone.

How it works

We use a corollary of Wilson's theorem:

At all times, the variable p is equal to the square of the factorial of m - 1.

If k < n, k/n will yield 0 and f is called recursively. m is incremented, p is updated, and k is incremented if and only if m is a prime that contains n.

The latter is achieved by adding the result of p%m*(`n`in`m`) to k. By the corollary of Wilson's theorem if m is prime, p%m returns 1, and if not, it returns 0.

Once k reaches n, we found q, the nth prime that contains n.

We're in the next call during the check, so m = q + 1. k/n will return 1, and the bitwise operators -~ will increment that number once for every function call. Since it takes q - 1 calls to f to increment m from 2 to q + 1, the outmost call to f will return 1 + q - 1 = q, as intended.


答:
Mathematica, 75 bytes

```<code>Nest[NestWhile[b=NextPrime,b@#,!StringContainsQ@@ToString/@{#,a}&]&,1,a=#]&
</code>```

May still be golfable.

Title: Print the nth prime that contains n

Body:
Mathematica, 75 bytes

Nest[NestWhile[b=NextPrime,b@#,!StringContainsQ@@ToString/@{#,a}&]&,1,a=#]&

May still be golfable.


答:
C# (58 bytes)

string F(string s,string t)=>s==(s=s.Replace(t,""))?s+t:s;

It uses an inline assignment to shave a few bytes off

Title: Toggle a string

Body:
The challenge involve simply toggling a string within another string.

Explanation

If the toggle string is a substring of the main string, remove all instances of the toggle string from the main string; otherwise, append the toggle string at the end of the main string.

Rules

All string are composed of printable ASCII characters

The function should take two parameters: the main string and the toggle string.

The main string can be empty.

The toggle string cannot be empty.

The result should be a string, which can be empty.

The shortest answer wins.

Examples

```<code>function toggle(main_string, toggle_string){ ... }

toggle('this string has 6 words ', 'now')
=> 'this string has 6 words now'

toggle('this string has 5 words now', ' now')
=> 'this string has 5 words'
</code>```

Tests cases

```<code>'','a'          => 'a'
'a','a'         => ''

'b','a'         => 'ba'
'ab','a'        => 'b'

'aba','a'       => 'b'
'ababa', 'aba'  => 'ba'
</code>```


问:
Hi, can you draw some odd art? Bye!
Create a program that outputs "Hi, Hello!" in k bytes. By altering n bytes, the code should output all odd numbers in the range 5 <= x <= 25.
Changing another m bytes should result in a code that prints the following frame in ASCII-art:

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

Change another o bytes, and print Hello, bye!.

m, n and o are calculated in Levenshtein distance (cumulative). n is the distance from the first to the second code. m is the distance between the second and third and so on.

The score of your submission will be 0.5*k + n + m + o.

As an example:

```<code>The code that prints `Hi, Hello!` is 30 bytes.              15
Add two bytes and remove one and print the odd numbers     + 3
Alter three bytes in place, and add one to print the box   + 4
Remove four bytes and print `Hello, bye!`                  + 4
Total score:                                                26
</code>```

Rules

All codes must be in the same language

You have to follow the given order (i.e. the first code prints Hi, Hello, the second prints the numbers etc.)

The strings and ASCII-box must be exactly as specified. The list of digits can be on any suitable format

Title: Hi, can you draw some odd art? Bye!

Body:
Pyth - <s>49</s> <s>46</s> 44/2 + 1 + 1 + 1 = 25

Hello code:

h["Hi, Hello!":5lG2"+-+
| |
+-+""Hello, bye!

Odd numbers code:

ht["Hi, Hello!":5lG2"+-+
| |
+-+""Hello, bye!

Box code:

htt["Hi, Hello!":5lG2"+-+
| |
+-+""Hello, bye!

Bye Code:

httt["Hi, Hello!":5lG2"+-+
| |
+-+""Hello, bye!