问:
End the tabs versus space war

End the tabs versus space war

So, there has been a great deal of debate of whether to use tabs or spaces to indent/format code. Can you help the university settle the dispute, by going to an incredibly <s>crazy</s> unique method of formatting.

Your job is to write a full program or function which expands all tabs into four spaces. And then replaces a run of n leading spaces with "/(n - two stars here)/". You will receive input over multiple lines in any reasonable format (single string array of strings for each new line. Columnar array etc.)

Sample input shamelessly stolen. Note that since tabs get automagically expanded to four spaces on SE I represent it as the "^" character, but you must handle tabs (codepoint 0x09) as well. All "^" characters represent a tabulation.

```<code>Calculate the value 256 and test if it's zero
If the interpreter errors on overflow this is where it'll happen
++++++++[>++++++++<-]>[<++++>-]
+<[>-<
    Not zero so multiply by 256 again to get 65536
    [>++++<-]>[<++++++++>-]<[>++++++++<-]
    +>[>
        # Print "32"
        ++++++++++[>+++++<-]>+.-.[-]<
    <[-]<->] <[>>
        # Print "16"
        +++++++[>+++++++<-]>.+++++.[-]<
<<-]] >[>
    # Print "8"
    ++++++++[>+++++++<-]>.[-]<
<-]<
# Print " bit cells\n"
+++++++++++[>+++>+++++++++>+++++++++>+<<<<-]>-.>-.+++++++.+++++++++++.<.
>>.++.+++++++..<-.>>-
Clean up used cells.
[[-]<]l
^this is preceded by a tab
^^two tabs
^^^three tabs etcetera!
</code>```

Sample output

```<code>Calculate the value 256 and test if it's zero
If the interpreter errors on overflow this is where it'll happen
++++++++[>++++++++<-]>[<++++>-]
+<[>-<
/**/Not zero so multiply by 256 again to get 65536
/**/[>++++<-]>[<++++++++>-]<[>++++++++<-]
/**/+>[>
/******/# Print "32"
/******/++++++++++[>+++++<-]>+.-.[-]<
/**/<[-]<->] <[>>
/******/# Print "16"
/******/+++++++[>+++++++<-]>.+++++.[-]<
<<-]] >[>
/**/# Print "8"
/**/++++++++[>+++++++<-]>.[-]<
<-]<
# Print " bit cells\n"
+++++++++++[>+++>+++++++++>+++++++++>+<<<<-]>-.>-.+++++++.+++++++++++.<.
>>.++.+++++++..<-.>>-
Clean up used cells.
[[-]<]l
/**/this is preceded by a tab
/******/two tabs
/**********/three tabs etcetera!
</code>```

Because the university needs space to download both Vim and Emacs, you are allowed very little storage for your code. Therefore this is code-golf and the shortest code wins. You may assume that input is well formed and lines with less than four spaces (after replacement of tabs) may result in undefined behavior.

Disclaimer

This "excellent" formatting strategy came courtesy of Geobits, and is reproduced with his permission. No programmers were harmed during the production of this challenge.

答:
The university should consider allowing a bit more space for programs in Emacs Lisp (or default to tabify and untabify alone), as they get even more verbose than Java. It should also pay close attention to students (or teachers) whose identation size is smaller than four or who happen to code in some non-C-like language.

The following solution has 206 bytes

```<code>(lambda (b e)(let((tab-width 4))(untabify b e)(goto-char b)(while(re-search-forward"^ +"e t)(replace-match(format"/%s/"(apply'concat(mapcar(lambda(x)"*")(number-sequence 1(-(length(match-string 0))2)))))))))
</code>```

Assuming that tab-width needs not to be explicitly set, we can save 20 of them.

```<code>(lambda(b e)(untabify b e)(goto-char b)(while(re-search-forward"^ +"e t)(replace-match(format"/%s/"(apply'concat(mapcar(lambda(x)"*")(number-sequence 1(-(length(match-string 0))2))))))))
</code>```

And ungolfed version would look like this

```<code>(defun end-tab-war (beg end)
  (let ((tab-width 4))
    (untabify beg end)
    (goto-char beg)
    (while (re-search-forward "^ +" end t)
      (replace-match
       (format
        "/%s/"
        (apply 'concat
               (mapcar (lambda(x) "*")
                       (number-sequence 1
                                        (- (length (match-string 0))
                                           2)))))))))
</code>```

We first untabify the region before jumping to its start. Then, while we see whitespace at the beginning of a line, we replace it with a comment that is as long as said whitespace. To be exact, the comment to be inserted is constructed by

```<code> (format"/%s/"(apply'concat(mapcar(lambda(x)"*")(number-sequence 1(-(length(match-string 0))2)))))
</code>```

which itself takes up 97 bytes. A shorter solution to copy some string n times is highly appreciated.

Title: End the tabs versus space war

Body:
The university should consider allowing a bit more space for programs in Emacs Lisp (or default to tabify and untabify alone), as they get even more verbose than Java. It should also pay close attention to students (or teachers) whose identation size is smaller than four or who happen to code in some non-C-like language.

The following solution has 206 bytes

(lambda (b e)(let((tab-width 4))(untabify b e)(goto-char b)(while(re-search-forward"^ +"e t)(replace-match(format"/%s/"(apply'concat(mapcar(lambda(x)"*")(number-sequence 1(-(length(match-string 0))2)))))))))

Assuming that tab-width needs not to be explicitly set, we can save 20 of them.

(lambda(b e)(untabify b e)(goto-char b)(while(re-search-forward"^ +"e t)(replace-match(format"/%s/"(apply'concat(mapcar(lambda(x)"*")(number-sequence 1(-(length(match-string 0))2))))))))

And ungolfed version would look like this

(defun end-tab-war (beg end)
  (let ((tab-width 4))
    (untabify beg end)
    (goto-char beg)
    (while (re-search-forward "^ +" end t)
      (replace-match
       (format
        "/%s/"
        (apply 'concat
               (mapcar (lambda(x) "*")
                       (number-sequence 1
                                        (- (length (match-string 0))
                                           2)))))))))

We first untabify the region before jumping to its start. Then, while we see whitespace at the beginning of a line, we replace it with a comment that is as long as said whitespace. To be exact, the comment to be inserted is constructed by

 (format"/%s/"(apply'concat(mapcar(lambda(x)"*")(number-sequence 1(-(length(match-string 0))2)))))

which itself takes up 97 bytes. A shorter solution to copy some string n times is highly appreciated.


问:
Is it a leap year?
This challenge is quite simple. You will take an input which will be a year from 1801 to 2400, and output if it is a leap year or not.

Your input will have no newlines or trailing spaces:

```<code>1954
</code>```

You will output in any way that you like that clearly tells the user if it is or isn't a leap year (I will accept y or n for yes/no)

You can get a list of leap years here: http://kalender-365.de/leap-years.php
I would note that leap years are not ever four years always. 1896 is a leap year, but 1900 is not. The years that follow this "skip" are:

```<code>1900
2100
2200
2300
</code>```

Test cases:

```<code>1936 ->  y
1805 ->  n
1900 ->  n
2272 ->  y
2400 ->  y
</code>```

EDIT: This is based on a standard Gregorian calendar: http://www.epochconverter.com/date-and-time/daynumbers-by-year.php

The Catalogue

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

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

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

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

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

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

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

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

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

/* Configuration */

var QUESTION_ID = 50798; // 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 = 8478; // 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,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\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,
      });
    else console.log(body);
  });

  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;
    lang = jQuery(''+lang+'').text();

    languages[lang] = languages[lang] || {lang: a.language, lang_raw: lang, user: a.user, size: a.size, link: a.link};
  });

  var langs = [];
  for (var lang in languages)
    if (languages.hasOwnProperty(lang))
      langs.push(languages[lang]);

  langs.sort(function (a, b) {
    if (a.lang_raw.toLowerCase() > b.lang_raw.toLowerCase()) return 1;
    if (a.lang_raw.toLowerCase() < b.lang_raw.toLowerCase()) 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;
  display: block !important;
}

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

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

table thead {
  font-weight: bold;
}

table td {
  padding: 5px;
}</code>```

<link rel="stylesheet" type="text/css" href="https://cdn.sstatic.net/Sites/codegolf/all.css?v=ffb5d0584c5f">

Shortest Solution by Language

Language	User	Score

Leaderboard

	Author	Language	Size

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

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

```

答:
C#, 23 bytes

```<code>y=>y%25<1?y%16<1:y%4<1;
</code>```

Try it online!

Full source, including test cases:

```<code>using System;

namespace CountingLeapYears
{
    class Program
    {
        static void Main(string[] args)
        {
            Func<int,bool>s=y=>y%25<1?y%16<1:y%4<1;
            Console.WriteLine(s(1936)); //y
            Console.WriteLine(s(1805)); //n
            Console.WriteLine(s(1900)); //n
            Console.WriteLine(s(2272)); //y
            Console.WriteLine(s(2400)); //y
        }
    }
}
</code>```

ContentLicense: CC BY-SA 4.0

Title: Is it a leap year?

Body:
C#, 23 bytes

y=>y%25<1?y%16<1:y%4<1;

Try it online!

Full source, including test cases:

using System;

namespace CountingLeapYears
{
    class Program
    {
        static void Main(string[] args)
        {
            Func<int,bool>s=y=>y%25<1?y%16<1:y%4<1;
            Console.WriteLine(s(1936)); //y
            Console.WriteLine(s(1805)); //n
            Console.WriteLine(s(1900)); //n
            Console.WriteLine(s(2272)); //y
            Console.WriteLine(s(2400)); //y
        }
    }
}

ContentLicense: CC BY-SA 3.0


问:
Roll the Alphabet into a Spiral
Write a program or function that, when given n, will print a spiral n characters long made up of the Latin alphabet ABCDEFGHIJKLMNOPQRSTUVWXYZ repeated as needed. This spiral should run through the alphabet only forwards.

Related to Alphabet Spiral, though the spiral runs through the alphabet forwards and backwards, and the spiral is constant.

Test cases

```<code>4   AB
    DC

40   UVWXYZ
     TGHIJA
    NSFABKB
    MREDCLC
    LQPONMD
    KJIHGFE

0

10  GHIJ
    FAB
    EDC

1000    UVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ
        TGHIJKLMNOPQRSTUVWXYZABCDEFGHIJA
        SFABCDEFGHIJKLMNOPQRSTUVWXYZABKB
        REZCDEFGHIJKLMNOPQRSTUVWXYZABCLC
        QDYBMNOPQRSTUVWXYZABCDEFGHIJCDMD
        PCXALEFGHIJKLMNOPQRSTUVWXYZKDENE
        OBWZKDEFGHIJKLMNOPQRSTUVWXALEFOF
        NAVYJCDMNOPQRSTUVWXYZABCDYBMFGPG
        MZUXIBCLCDEFGHIJKLMNOPQREZCNGHQH
        LYTWHABKBABCDEFGHIJKLMNSFADOHIRI
        KXSVGZAJAZGHIJKLMNOPQROTGBEPIJSJ
        JWRUFYZIZYFUVWXYZABCDSPUHCFQJKTK
        IVQTEXYHYXETQRSTUVWXETQVIDGRKLUL
        HUPSDWXGXWDSPUVWXYZYFURWJEHSLMVM
        GTORCVWFWVCROTGHIJAZGVSXKFITMNWN
        FSNQBUVEVUBQNSFABKBAHWTYLGJUNOXO
        ERMPATUDUTAPMREDCLCBIXUZMHKVOPYP
        DQLOZSTCTSZOLQPONMDCJYVANILWPQZQ
        CPKNYRSBSRYNKJIHGFEDKZWBOJMXQRAR
        BOJMXQRARQXMLKJIHGFELAXCPKNYRSBS
        ANILWPQZQPWVUTSRQPONMBYDQLOZSTCT
        ZMHKVOPYPONMLKJIHGFEDCZERMPATUDU
        YLGJUNOXONMLKJIHGFEDCBAFSNQBUVEV
        XKFITMNWVUTSRQPONMLKJIHGTORCVWFW
        WJEHSLMLKJIHGFEDCBAZYXWVUPSDWXGX
        VIDGRKJIHGFEDCBAZYXWVUTSRQTEXYHY
        UHCFQPONMLKJIHGFEDCBAZYXWVUFYZIZ
        TGBEDCBAZYXWVUTSRQPONMLKJIHGZAJA
        SFAZYXWVUTSRQPONMLKJIHGFEDCBABKB
        REDCBAZYXWVUTSRQPONMLKJIHGFEDCLC
        QPONMLKJIHGFEDCBAZYXWVUTSRQPONMD
                                LKJIHGFE
</code>```

Rules

Your input will be a non-negative integer 0 <= n <= 1000, but your code should theoretically handle any non-negative integer.

Your output format may be in any sane format, with delimiters if necessary.

Rotations and reflections are equivalent.

Your alphabet may be uppercase or lowercase.

The empty spaces in your spiral may be filled in with whatever non-alphabetic nulls you see fit.

The spiral itself may be in any shape you see fit. Rectangular spirals work best with ASCII solutions, but graphical solutions may be shorter with circular spirals.

Leading and trailing spaces and newlines are allowed.

This is code golf. The shortest answer in bytes (or equivalent) wins.

As always, if anything is unclear or incorrect, please let me know in the comments. Good luck and good golfing!

答:
TSQL, <s>386</s> <s>362</s> <s>358</s> 306 bytes

Please note that TSQL doesn't have a way to rotate text. This script is starting from A and calculating which direction the next letter should be placed. (right, down, left, left, left, up, up, right...)

The script can handle a maximum of 7744 letters.

Golfed:

```<code>DECLARE @z INT = 7744

DECLARE @ INT=2+SQRT(@z-1)DECLARE @o varchar(max)=REPLICATE(SPACE(@-1)+char(10),@-1);WITH C as(SELECT 0i,@/2a,@/2b UNION ALL SELECT i+1,a+z/2,b+z%2FROM(SELECT*,IIF(a>@/2*2-b,IIF(a<b,2,-1),IIF(a>b,-2,1))z FROM C)t WHERE i<@z-1)SELECT @o=STUFF(@o,@*a-@+b,1,char(i%26+65))FROM c OPTION(maxrecursion 0)PRINT @o
</code>```

Ungolfed:

```<code>DECLARE @z INT = 7744

DECLARE @ INT=2+SQRT(@z-1)
DECLARE @o varchar(max)=REPLICATE(SPACE(@-1)+char(10),@-1)

;WITH C as
(
  SELECT
    0i,@/2a,@/2b
  UNION ALL
  SELECT
    i+1,a+z/2,b+z%2
    FROM
      (SELECT*,
         IIF(a>@/2*2-b,
           IIF(a<b,2,-1),
             IIF(a>b,-2,1))z FROM C)t
  WHERE
    i<@z-1
)
SELECT
  @o=STUFF(@o,@*a-@+b,1,char(i%26+65))
FROM c
OPTION(maxrecursion 0)

PRINT @o
</code>```

Fiddle

Title: Roll the Alphabet into a Spiral

Body:
TSQL, <s>386</s> <s>362</s> <s>358</s> 306 bytes

Please note that TSQL doesn't have a way to rotate text. This script is starting from A and calculating which direction the next letter should be placed. (right, down, left, left, left, up, up, right...)

The script can handle a maximum of 7744 letters.

Golfed:

DECLARE @z INT = 7744

DECLARE @ INT=2+SQRT(@z-1)DECLARE @o varchar(max)=REPLICATE(SPACE(@-1)+char(10),@-1);WITH C as(SELECT 0i,@/2a,@/2b UNION ALL SELECT i+1,a+z/2,b+z%2FROM(SELECT*,IIF(a>@/2*2-b,IIF(a<b,2,-1),IIF(a>b,-2,1))z FROM C)t WHERE i<@z-1)SELECT @o=STUFF(@o,@*a-@+b,1,char(i%26+65))FROM c OPTION(maxrecursion 0)PRINT @o

Ungolfed:

DECLARE @z INT = 7744

DECLARE @ INT=2+SQRT(@z-1)
DECLARE @o varchar(max)=REPLICATE(SPACE(@-1)+char(10),@-1)

;WITH C as
(
  SELECT
    0i,@/2a,@/2b
  UNION ALL
  SELECT
    i+1,a+z/2,b+z%2
    FROM
      (SELECT*,
         IIF(a>@/2*2-b,
           IIF(a<b,2,-1),
             IIF(a>b,-2,1))z FROM C)t
  WHERE
    i<@z-1
)
SELECT
  @o=STUFF(@o,@*a-@+b,1,char(i%26+65))
FROM c
OPTION(maxrecursion 0)

PRINT @o

Fiddle


问:
Can you beat the British Intelligence? (Nonogram Solver)
It is time to embark on a perilous quest to defeat the British Intelligence. The aim of this challenge is to write the shortest code that will solve a Nonogram.

What is a Nonogram?

The rules are simple.
  You have a grid of squares, which must be either filled in black or left blank. Beside each row of the grid are listed the lengths of the runs of black squares on that row. Above each column are listed the lengths of the runs of black squares in that column. Your aim is to find all black squares. In this puzzle type, the numbers are a form of discrete tomography that measures how many unbroken lines of filled-in squares there are in any given row or column. For example, a clue of "4 8 3" would mean there are sets of four, eight, and three filled squares, in that order, with at least one blank square between successive groups.
   [1][2]

So the solution to the above Nonogram would be:

Implementation Details

You can chose to represent the Nonogram however you would like and take it as an input in whatever way you deem fit for your language. Same goes for output. The aim of this challenge is to literally just get the job done; if you can solve the nonogram with whatever output your program gives, that is valid. One caveat is you can't use an online solver :)

This problem is very algorithmically challenging (np-complete) in that there is no completely efficient solution to it and as such, you won't be penalized for not being able to solve larger ones, although your answer will be heavily rewarded if it is able to handle big cases (see bonus). As a benchmark, my solution works for up to roughly 25x25 within 5-10 seconds. To allow for flexibility amongst different languages, solutions that take less than 5 mins for a 25x25 nonogram are good enough.

You may assume a puzzle in always a square NxN nonogram.

You can use this online nonogram puzzle maker to test your solutions.

Scoring

You are, of course, free to use any language you want and since this is code golf, the entries will be sorted in the order: accuracy -> length of code -> speed. However, don't be discouraged by code golfing languages, answers in all languages that show attempts at golfing in an interesting way will be upvoted!

Bonus

I actually learnt about Nonograms from a cryptographic Christmas card released by the British Intelligence here. The first part was basically a massive 25x25 Nonogram. If your solution is able to solve this, you will get kudos :)

To make your life easier in terms of data entry, I have provided how I represented the data for this specific puzzle for your free use. The first 25 lines are the row clues, followed by a '-' separator line, followed by 25 lines of the col clues, followed by a '#' separator line, and then a representation of the grid with the square clues filled in.

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

And here is a slightly different version for your convenience; a comma separated tuple (row, col) where each element is list of lists.

```<code>([[7, 3, 1, 1, 7],
  [1, 1, 2, 2, 1, 1],
  [1, 3, 1, 3, 1, 1, 3, 1],
  [1, 3, 1, 1, 6, 1, 3, 1],
  [1, 3, 1, 5, 2, 1, 3, 1],
  [1, 1, 2, 1, 1],
  [7, 1, 1, 1, 1, 1, 7],
  [3, 3],
  [1, 2, 3, 1, 1, 3, 1, 1, 2],
  [1, 1, 3, 2, 1, 1],
  [4, 1, 4, 2, 1, 2],
  [1, 1, 1, 1, 1, 4, 1, 3],
  [2, 1, 1, 1, 2, 5],
  [3, 2, 2, 6, 3, 1],
  [1, 9, 1, 1, 2, 1],
  [2, 1, 2, 2, 3, 1],
  [3, 1, 1, 1, 1, 5, 1],
  [1, 2, 2, 5],
  [7, 1, 2, 1, 1, 1, 3],
  [1, 1, 2, 1, 2, 2, 1],
  [1, 3, 1, 4, 5, 1],
  [1, 3, 1, 3, 10, 2],
  [1, 3, 1, 1, 6, 6],
  [1, 1, 2, 1, 1, 2],
  [7, 2, 1, 2, 5]],
 [[7, 2, 1, 1, 7],
  [1, 1, 2, 2, 1, 1],
  [1, 3, 1, 3, 1, 3, 1, 3, 1],
  [1, 3, 1, 1, 5, 1, 3, 1],
  [1, 3, 1, 1, 4, 1, 3, 1],
  [1, 1, 1, 2, 1, 1],
  [7, 1, 1, 1, 1, 1, 7],
  [1, 1, 3],
  [2, 1, 2, 1, 8, 2, 1],
  [2, 2, 1, 2, 1, 1, 1, 2],
  [1, 7, 3, 2, 1],
  [1, 2, 3, 1, 1, 1, 1, 1],
  [4, 1, 1, 2, 6],
  [3, 3, 1, 1, 1, 3, 1],
  [1, 2, 5, 2, 2],
  [2, 2, 1, 1, 1, 1, 1, 2, 1],
  [1, 3, 3, 2, 1, 8, 1],
  [6, 2, 1],
  [7, 1, 4, 1, 1, 3],
  [1, 1, 1, 1, 4],
  [1, 3, 1, 3, 7, 1],
  [1, 3, 1, 1, 1, 2, 1, 1, 4],
  [1, 3, 1, 4, 3, 3],
  [1, 1, 2, 2, 2, 6, 1],
  [7, 1, 3, 2, 1, 1]])
</code>```

答:
Brachylog, <s>70</s> 69 bytes

```<code>[R:C]hlL~l:L:1f=.:3aR,.z:3aC,
tL,?he##ElL,E:2a
.<2,_1<
@b:4f:la
e.h1,
</code>```

This takes a list of two lists (first the rows indicators, then the column ones). Each indicator is itself a list (for situtions like [3,1] on one row).

This version takes about 3 minutes to solve the 5 by 5 example of the challenge.

Way more efficient version, 91 bytes

```<code>[R:C]hlL~l:L:1f:Cz:3az:Rz:3a=.:4aR,.z:4aC,
tL,?he##ElL,E:2a
.<2,_1<
:+a#=,?h
@b:5f:la
e.h1,
</code>```

Try it online!

This one is not complete brute force: the only difference is that this one imposes constraints on the values of cells such that the number of 1s in each row and column matches the numbers given as indicators in the input. The only brute force part is then in finding the one grid with those constraints for which the "blocks" of 1s match what is given as indication.

This one takes about 0.05 seconds on the 5 by 5 example of the challenge. This is still way too slow for the bonus case, as I have no idea how to express the blocks of ones separated by one or more zeroes in terms of constraints.

Explanation

I will explain below the 93 bytes version. The only difference between the two is the call to predicate 3 which doesn't exist in the 70 bytes version, and the numbering of the predicates (since there is one less).

Main predicate:

```<code>[R:C]     Input = [R, C]
hlL       The length of R is L
~l        Create a list of length L
:L:1f     Each element of that list is a sublist of length L with cells 0 or 1 (Pred 1)
          %%% Part unique to the 93 bytes version
:Cz       Zip the rows of the list of lists with C
:3a       The sum of 1s in each row is equal to the sum of the indicators (Pred 3)
z         Transpose
:Rz       Zip the columns of the list of lists with R
:3a       The sum of 1s in each column is equal to the sum of the indicators (Pred 3)
          %%%
=.        Assign values to the cells of the list of lists which satisfy the constraints
:4aR,     The blocks of 1s must match the indicators on rows
.z        Transpose
:4aC,     The blocks of 1s must match the indicators on columns
</code>```

Predicate 1: Forces the rows to have a specific length, and that each cell is 0 or 1.

```<code>tL,       L is the length given as second element of the input
?he       Take an element from the list
##ElL,    That element E is itself a list of length L
E:2a      The elements of E are 0s and 1s (Pred 2)
</code>```

Predicate 2: Constrain a variable to be either 0 or 1

```<code>.<2,      Input = Output < 2
_1<       Output > -1
</code>```

Predicate 3: The sum of 1s in a list must be equal to the sum of indicators (e.g. if the indicator is [3:1] then the list must have sum 4)

```<code>:+a       Sum the elements of the list and sum the indicator
#=,       Both sums must be equal
?h        Output is the list
</code>```

Predicate 4: Check that blocks of 1s match the indicator

```<code>@b        Split the list in blocks of the same value
:5f       Find all blocks of 1s (Pred 5)
:la       The list of lengths of the blocks results in the indicator (given as output)
</code>```

Predicate 5: True for blocks of 1s, false otherwise

```<code>e.        Output is an element of the input
  h1,     Its first value is 1
</code>```

Body:
Brachylog, <s>70</s> 69 bytes

[R:C]hlL~l:L:1f=.:3aR,.z:3aC,
tL,?he##ElL,E:2a
.<2,_1<
@b:4f:la
e.h1,

This takes a list of two lists (first the rows indicators, then the column ones). Each indicator is itself a list (for situtions like [3,1] on one row).

This version takes about 3 minutes to solve the 5 by 5 example of the challenge.

Way more efficient version, 91 bytes

[R:C]hlL~l:L:1f:Cz:3az:Rz:3a=.:4aR,.z:4aC,
tL,?he##ElL,E:2a
.<2,_1<
:+a#=,?h
@b:5f:la
e.h1,

Try it online!

This one is not complete brute force: the only difference is that this one imposes constraints on the values of cells such that the number of 1s in each row and column matches the numbers given as indicators in the input. The only brute force part is then in finding the one grid with those constraints for which the "blocks" of 1s match what is given as indication.

This one takes about 0.05 seconds on the 5 by 5 example of the challenge. This is still way too slow for the bonus case, as I have no idea how to express the blocks of ones separated by one or more zeroes in terms of constraints.

Explanation

I will explain below the 93 bytes version. The only difference between the two is the call to predicate 3 which doesn't exist in the 70 bytes version, and the numbering of the predicates (since there is one less).

Main predicate:

[R:C]     Input = [R, C]
hlL       The length of R is L
~l        Create a list of length L
:L:1f     Each element of that list is a sublist of length L with cells 0 or 1 (Pred 1)
          %%% Part unique to the 93 bytes version
:Cz       Zip the rows of the list of lists with C
:3a       The sum of 1s in each row is equal to the sum of the indicators (Pred 3)
z         Transpose
:Rz       Zip the columns of the list of lists with R
:3a       The sum of 1s in each column is equal to the sum of the indicators (Pred 3)
          %%%
=.        Assign values to the cells of the list of lists which satisfy the constraints
:4aR,     The blocks of 1s must match the indicators on rows
.z        Transpose
:4aC,     The blocks of 1s must match the indicators on columns

Predicate 1: Forces the rows to have a specific length, and that each cell is 0 or 1.

tL,       L is the length given as second element of the input
?he       Take an element from the list
##ElL,    That element E is itself a list of length L
E:2a      The elements of E are 0s and 1s (Pred 2)

Predicate 2: Constrain a variable to be either 0 or 1

.<2,      Input = Output < 2
_1<       Output > -1

Predicate 3: The sum of 1s in a list must be equal to the sum of indicators (e.g. if the indicator is [3:1] then the list must have sum 4)

:+a       Sum the elements of the list and sum the indicator
#=,       Both sums must be equal
?h        Output is the list

Predicate 4: Check that blocks of 1s match the indicator

@b        Split the list in blocks of the same value
:5f       Find all blocks of 1s (Pred 5)
:la       The list of lengths of the blocks results in the indicator (given as output)

Predicate 5: True for blocks of 1s, false otherwise

e.        Output is an element of the input
  h1,     Its first value is 1


问:
Mirror, Mirror, in the Code
Two-dimensional programming languages often have mirror commands like / and \ to redirect the instruction pointer on the grid:

```<code>>>>>\
    v
    v
<<<</
</code>```

In this challenge, you're given an incoming direction and a mirror and you need to determine the outgoing direction.

Rules

The incoming direction will be given as one of the characters NESW and the mirror will be given as either / or \. You may receive these in any order. You must use uppercase letters.

You may take input in any convenient format, including a two-character string, a string using some separator between the characters, a pair of characters in a list, or even a pair of singleton strings. If you do use a string with separator, the separator cannot use any of the characters NWSE\/.

Output should be a character from NESW or single-character string.

You may write a program or a function and use any of the our standard methods of receiving input and providing output.

You may use any programming language, but note that these loopholes are forbidden by default.

This is code-golf, so the shortest valid answer – measured in bytes – wins.

Test Cases

There are only 8 possible inputs you need to handle, so there is no excuse for not testing your code on all of them:

```<code>N /   -->   W
N \   -->   E
E /   -->   S
E \   -->   N
S /   -->   E
S \   -->   W
W /   -->   N
W \   -->   S
</code>```

答:
Python, <s>63</s> <s>61</s> 59 bytes

lambda d,m,x='NESW'*2:x[x.find(d)+2*(m=='/\\'[d in'NS'])-1]
```

Pretty simple. Can definitely be golfed more. Decides whether to add 1 or -1 to the input's index in 'NESW'.

This is a lambda expression; to use it, prefix it with f=.

Ideone it!

Title: Mirror, Mirror, in the Code

Body:
Python, <s>63</s> <s>61</s> 59 bytes

lambda d,m,x='NESW'*2:x[x.find(d)+2*(m=='/\\'[d in'NS'])-1]

Pretty simple. Can definitely be golfed more. Decides whether to add 1 or -1 to the input's index in 'NESW'.

This is a lambda expression; to use it, prefix it with f=.

Ideone it!


Title: Mirror, Mirror, in the Code

Body:
Two-dimensional programming languages often have mirror commands like / and \ to redirect the instruction pointer on the grid:

```<code>>>>>\
    v
    v
<<<</
</code>```

In this challenge, you're given an incoming direction and a mirror and you need to determine the outgoing direction.

Rules

The incoming direction will be given as one of the characters NESW and the mirror will be given as either / or \. You may receive these in any order. You must use uppercase letters.

You may take input in any convenient format, including a two-character string, a string using some separator between the characters, a pair of characters in a list, or even a pair of singleton strings. If you do use a string with separator, the separator cannot use any of the characters NWSE\/.

Output should be a character from NESW or single-character string.

You may write a program or a function and use any of the our standard methods of receiving input and providing output.

You may use any programming language, but note that these loopholes are forbidden by default.

This is code-golf, so the shortest valid answer – measured in bytes – wins.

Test Cases

There are only 8 possible inputs you need to handle, so there is no excuse for not testing your code on all of them:

```<code>N /   -->   W
N \   -->   E
E /   -->   S
E \   -->   N
S /   -->   E
S \   -->   W
W /   -->   N
W \   -->   S
</code>```

Body:
Javascript (ES6), <s>50</s> <s>41</s> <s>40</s> 37 bytes

d=>m=>(S="NWES")[S.search(d)^-~(m>S)]

Saved 3 more bytes by using comparison, thanks to Lynn's answer

Usage

let f =
d=>m=>(S="NWES")[S.search(d)^-~(m>S)]

console.log(f("N")("/"));  //   -->   W
console.log(f("N")("\\")); //   -->   E
console.log(f("E")("/"));  //   -->   S
console.log(f("E")("\\")); //   -->   N
console.log(f("S")("/"));  //   -->   E
console.log(f("S")("\\")); //   -->   W
console.log(f("W")("/"));  //   -->   N
console.log(f("W")("\\")); //   -->   S


答:
Python 2, 40 bytes

```<code>lambda c,m,k="NWES":k[k.find(c)^(m>k)+1]
</code>```

Sp3000 saved one byte (.index → .find).

Explanation

We want to map the directions like so:

```<code>       \
  N ⇄⇄⇄⇄⇄⇄⇄ E
  ⇅         ⇅
  ⇅         ⇅
/ ⇅         ⇅ /
  ⇅         ⇅
  ⇅         ⇅
  W ⇄⇄⇄⇄⇄⇄⇄ S
       \
</code>```

We can assign the directions 2-bit codes, and view both flips as XOR-ing the first and second bits:

```<code>         xor 2
     0 0 ⇄⇄⇄⇄⇄ 1 0
      ⇅         ⇅
      ⇅         ⇅
xor 1 ⇅         ⇅ xor 1
      ⇅         ⇅
      ⇅         ⇅
     0 1 ⇄⇄⇄⇄⇄ 1 1
         xor 2
</code>```

The mapping between bit strings and directions happens using the string k. Now we just need to map mirror characters '/' and '\\' to the values 1 and 2. Since '/' < '\\', we could naïvely use (m>'/')+1 as a formula. But wait! Lexicographically,

```<code>'/' < 'NWES' < '\\'
</code>```

and we have 'NWES' nicely assigned to k! So we can use (m>k)+1 instead.

Title: Mirror, Mirror, in the Code

Body:
Python 2, 40 bytes

lambda c,m,k="NWES":k[k.find(c)^(m>k)+1]

Sp3000 saved one byte (.index → .find).

Explanation

We want to map the directions like so:

       \
  N ⇄⇄⇄⇄⇄⇄⇄ E
  ⇅         ⇅
  ⇅         ⇅
/ ⇅         ⇅ /
  ⇅         ⇅
  ⇅         ⇅
  W ⇄⇄⇄⇄⇄⇄⇄ S
       \

We can assign the directions 2-bit codes, and view both flips as XOR-ing the first and second bits:

         xor 2
     0 0 ⇄⇄⇄⇄⇄ 1 0
      ⇅         ⇅
      ⇅         ⇅
xor 1 ⇅         ⇅ xor 1
      ⇅         ⇅
      ⇅         ⇅
     0 1 ⇄⇄⇄⇄⇄ 1 1
         xor 2

The mapping between bit strings and directions happens using the string k. Now we just need to map mirror characters '/' and '\\' to the values 1 and 2. Since '/' < '\\', we could naïvely use (m>'/')+1 as a formula. But wait! Lexicographically,

'/' < 'NWES' < '\\'

and we have 'NWES' nicely assigned to k! So we can use (m>k)+1 instead.


答:
MATL, <s>19</s> 17 bytes

```<code>'NWSE'jy&mjy+Eq-)
</code>```

Try it online! Or verify the eight cases.

Explanation

```<code>'NWSE'    % Push this string
j         % Take first input, say 'W'. Stack contains: 'NWSE', 'W'
y         % Duplicate from below. Stack: 'NWSE', 'W', 'NWSE'
&m        % Index of membership. Stack: 'NWSE', 2
j         % Take second input, say '/'. Stack: 'NWSE', 2, '/'
y         % Duplicate from below. Stack: 'NWSE', 2, '/', 2
+         % Add (char '/' is converted to code point). Stack: 'NWSE', 2, 49
Eq        % Multiply by 2, subtract 1. Stack: 'NWSE', 2, 97
-         % Subtract. Stack: 'NWSE', -95
)         % Apply -95 as (modular, 1-based) index into 'NWSE'. Stack: 'N'
          % Implicitly display
</code>```

Title: Mirror, Mirror, in the Code

Body:
MATL, <s>19</s> 17 bytes

'NWSE'jy&mjy+Eq-)

Try it online! Or verify the eight cases.

Explanation

'NWSE'    % Push this string
j         % Take first input, say 'W'. Stack contains: 'NWSE', 'W'
y         % Duplicate from below. Stack: 'NWSE', 'W', 'NWSE'
&m        % Index of membership. Stack: 'NWSE', 2
j         % Take second input, say '/'. Stack: 'NWSE', 2, '/'
y         % Duplicate from below. Stack: 'NWSE', 2, '/', 2
+         % Add (char '/' is converted to code point). Stack: 'NWSE', 2, 49
Eq        % Multiply by 2, subtract 1. Stack: 'NWSE', 2, 97
-         % Subtract. Stack: 'NWSE', -95
)         % Apply -95 as (modular, 1-based) index into 'NWSE'. Stack: 'N'
          % Implicitly display


答:
Mathematica, 98 bytes

```<code>If[#2=="/",{"S",,,,,,,,,"W",,,,,"E",,,,"N"},{"N",,,,,,,,,"E",,,,,"W",,,,"S"}][[LetterNumber@#-4]]&
</code>```

Anonymous function. Takes two strings as input and returns a string as output.

Title: Mirror, Mirror, in the Code

Body:
Mathematica, 98 bytes

If[#2=="/",{"S",,,,,,,,,"W",,,,,"E",,,,"N"},{"N",,,,,,,,,"E",,,,,"W",,,,"S"}][[LetterNumber@#-4]]&

Anonymous function. Takes two strings as input and returns a string as output.


答:
Java 8, <s>62</s> <s>58</s> 56 bytes

```<code>(d,m)->"SEWN".charAt("NWES".indexOf(d)^m.indexOf(47)+2);
</code>```

Ungolfed test program

```<code>import java.util.function.BiFunction;

public class Mirror {

public static void main(String[] args) {
    BiFunction<String, String, Character> function = (d,m)->"SEWN".charAt("NWES".indexOf(d)^m.indexOf(47)+2);

    System.out.println(function.apply("N", "/")); //W
    System.out.println(function.apply("N", "\\")); //E
    System.out.println(function.apply("W", "/")); //N
    System.out.println(function.apply("W", "\\")); //S
    System.out.println(function.apply("E", "/")); //S
    System.out.println(function.apply("E", "\\")); //N
    System.out.println(function.apply("S", "/")); //E
    System.out.println(function.apply("S", "\\")); //W
}

}
</code>```

Title: Mirror, Mirror, in the Code

Body:
Java 8, <s>62</s> <s>58</s> 56 bytes

(d,m)->"SEWN".charAt("NWES".indexOf(d)^m.indexOf(47)+2);

Ungolfed test program

import java.util.function.BiFunction;

public class Mirror {

public static void main(String[] args) {
    BiFunction<String, String, Character> function = (d,m)->"SEWN".charAt("NWES".indexOf(d)^m.indexOf(47)+2);

    System.out.println(function.apply("N", "/")); //W
    System.out.println(function.apply("N", "\\")); //E
    System.out.println(function.apply("W", "/")); //N
    System.out.println(function.apply("W", "\\")); //S
    System.out.println(function.apply("E", "/")); //S
    System.out.println(function.apply("E", "\\")); //N
    System.out.println(function.apply("S", "/")); //E
    System.out.println(function.apply("S", "\\")); //W
}

}


答:
Java 7, <s>71</s> <s>70</s> 68 bytes

```<code>char c(int d,int m){return"NEWS".charAt("NEWS".indexOf(d)^-~(m%2));}
</code>```

Too bad the charAt and indexOf takes up so much bytes..

Ungolfed & all test cases:

Try it here.

```<code>class M{
  static char c(int d, int m) {
    return "NEWS".charAt("NEWS".indexOf(d) ^ -~(m%2));
  }

  public static void main(String[] a){
    System.out.print(c('N', '/') + " ");
    System.out.print(c('N', '\\') + " ");
    System.out.print(c('E', '/') + " ");
    System.out.print(c('E', '\\') + " ");
    System.out.print(c('S', '/') + " ");
    System.out.print(c('S', '\\') + " ");
    System.out.print(c('W', '/') + " ");
    System.out.print(c('W', '\\') + " ");
  }
}
</code>```

Output:

```<code>W E S N E W N S
</code>```

Title: Mirror, Mirror, in the Code

Body:
Java 7, <s>71</s> <s>70</s> 68 bytes

char c(int d,int m){return"NEWS".charAt("NEWS".indexOf(d)^-~(m%2));}

Too bad the charAt and indexOf takes up so much bytes..

Ungolfed & all test cases:

Try it here.

class M{
  static char c(int d, int m) {
    return "NEWS".charAt("NEWS".indexOf(d) ^ -~(m%2));
  }

  public static void main(String[] a){
    System.out.print(c('N', '/') + " ");
    System.out.print(c('N', '\\') + " ");
    System.out.print(c('E', '/') + " ");
    System.out.print(c('E', '\\') + " ");
    System.out.print(c('S', '/') + " ");
    System.out.print(c('S', '\\') + " ");
    System.out.print(c('W', '/') + " ");
    System.out.print(c('W', '\\') + " ");
  }
}

Output:

W E S N E W N S


答:
Pyth, <s>17</s> <s>16</s> 15 bytes

Thanks to @Jakube and @Maltysen for -1 byte each

```<code>@J"NWES"xxJQh>E
</code>```

A program that takes input of two newline-separated quoted strings, first the direction and then the mirror, and prints the result.

This is a port of @Lynn's Python answer.

Try it online

How it works

```<code>@J"NWES"xxJQh>E  Program. Inputs: Q, E
 J"NWES"         J="NWES". Yield J
         xJQ     J.index(Q)
             >E  E>Q, lexographically (implicit input fill)
            h    +1
        x        Bitwise XOR of the above two
@                Index into J with the above
                 Implicitly print
</code>```

Title: Mirror, Mirror, in the Code

Body:
Pyth, <s>17</s> <s>16</s> 15 bytes

Thanks to @Jakube and @Maltysen for -1 byte each

@J"NWES"xxJQh>E

A program that takes input of two newline-separated quoted strings, first the direction and then the mirror, and prints the result.

This is a port of @Lynn's Python answer.

Try it online

How it works

@J"NWES"xxJQh>E  Program. Inputs: Q, E
 J"NWES"         J="NWES". Yield J
         xJQ     J.index(Q)
             >E  E>Q, lexographically (implicit input fill)
            h    +1
        x        Bitwise XOR of the above two
@                Index into J with the above
                 Implicitly print


问:
Convert the Binary Champernowne Constant to Decimal
The Champernowne constant is a transcendental decimal number whose digits are the concatination of all positive integers.

C10 =  0.12345678910111213141516...10

The binary version of this is

C2 = 0.1101110010111011110001...2

Write a program that prints C2 in decimal.  The program should never halt.  It should continue printing digits such that given infinite time and memory, it will print an infinite number of correct digits.

To illustrate this, you must account for integer overflow, since integer overflow will either cause an error or print incorrect digits, even with infinite memory available.

To test your code, here are the first 150 digits of this number.

```<code>0.862240125868054571557790283249394578565764742768299094516071214557306740590516458042038441438618133400466718933678923129464456214392016383510596824661
</code>```

Shortest code wins.

答:
Python, 225

```<code>import sys,fractions
w=sys.stdout.write
w('0.')
h=t=10
l=n=0
p=fractions.Fraction(5)
i=int
while 1:
 while i(h)!=i(l):
  n+=1
  for c in bin(n)[2:]:
    if c=='1':l+=p
    else:h-=p
    p/=2
 w(str(i(h)));h-=i(h);l-=i(l);h*=t;l*=t;p*=t
</code>```

Note that the 4-space indentation should be tab characters.  They seem to be converted to spaces when displayed here.

Explanation

h and l are the highest and lowest possible values for the current digit, as fractions.

For example, if h is 7/2 or 3.5, the current digit is at most 3, and if it is 3, then the next digit is at most 5.

When int(h) == int(l), we know what the next digit is, so we print that, subtract it from h and l, and multiply them by 10 to get the bounds for the next digit.

When int(h) != int(l), we improve our bounds by looking further into C2.  For the nth decimal place in the output and bth binary place in C2, a 1 means l increases by 10^n/2^b and a 0 means h decreases by that amount.

Body:
Python, 225

import sys,fractions
w=sys.stdout.write
w('0.')
h=t=10
l=n=0
p=fractions.Fraction(5)
i=int
while 1:
 while i(h)!=i(l):
  n+=1
  for c in bin(n)[2:]:
    if c=='1':l+=p
    else:h-=p
    p/=2
 w(str(i(h)));h-=i(h);l-=i(l);h*=t;l*=t;p*=t

Note that the 4-space indentation should be tab characters.  They seem to be converted to spaces when displayed here.

Explanation

h and l are the highest and lowest possible values for the current digit, as fractions.

For example, if h is 7/2 or 3.5, the current digit is at most 3, and if it is 3, then the next digit is at most 5.

When int(h) == int(l), we know what the next digit is, so we print that, subtract it from h and l, and multiply them by 10 to get the bounds for the next digit.

When int(h) != int(l), we improve our bounds by looking further into C2.  For the nth decimal place in the output and bth binary place in C2, a 1 means l increases by 10^n/2^b and a 0 means h decreases by that amount.


问:
As Easy as One-Two-Three
Write a program or function that takes in a positive integer. You can assume the input is valid and may take it as a string. If the number is any of

```<code>123
234
345
456
567
678
789
</code>```

then output a truthy value. Otherwise, output a falsy value. For example, the inputs

```<code>1
2
3
12
122
124
132
321
457
777
890
900
1011
1230
1234
</code>```

must all result in falsy output. (The input will not have leading zeroes so you needn't worry about things like 012.)

The shortest code in bytes wins.

Title: As Easy as One-Two-Three

Body:
Clojure, 48 bytes

(defn f [n] (= n ((set (range 123 900 111)) n)))

Test:

user=> (map (fn [n] [n (f n)]) [123 234 345 456 567 678 789])
([123 true]
 [234 true]
 [345 true]
 [456 true]
 [567 true]
 [678 true]
 [789 true])

user=> (map (fn [n] [n (f n)]) [1 2 3 12 122 124 132 321 457 777 890 900 1011 1230 1234])
([1 false]
 [2 false]
 [3 false]
 [12 false]
 [122 false]
 [124 false]
 [132 false]
 [321 false]
 [457 false]
 [777 false]
 [890 false]
 [900 false]
 [1011 false]
 [1230 false]
 [1234 false])


问:
The longest period iterating quine
As we know, a quine is a program that outputs its own source code. However, it's also possible to write a program that outputs another, different program, that outputs the first program again. For example, the Python 2 program

```<code>x = '''x = {}
print 'print '+'"'*3+x.format("'"*3+x+"'"*3)+'"'*3'''
print 'print '+'"'*3+x.format("'"*3+x+"'"*3)+'"'*3
</code>```

will, when run, output the following text:

```<code>print """x = '''x = {}
print 'print '+'"'*3+x.format("'"*3+x+"'"*3)+'"'*3'''
print 'print '+'"'*3+x.format("'"*3+x+"'"*3)+'"'*3"""
</code>```

When run as a Python program, this will output the original code again. This is called an iterating quine. Because you have to run it twice to get the original code back, we say it has period 2. But of course, much higher periods are possible.

Your challenge is to write an iterating quine with as long a period as you can, in 100 bytes or less, in the language of your choice. (Note that my example above doesn't fit this spec, as it's 119 bytes, including the trailing newline.)

Please note the following rules and clarifications:

The usual quine rules apply, i.e. your program can't use language features that would let it access its own source code directly.

The iterated outputs have to eventually loop back to exactly your original code, and you have to include a demonstration or proof that it will.

You must also include an explanation of why the cycle is as long as you say it is. This doesn't have to be at the level of a mathematical proof, but it should be convincing to someone familiar with your language. (This rule is here because I expect some of the answers to involve very, very large numbers.)

It's fine to say something like "at least 1,000,000 iterations" rather than giving the exact number, as long as you can prove that it is at least that long. In this case, your score would be 1,000,000. Otherwise, your score is the period of your quine.

The 100 byte limit only applies to your initial program - the programs it outputs can be longer, though of course they'll eventually have to get back down to 100 bytes in order to output your original code.

You can assume your machine has infinite RAM and infinite runtime, but you can't assume unlimited precision data types (such as integers) if your language doesn't have them. You can assume there is no limit to the length of input your parser can handle.

The highest score wins.

Please note: there is an existing challenge called Quit Whining; Start Quining that also involves iterating quines. However, aside from being based on the same concept, these are completely different types of challenge. The other one is straight up code golf, whereas this one is (intentionally!) really a busy beaver problem in disguise. The techniques needed to produce a good answer to this question are likely to be very different from what's needed to answer the other question, and this is very much by design.

答:
R, random period with expectation 2^19936-0.5

```<code>f=function(){
    options(scipen=50)
    body(f)[[4]]<<-sum(runif(623))
    0
    cat("f=")
    print(f)
}
</code>```

R's default random number generator has a period of 2^19937-1 and equidistribution in 623 consecutive dimensions. Thus, somewhere (but only once) in its period will be a 623-long vector of zeroes. When we get there (and are aligned with the start of the sequence) the sum of the next 623 random U[0,1] numbers will be zero and we return to our original program.

Note that the program will with very high probability pass through the same non-zero state several times before returning to zero. For instance, the sum 311.5 is the most likely, and there are a great many ways that can happen, but the RNG allows the period for 0 to be longer than the period for 311.5.

Title: The longest period iterating quine

Body:
R, random period with expectation 2^19936-0.5

f=function(){
    options(scipen=50)
    body(f)[[4]]<<-sum(runif(623))
    0
    cat("f=")
    print(f)
}

R's default random number generator has a period of 2^19937-1 and equidistribution in 623 consecutive dimensions. Thus, somewhere (but only once) in its period will be a 623-long vector of zeroes. When we get there (and are aligned with the start of the sequence) the sum of the next 623 random U[0,1] numbers will be zero and we return to our original program.

Note that the program will with very high probability pass through the same non-zero state several times before returning to zero. For instance, the sum 311.5 is the most likely, and there are a great many ways that can happen, but the RNG allows the period for 0 to be longer than the period for 311.5.


答:
T-SQL 37 22 bytes

Saved 15 bytes thanks to BradC's comment.

The usual hardcoded variable for lack of a stdin.

e.g.

```<code>DECLARE @ NVARCHAR(4) = '2016'
</code>```

Then the solution is:

```<code>PRINT ISDATE(@+'0229')
</code>```

Title: Is it a leap year?

Body:
This challenge is quite simple. You will take an input which will be a year from 1801 to 2400, and output if it is a leap year or not.

Your input will have no newlines or trailing spaces:

```<code>1954
</code>```

You will output in any way that you like that clearly tells the user if it is or isn't a leap year (I will accept y or n for yes/no)

You can get a list of leap years here: http://kalender-365.de/leap-years.php
I would note that leap years are not ever four years always. 1896 is a leap year, but 1900 is not. The years that follow this "skip" are:

```<code>1900
2100
2200
2300
</code>```

Test cases:

```<code>1936 ->  y
1805 ->  n
1900 ->  n
2272 ->  y
2400 ->  y
</code>```

EDIT: This is based on a standard Gregorian calendar: http://www.epochconverter.com/date-and-time/daynumbers-by-year.php

The Catalogue

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

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

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

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

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

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

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

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

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

/* Configuration */

var QUESTION_ID = 50798; // 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 = 8478; // 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,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\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,
      });
    else console.log(body);
  });

  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;
    lang = jQuery(''+lang+'').text();

    languages[lang] = languages[lang] || {lang: a.language, lang_raw: lang, user: a.user, size: a.size, link: a.link};
  });

  var langs = [];
  for (var lang in languages)
    if (languages.hasOwnProperty(lang))
      langs.push(languages[lang]);

  langs.sort(function (a, b) {
    if (a.lang_raw.toLowerCase() > b.lang_raw.toLowerCase()) return 1;
    if (a.lang_raw.toLowerCase() < b.lang_raw.toLowerCase()) 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;
  display: block !important;
}

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

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

table thead {
  font-weight: bold;
}

table td {
  padding: 5px;
}</code>```

<link rel="stylesheet" type="text/css" href="https://cdn.sstatic.net/Sites/codegolf/all.css?v=ffb5d0584c5f">

Shortest Solution by Language

Language	User	Score

Leaderboard

	Author	Language	Size

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

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

```

Body:
T-SQL 37 22 bytes

Saved 15 bytes thanks to BradC's comment.

The usual hardcoded variable for lack of a stdin.

e.g.

DECLARE @ NVARCHAR(4) = '2016'

Then the solution is:

PRINT ISDATE(@+'0229')


答:
Python, <s>40</s> 38 bytes

-2 bytes thanks to @MitchSchwartz (ord(d)+ord(m))%8 -> ord(d)+ord(m)&7

lambda d,m:' NESSWNW'[ord(d)+ord(m)&7]
```

plain lookup of answer in a list (AKA string) indexed by the smallest mod of the sum of ordinals that works.

Test cases are on ideone

Title: Mirror, Mirror, in the Code

Body:
Python, <s>40</s> 38 bytes

-2 bytes thanks to @MitchSchwartz (ord(d)+ord(m))%8 -> ord(d)+ord(m)&7

lambda d,m:' NESSWNW'[ord(d)+ord(m)&7]

plain lookup of answer in a list (AKA string) indexed by the smallest mod of the sum of ordinals that works.

Test cases are on ideone


问:
Subtract the next numbers

Description

Subtract the next P numbers from a N number. The next number of N is N + 1.

Look at the examples to get what I mean.

Examples:

```<code>Input: N=2,P=3
Calculate: n - (n+1) - (n+2) - (n+3)     //Ending with 3, because P=3
Calculate: 2 -  2+1  -  2+2  - 2+3       //Replacing N with 2 from Input
Calculate: 2 -  3    -  4    - 5
Output: -10

Input: N=100,P=5
Calculate: n - (n+1) - (n+2) - (n+3) - (n+4) - (n+5)
Calculate: 100-  101 -  102  -  103  -  104  - 105
Output: -415

Input: N=42,P=0
Calculate: n
Calculate: 42
Output: 42

Input: N=0,P=3
Calculate: n - (n+1) - (n+2) - (n+3)
Calculate: 0 -  1    -  2    -  3
Output: -6

Input: N=0,P=0
Calulate: n
Calculate: 0
Output: 0
</code>```

Input:

N: Integer, positive, negative or 0

P: Integer, positive or 0, not negative

Output:

Integer or String, leading 0 allowed, trailing newline allowed

Rules:

No loopholes

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

Input and Output must be as described

答:
Java 8, 25 bytes

```<code>(n,p)->n-(p*n+p*(p+1)/2);
</code>```

Ungolfed test program

```<code>public static void main(String[] args) {

    BiFunction<Integer, Integer, Integer> f = (n, p) -> n - (p * n + p * (p + 1) / 2);
    System.out.println(f.apply(100, 5));
}
</code>```

Title: Subtract the next numbers

Body:
Java 8, 25 bytes

(n,p)->n-(p*n+p*(p+1)/2);

Ungolfed test program

public static void main(String[] args) {

    BiFunction<Integer, Integer, Integer> f = (n, p) -> n - (p * n + p * (p + 1) / 2);
    System.out.println(f.apply(100, 5));
}


问:
Print numbers from 1 to 10
This might be a very simple challenge, but I am surprised it hasn't been done on code-golf yet:

Print all Integers from 1 to 10 inclusive in ascending order to standard output.

Your output format can be whatever your language supports. This includes arbitrary separators (commas, semicolons, newlines, combinations of those, etc., but no digits), and prefixes and postfixes (like [...]). However, you may not output any other numbers than 1 through 10. Your program may not take any input. Standard loopholes are disallowed.

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

Leaderboard

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

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

```

答:
Emmet (HTML) - 6 bytes

You'll have to excuse me, I'm new to code golf but I think I understand the concept.

```<code>{$}*10
</code>```

Output:

```<code>12345678910
</code>```

Alternatively, if it's required for the numbers to be seperate, adding a p infront of the braces will put it into
 tags, like so:

```<code><p>1</p>
<p>2</p>
<p>3</p>
<p>4</p>
<p>5</p>
<p>6</p>
<p>7</p>
<p>8</p>
<p>9</p>
<p>10</p>
</code>```

It also requires a tab to make it "go", I've left that out of the byte count.

Please let me know if I've stuffed up somewhere. Thanks!

Title: Print numbers from 1 to 10

Body:
Emmet (HTML) - 6 bytes

You'll have to excuse me, I'm new to code golf but I think I understand the concept.

{$}*10

Output:

12345678910

Alternatively, if it's required for the numbers to be seperate, adding a p infront of the braces will put it into <p> tags, like so:

<p>1</p>
<p>2</p>
<p>3</p>
<p>4</p>
<p>5</p>
<p>6</p>
<p>7</p>
<p>8</p>
<p>9</p>
<p>10</p>

It also requires a tab to make it "go", I've left that out of the byte count.

Please let me know if I've stuffed up somewhere. Thanks!


答:
CJam, 14 bytes

(@MartinEnder ported my Python answer)

```<code>l1b" NESSWNW"=
</code>```

How?

```<code>l1b" NESSWNW"= -
l              - read input
 1b            - cast characters as base 1 digits
   " NESSWNW"  - the string " NESSWNW"
             = - modulo index into the string
</code>```

Tests are on aditsu

Title: Mirror, Mirror, in the Code

Body:
CJam, 14 bytes

(@MartinEnder ported my Python answer)

l1b" NESSWNW"=

How?

l1b" NESSWNW"= -
l              - read input
 1b            - cast characters as base 1 digits
   " NESSWNW"  - the string " NESSWNW"
             = - modulo index into the string

Tests are on aditsu


答:
Jelly, <s>14 13</s> 12 bytes

(a port of my Python answer)

-1 byte thanks to @MartinEnder (add a space to end of the string and remove need for modulo 8)

-1 byte thanks to @LuisMendo (take a single string argument rather than two)

```<code>OSị“NESSWNW
</code>```

How?

```<code>OSị“NESSWNW  - takes a single argument "dm" (direction and mirror), in either order.
                   strings and lists are equivalent in Jelly
 O            - ordinal: [ord(d),ord(m)]
  S           - sum: ord(d)+ord(m)
    “NESSWNW  - string: "NESSWNW "
   ị          - fetch modulo index (the string is 8 long and 1-based)
</code>```

Test it on TryItOnline

Title: Mirror, Mirror, in the Code

Body:
Two-dimensional programming languages often have mirror commands like / and \ to redirect the instruction pointer on the grid:

```<code>>>>>\
    v
    v
<<<</
</code>```

In this challenge, you're given an incoming direction and a mirror and you need to determine the outgoing direction.

Rules

The incoming direction will be given as one of the characters NESW and the mirror will be given as either / or \. You may receive these in any order. You must use uppercase letters.

You may take input in any convenient format, including a two-character string, a string using some separator between the characters, a pair of characters in a list, or even a pair of singleton strings. If you do use a string with separator, the separator cannot use any of the characters NWSE\/.

Output should be a character from NESW or single-character string.

You may write a program or a function and use any of the our standard methods of receiving input and providing output.

You may use any programming language, but note that these loopholes are forbidden by default.

This is code-golf, so the shortest valid answer – measured in bytes – wins.

Test Cases

There are only 8 possible inputs you need to handle, so there is no excuse for not testing your code on all of them:

```<code>N /   -->   W
N \   -->   E
E /   -->   S
E \   -->   N
S /   -->   E
S \   -->   W
W /   -->   N
W \   -->   S
</code>```

Body:
Jelly, <s>14 13</s> 12 bytes

(a port of my Python answer)

-1 byte thanks to @MartinEnder (add a space to end of the string and remove need for modulo 8)

-1 byte thanks to @LuisMendo (take a single string argument rather than two)

OSị“NESSWNW

How?

OSị“NESSWNW  - takes a single argument "dm" (direction and mirror), in either order.
                   strings and lists are equivalent in Jelly
 O            - ordinal: [ord(d),ord(m)]
  S           - sum: ord(d)+ord(m)
    “NESSWNW  - string: "NESSWNW "
   ị          - fetch modulo index (the string is 8 long and 1-based)

Test it on TryItOnline


答:
Batch, 111 bytes

```<code>:goto %1
:W/
:E\
@echo N
@exit/b
:S/
:N\
@echo E
@exit/b
:E/
:W\
@echo S
@exit/b
:N/
:S\
@echo W
</code>```

Accepts e.g. W/ as a two-character string command line parameter. The \ and / make looping awkward; it would have taken 124 bytes.

Title: Mirror, Mirror, in the Code

Body:
Batch, 111 bytes

:goto %1
:W/
:E\
@echo N
@exit/b
:S/
:N\
@echo E
@exit/b
:E/
:W\
@echo S
@exit/b
:N/
:S\
@echo W

Accepts e.g. W/ as a two-character string command line parameter. The \ and / make looping awkward; it would have taken 124 bytes.


答:
05AB1E, 14 bytes

```<code>‘€Ã‘DIkI'/kÌ^è

‘€Ã‘             # from string "NEWS"
             è   # get element at index
    DIk          # index of 1st input in string "NEWS"
            ^    # XOR
       I'/k      # index of 2nd input in string "/"
           Ì     # +2
</code>```

Try it online!

Title: Mirror, Mirror, in the Code

Body:
05AB1E, 14 bytes

‘€Ã‘DIkI'/kÌ^è

‘€Ã‘             # from string "NEWS"
             è   # get element at index
    DIk          # index of 1st input in string "NEWS"
            ^    # XOR
       I'/k      # index of 2nd input in string "/"
           Ì     # +2

Try it online!


问:
Count from 1 to 100... in Roman Numerals
Write a program that count from 1 to 100 in Roman Numerals and print these numbers by standard output. Each one of the numbers must be separated by spaces.

You cannot use any built in function to transform to roman numerals nor external application or library to do so.

The desired result is

```<code>I II III IV V VI VII VIII IX X XI XII XIII XIV XV XVI XVII XVIII XIX XX XXI XXII XXIII XXIV XXV XXVI XXVII XXVIII XXIX XXX XXXI XXXII XXXIII XXXIV XXXV XXXVI XXXVII XXXVIII XXXIX XL XLI XLII XLIII XLIV XLV XLVI XLVII XLVIII XLIX L LI LII LIII LIV LV LVI LVII LVIII LIX LX LXI LXII LXIII LXIV LXV LXVI LXVII LXVIII LXIX LXX LXXI LXXII LXXIII LXXIV LXXV LXXVI LXXVII LXXVIII LXXIX LXXX LXXXI LXXXII LXXXIII LXXXIV LXXXV LXXXVI LXXXVII LXXXVIII LXXXIX XC XCI XCII XCIII XCIV XCV XCVI XCVII XCVIII XCIX C
</code>```

As it is a code golf challenge, shortest code wins.

答:
Ruby 1.9, 140 132

```<code>r=" "
100.times{r+=?I
0while[[?I*4,"IV"],["VIV","IX"],[?X*4,"XL"],["LXL","XC"],[/(.)((?!\1)[^I])\1/,'\2']].any?{|q|r.sub! *q}
$><<r}
</code>```

This literally counts from 1 to 100 in Roman numerals.  Starts with a blank string, then loops through appending "I" and then repeatedly applying a series of substitution rules, effectively adding 1.

Edit: Added version number, since ?I only works in 1.9, and used @Howard's changes to trim some characters.

Body:
Ruby 1.9, 140 132

r=" "
100.times{r+=?I
0while[[?I*4,"IV"],["VIV","IX"],[?X*4,"XL"],["LXL","XC"],[/(.)((?!\1)[^I])\1/,'\2']].any?{|q|r.sub! *q}
$><<r}

This literally counts from 1 to 100 in Roman numerals.  Starts with a blank string, then loops through appending "I" and then repeatedly applying a series of substitution rules, effectively adding 1.

Edit: Added version number, since ?I only works in 1.9, and used @Howard's changes to trim some characters.


答:
PowerShell v2+, 34 bytes

```<code>param($a,$b)"xNESSWNW"[(+$a+$b)%8]
</code>```

Takes input as two explicit chars, outputs a char.

This works as follows: If we sort the output, we want S / to somehow equal the same as N \, W / to equal E \, etc. Or, at least, produce numbers that are "close enough" yet still distinct. If we look at the ASCII values, we get a table like the below:

```<code>In1   In2       Res.    Sum
S 83  / 47  --> E 69 -> 130
N 78  \ 92  --> E 69 -> 170
W 87  / 47  --> N 78 -> 134
E 69  \ 92  --> N 78 -> 161
W 87  \ 92  --> S 83 -> 179
E 69  / 47  --> S 83 -> 116
N 78  / 47  --> W 87 -> 125
S 83  \ 92  --> W 87 -> 175
</code>```

Running a quick brute-forcer on the summations column (derived from summing the ASCII code points of the inputs) shows that if we take the sums modulo 8, we get the following 2 2 | 6 1 | 3 4 | 5 7. That's evidenced in the string "xNESSWNW", as E is at index 2, N is at 6 and 1, and so on.

So, we just need to sum the inputs (implicitly casting from char to int32 along the way), take that %8, and use that to index into our string.

Test Cases

```<code>PS C:\Tools\Scripts\golfing> ('N','/'),('N','\'),('E','/'),('E','\'),('S','/'),('S','\'),('W','/'),('W','\')|%{"$($_[0]) $($_[1]) --> "+(.\mirror-mirror-in-the-code.ps1 ([char]$_[0]) ([char]$_[1]))}
N / --> W
N \ --> E
E / --> S
E \ --> N
S / --> E
S \ --> W
W / --> N
W \ --> S
</code>```

Title: Mirror, Mirror, in the Code

Body:
PowerShell v2+, 34 bytes

param($a,$b)"xNESSWNW"[(+$a+$b)%8]

Takes input as two explicit chars, outputs a char.

This works as follows: If we sort the output, we want S / to somehow equal the same as N \, W / to equal E \, etc. Or, at least, produce numbers that are "close enough" yet still distinct. If we look at the ASCII values, we get a table like the below:

In1   In2       Res.    Sum
S 83  / 47  --> E 69 -> 130
N 78  \ 92  --> E 69 -> 170
W 87  / 47  --> N 78 -> 134
E 69  \ 92  --> N 78 -> 161
W 87  \ 92  --> S 83 -> 179
E 69  / 47  --> S 83 -> 116
N 78  / 47  --> W 87 -> 125
S 83  \ 92  --> W 87 -> 175

Running a quick brute-forcer on the summations column (derived from summing the ASCII code points of the inputs) shows that if we take the sums modulo 8, we get the following 2 2 | 6 1 | 3 4 | 5 7. That's evidenced in the string "xNESSWNW", as E is at index 2, N is at 6 and 1, and so on.

So, we just need to sum the inputs (implicitly casting from char to int32 along the way), take that %8, and use that to index into our string.

Test Cases

PS C:\Tools\Scripts\golfing> ('N','/'),('N','\'),('E','/'),('E','\'),('S','/'),('S','\'),('W','/'),('W','\')|%{"$($_[0]) $($_[1]) --> "+(.\mirror-mirror-in-the-code.ps1 ([char]$_[0]) ([char]$_[1]))}
N / --> W
N \ --> E
E / --> S
E \ --> N
S / --> E
S \ --> W
W / --> N
W \ --> S


问:
The Squiggly Sequence

All credits to Adnan for coming up with this challenge.

My last challenge, before I go on break.

Task

Given positive integer n, if n is odd, repeat / that many times; if n is even, repeat \ that many times.

(Seriously, the testcases would be much clearer than this description, so just look at the testcases.)

Specs

Any reasonable input/output format.

Standard loopholes apply.

Testcases

```<code>n output
1 /
2 \\
3 ///
4 \\\\
5 /////
6 \\\\\\
</code>```

答:
Forth, <s>58</s> 54 bytes

Leaves n%2 as junk on the stack. Output is sent to stdout. 47 is /, and 92 is \. Computes y=92-45*x, where x is n%2 and emits (outputs) the character with that codepoint.

: f dup 2 mod swap 0 DO dup 92 swap 45 * - emit LOOP ;
```

Try it online

Title: The Squiggly Sequence

Body:
Forth, <s>58</s> 54 bytes

Leaves n%2 as junk on the stack. Output is sent to stdout. 47 is /, and 92 is \. Computes y=92-45*x, where x is n%2 and emits (outputs) the character with that codepoint.

: f dup 2 mod swap 0 DO dup 92 swap 45 * - emit LOOP ;

Try it online


问:
Draw the Union Jack

Preface

There are many "draw x flag" challenges, and upon searching it turns out there are no challenges to draw the union Jack! I feel like this would be a harder flag to draw but it should still be possible.

Challenge

Draw the Union Jack. It can be outputted to a file in any freely available graphics file format or drawn onto the screen.

Code Golf rules apply, shortest code in bytes wins.

Standard loopholes apply.

No builtins for flag drawing allowed.

Dimensions shall be as below. Minimum size 600x300 pixels (or units if your language supports only scalable graphics.) Maximum error 1 pixel.

Colours shall be red, white and blue as defined by your language or its documentation, or #CC0000, #FFFFFF and #003399 per Wikipedia page.

答:
Processing, 312 bytes

This is the type of puzzle where Processing is pretty efficient.

```<code>int a=300,b=2*a,c=255,d=100;size(b,a);background(0,51,153);stroke(c);strokeWeight(60);line(0,a,b,0);line(0,0,b,a);stroke(c,0,0);strokeWeight(20);line(0,310,a,160);line(-22,0,a,160);line(a,139,b,-12);line(a,139,624,a);noStroke();fill(c);rect(250,0,d,b);rect(0,d,b,d);fill(c,0,0);rect(270,0,60,b);rect(0,120,b,60);
</code>```

Results in:

Title: Draw the Union Jack

Body:
Processing, 312 bytes

This is the type of puzzle where Processing is pretty efficient.

int a=300,b=2*a,c=255,d=100;size(b,a);background(0,51,153);stroke(c);strokeWeight(60);line(0,a,b,0);line(0,0,b,a);stroke(c,0,0);strokeWeight(20);line(0,310,a,160);line(-22,0,a,160);line(a,139,b,-12);line(a,139,624,a);noStroke();fill(c);rect(250,0,d,b);rect(0,d,b,d);fill(c,0,0);rect(270,0,60,b);rect(0,120,b,60);

Results in:


答:
CJam, 17 bytes

```<code>r"SWEN"_e!r'/#=er
</code>```

Input is space-separated.

Try it online! (As a linefeed-separated test suite.)

This is the solution I found before posting the challenge. Not as short as Jonathan's cyclic indexing, but I thought this approach is quite interesting (and novel).

Explanation

The goal is use transliteration (i.e. using a character-to-character mapping) to replace the input character with the output character. To do this, we need to select the correct map based on whether the mirror is / or \. We'll map from the SWEN list to another one which we'll select conditionally. If the input list is SWEN, the two output maps need to be the following:

```<code>in  SWEN
/   ENSW
\   WSNE
</code>```

Note that these are in sorted and reverse-sorted order (which is why we chose the seemingly random SWEN order as the input set). We could generate these by sorting the input list and the reversing the result if the input has \, but there's a better way:

```<code>r       e# Read incoming direction.
"SWEN"  e# Push input list for transliteration.
_e!     e# Duplicate and get all permutations. The way, `e!` is implemented, it
        e# always gives the permutations in sort order, regardless of the order
        e# of the input set. Specifically that means that "ENSW" will be first
        e# and "WSNE" will be last in this list.
r       e# Read the mirror.
'/#     e# Find the index of / in this string. If the mirror is '/', then this
        e# gives 0. Otherwise, this gives -1, indicating that '/' was not found.
=       e# Select the corresponding permutation. Indexing is zero-based and
        e# cyclic so that 0 (input '/') gives the first permutation "ENSW" and
        e# -1 (input '\') gives the last permutation "WSNE".
er      e# Perform the transliteration on the incoming direction.
        e# Printing is implicit.
</code>```

Title: Mirror, Mirror, in the Code

Body:
CJam, 17 bytes

r"SWEN"_e!r'/#=er

Input is space-separated.

Try it online! (As a linefeed-separated test suite.)

This is the solution I found before posting the challenge. Not as short as Jonathan's cyclic indexing, but I thought this approach is quite interesting (and novel).

Explanation

The goal is use transliteration (i.e. using a character-to-character mapping) to replace the input character with the output character. To do this, we need to select the correct map based on whether the mirror is / or \. We'll map from the SWEN list to another one which we'll select conditionally. If the input list is SWEN, the two output maps need to be the following:

in  SWEN
/   ENSW
\   WSNE

Note that these are in sorted and reverse-sorted order (which is why we chose the seemingly random SWEN order as the input set). We could generate these by sorting the input list and the reversing the result if the input has \, but there's a better way:

r       e# Read incoming direction.
"SWEN"  e# Push input list for transliteration.
_e!     e# Duplicate and get all permutations. The way, `e!` is implemented, it
        e# always gives the permutations in sort order, regardless of the order
        e# of the input set. Specifically that means that "ENSW" will be first
        e# and "WSNE" will be last in this list.
r       e# Read the mirror.
'/#     e# Find the index of / in this string. If the mirror is '/', then this
        e# gives 0. Otherwise, this gives -1, indicating that '/' was not found.
=       e# Select the corresponding permutation. Indexing is zero-based and
        e# cyclic so that 0 (input '/') gives the first permutation "ENSW" and
        e# -1 (input '\') gives the last permutation "WSNE".
er      e# Perform the transliteration on the incoming direction.
        e# Printing is implicit.


答:
Octave, 30 bytes

Used the same order of arguments as Jonathan Allan.

Takes the input as two-character string 'W\'.

```<code>@(x)['NESSWNW'](mod(sum(x),8))
</code>```

Try it online.

Title: Mirror, Mirror, in the Code

Body:
Octave, 30 bytes

Used the same order of arguments as Jonathan Allan.

Takes the input as two-character string 'W\'.

@(x)['NESSWNW'](mod(sum(x),8))

Try it online.


答:
SED 48 (42 + 1 for -r) 43

Saved 5 thanks to Martin Ender♦

```<code>s,N/|S\\,W,;s,E/|W\\,S,;s,N.|S/,E,;s,..,N,
</code>```

Takes input as a two character string.

Title: Mirror, Mirror, in the Code

Body:
SED 48 (42 + 1 for -r) 43

Saved 5 thanks to Martin Ender♦

s,N/|S\\,W,;s,E/|W\\,S,;s,N.|S/,E,;s,..,N,

Takes input as a two character string.


问:
Is this a Smith number?

Challenge description

A Smith number is a composite number whose sum of digits is equal to the sum of sums of digits of its prime factors. Given an integer N, determine if it's a Smith number or not.

The first few Smith numbers are 4, 22, 27, 58, 85, 94, 121, 166, 202, 265, 274, 319, 346, 355, 378, 382, 391, 438 (sequence A006753 in OEIS).

Sample input / output

```<code>18: False (sum of digits: 1 + 8 = 9; factors: 2, 3, 3; sum of digits of factors: 2 + 3 + 3 = 8)
22: True
13: False (meets the digit requirement, but is prime)
666: True (sum of digits: 6 + 6 + 6 = 18; factors: 2, 3, 3, 37; sum of digits of factors: 2 + 3 + 3 + 3 + 7 = 18)
-265: False (negative numbers can't be composite)
0: False (not composite)
1: False (not composite)
4937775: True
</code>```

Notes

Your code can be a function (method) or a full working program,

Instead of words like True and False, you can use any truthy and falsy values, as long as it's clear what they are,

This is a code-golf challenge, so make your code as short as possible!

答:
05AB1E, <s>11</s> 17 bytes

```<code>X›0si¹ÒSO¹SOQ¹p_&
</code>```

Explanation

```<code>X›0si              # if input is less than 2 then false, else
       SO          # sum of digits
     ¹Ò            # of prime factors with duplicates
            Q      # equal to
          SO       # sum of digits
         ¹         # of input
                &  # and
             ¹p_   # input is not prime
</code>```

Try it online!

Title: Is this a Smith number?

Body:
05AB1E, <s>11</s> 17 bytes

X›0si¹ÒSO¹SOQ¹p_&

Explanation

X›0si              # if input is less than 2 then false, else
       SO          # sum of digits
     ¹Ò            # of prime factors with duplicates
            Q      # equal to
          SO       # sum of digits
         ¹         # of input
                &  # and
             ¹p_   # input is not prime

Try it online!


答:
Pyke, 16 bytes

```<code>Pm[`mbs(sQ[qRlt*
</code>```

Try it here!

Title: Is this a Smith number?

Body:
Challenge description

A Smith number is a composite number whose sum of digits is equal to the sum of sums of digits of its prime factors. Given an integer N, determine if it's a Smith number or not.

The first few Smith numbers are 4, 22, 27, 58, 85, 94, 121, 166, 202, 265, 274, 319, 346, 355, 378, 382, 391, 438 (sequence A006753 in OEIS).

Sample input / output

```<code>18: False (sum of digits: 1 + 8 = 9; factors: 2, 3, 3; sum of digits of factors: 2 + 3 + 3 = 8)
22: True
13: False (meets the digit requirement, but is prime)
666: True (sum of digits: 6 + 6 + 6 = 18; factors: 2, 3, 3, 37; sum of digits of factors: 2 + 3 + 3 + 3 + 7 = 18)
-265: False (negative numbers can't be composite)
0: False (not composite)
1: False (not composite)
4937775: True
</code>```

Notes

Your code can be a function (method) or a full working program,

Instead of words like True and False, you can use any truthy and falsy values, as long as it's clear what they are,

This is a code-golf challenge, so make your code as short as possible!

Body:
Pyke, 16 bytes

Pm[`mbs(sQ[qRlt*

Try it here!


答:
Octave, <s>80</s> 78 bytes

```<code>t=num2str(factor(x=input('')))-48;disp(any(t<0)&~sum([num2str(x)-48 -t(t>0)]))
</code>```

Explanation:

```<code>factor(x=input(''))                 % Take input, store as x and factor it
num2str(factor(x=input('')))-48     % Convert it to an array (123 -> [1 2 3])
                                    % and store as t
any(t<0)                            % Check if there are several prime factors
                                    % [2 3] -> [2 -16 3]
sum([num2str(x)-48 -t(t>0)])        % Check if sum of prime factor
                                    % is equal the sum of digits
</code>```

Try it online.

Title: Is this a Smith number?

Body:
Octave, <s>80</s> 78 bytes

t=num2str(factor(x=input('')))-48;disp(any(t<0)&~sum([num2str(x)-48 -t(t>0)]))

Explanation:

factor(x=input(''))                 % Take input, store as x and factor it
num2str(factor(x=input('')))-48     % Convert it to an array (123 -> [1 2 3])
                                    % and store as t
any(t<0)                            % Check if there are several prime factors
                                    % [2 3] -> [2 -16 3]
sum([num2str(x)-48 -t(t>0)])        % Check if sum of prime factor
                                    % is equal the sum of digits

Try it online.


问:
Write a program that always outputs "2012" - even if it's modified!
This idea is not mine, though I don't know where it originated. I once met it in a programming contest very long ago (1998, if I remember correctly). The task is to write a program in your favorite language that outputs 2012 and only 2012. The catch is that the program must still output 2012 after any one of its characters is modified. The modification can be either insertion, deletion or replacement. Of course, the modification will be such that the program is still syntactically valid.

Since I don't know all the programming languages, I have to ask the audience to help me and test the answers submitted.

Added: Many have commented that my definition of acceptable modifications is too vague. Here's my second attempt: The allowed modifications will leave your program syntactically valid and will not cause it to crash. There, I think that should cover all the compile-time, link-time and run-time errors. Though I'm sure that there will be some odd edge case in some language anyway, so when that comes up we'll look at it individually.

答:
Excel, 14 characters (cheating slightly):

```<code>{=2012} (in a 2x1 array with one cell hidden)
</code>```

Any valid change to the array will affect the contents of both cells, and attempting to change just one cell triggers an error message.

Of course, this breaks down if you take the view that it's really only one formula, as opposed to 2 formulas that are constrained to be identical.

Body:
Excel, 14 characters (cheating slightly):

{=2012} (in a 2x1 array with one cell hidden)

Any valid change to the array will affect the contents of both cells, and attempting to change just one cell triggers an error message.

Of course, this breaks down if you take the view that it's really only one formula, as opposed to 2 formulas that are constrained to be identical.


答:
Brachylog, 19 bytes

```<code>@e+S,?$pPl>1,P@ec+S
</code>```

Try it online!

Explanation

```<code>@e+S,                 S is the sum of the digits of the input.
     ?$pP             P is the list of prime factors of the input.
        Pl>1,         There are more than 1 prime factors.
             P@e      Split each prime factor into a list of digits.
                c     Flatten the list.
                 +S   The sum of this list of digits must be S.
</code>```

Title: Is this a Smith number?

Body:
Brachylog, 19 bytes

@e+S,?$pPl>1,P@ec+S

Try it online!

Explanation

@e+S,                 S is the sum of the digits of the input.
     ?$pP             P is the list of prime factors of the input.
        Pl>1,         There are more than 1 prime factors.
             P@e      Split each prime factor into a list of digits.
                c     Flatten the list.
                 +S   The sum of this list of digits must be S.


Title: Mirror, Mirror, in the Code

Body:
Two-dimensional programming languages often have mirror commands like / and \ to redirect the instruction pointer on the grid:

```<code>>>>>\
    v
    v
<<<</
</code>```

In this challenge, you're given an incoming direction and a mirror and you need to determine the outgoing direction.

Rules

The incoming direction will be given as one of the characters NESW and the mirror will be given as either / or \. You may receive these in any order. You must use uppercase letters.

You may take input in any convenient format, including a two-character string, a string using some separator between the characters, a pair of characters in a list, or even a pair of singleton strings. If you do use a string with separator, the separator cannot use any of the characters NWSE\/.

Output should be a character from NESW or single-character string.

You may write a program or a function and use any of the our standard methods of receiving input and providing output.

You may use any programming language, but note that these loopholes are forbidden by default.

This is code-golf, so the shortest valid answer – measured in bytes – wins.

Test Cases

There are only 8 possible inputs you need to handle, so there is no excuse for not testing your code on all of them:

```<code>N /   -->   W
N \   -->   E
E /   -->   S
E \   -->   N
S /   -->   E
S \   -->   W
W /   -->   N
W \   -->   S
</code>```

Body:
C, 81 bytes

f(char*a){return a!="N/"&a!="S\\"?a!="N\\"&a!="S/"?a!="W\\"&a!="E/"?78:83:69:87;}

Usage

main()
{
    printf("N/ \t %c\n",f("N/"));
    printf("N\\\t %c\n",f("N\\"));
    printf("E/ \t %c\n",f("E/"));
    printf("E\\\t %c\n",f("E\\"));
    printf("S/ \t %c\n",f("S/"));
    printf("S\\\t %c\n",f("S\\"));
    printf("W/ \t %c\n",f("W/"));
    printf("W\\\t %c\n",f("W\\"));
}

Output:

N/      : W
N\      : E
E/      : S
E\      : N
S/      : E
S\      : W
W/      : N
W\      : S


问:
Shortest infinite loop producing no output
Your task is to create the shortest infinite loop!

The point of this challenge is to create an infinite loop producing no output, unlike its possible duplicate. The reason to this is because the code might be shorter if no output is given.

Rules

Each submission must be a full program.

You must create the shortest infinite loop.

Even if your program runs out of memory eventually, it is still accepted as long as it is running the whole time from the start to when it runs out of memory. Also when it runs out of memory, it should still not print anything to STDERR.

The program must take no input (however, reading from a file is allowed), and should not print anything to STDOUT. Output to a file is also forbidden.

The program must not write anything to STDERR.

Feel free to use a language (or language version) even if it's newer than this challenge.
-Note that there must be an interpreter so the submission can be tested. It is allowed (and even encouraged) to write this interpreter yourself for a previously unimplemented language. :D

Submissions are scored in bytes, in an appropriate (pre-existing) encoding, usually (but not necessarily) UTF-8. Some languages, like Folders, are a bit tricky to score - if in doubt, please ask on Meta.

This is not about finding the language with the shortest infinite loop program. This is about finding the shortest infinite loop program in every language. Therefore, I will not accept an answer.

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

There should be a website such as Wikipedia, Esolangs, or GitHub for the language. For example, if the language is CJam, then one could link to the site in the header like #[CJam](http://sourceforge.net/p/cjam/wiki/Home/), X bytes.

Standard loopholes are not allowed.

(I have taken some of these rules from Martin Büttner's "Hello World" challenge)

Please feel free to post in the comments to tell me how this challenge could be  improved.

Catalogue

This is a Stack Snippet which generates both an alphabetical catalogue of the used languages, and an overall leaderboard. To make sure your answer shows up, please start it with this Markdown header:

```<code># Language name, X bytes
</code>```

Obviously replacing Language name and X bytes with the proper items. If you want to link to the languages' website, use this template, as posted above:

```<code>#[Language name](http://link.to/the/language), X bytes
</code>```

Now, finally, here's the snippet: (Try pressing "Full page" for a better view.)

var QUESTION_ID=59347;var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";var COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk";var OVERRIDE_USER=41805;var answers=[],answers_hash,answer_ids,answer_page=1,more_answers=true,comment_page;function answersUrl(index){return"//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"//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,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\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,});else console.log(body)});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;lang=jQuery(''+lang+'').text();languages[lang]=languages[lang]||{lang:a.language,lang_raw:lang,user:a.user,size:a.size,link:a.link}});var langs=[];for(var lang in languages)if(languages.hasOwnProperty(lang))langs.push(languages[lang]);langs.sort(function(a,b){if(a.lang_raw.toLowerCase()>b.lang_raw.toLowerCase())return 1;if(a.lang_raw.toLowerCase()<b.lang_raw.toLowerCase())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:500px;float:left}#language-list{padding:10px;padding-right:40px;width:500px;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">

Shortest Solution by Language

Language	User	Score

Leaderboard

	Author	Language	Size

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

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

```

答:
Ru, 4 bytes

```<code>¿Ϟ{}
</code>```

¿ call a function while koppa is not 0/nil/false. But since Ϟ also return its argument, it's possible to chain ¿ and Ϟ.

Body:
Ru, 4 bytes

¿Ϟ{}

¿ call a function while koppa is not 0/nil/false. But since Ϟ also return its argument, it's possible to chain ¿ and Ϟ.