答:
Retina, <s>38</s> 31 bytes

Byte count assumes ISO 8859-1 encoding.

```<code>(.+)(?=.*¶\1$)
·
1>`·|¶.+

T`·¶
</code>```

The trailing linefeed is significant. Input format is both strings separated with a linefeed.

Try it online! The first line allows running several test cases at once (for the test suite, use ; to separate the strings and linefeeds to separate test cases; the first line takes care of the conversion).

Explanation

```<code>(.+)(?=.*¶\1$)
·
</code>```

In this first step we replace all occurrences of the toggle string in the main string with ·. We need to insert these markers so that we can determine afterwards if any substitution happened.

```<code>1>`·|¶.+

</code>```

This is another substitution which removes a · marker, or the second line (including the separating linefeed). However, the 1> is a limit which means that only matches after the first are considered. Hence, if the toggle string did not occur in the main string, we won't have inserted any ·, so the second line will be the first match and won't be removed. Otherwise, we remove the second line along with all but the first marker.

```<code>T`·¶
</code>```

While this uses a transliteration stage, it's also used simply for removing characters. In particular, we move both · and linefeeds. We need the first one, in case there was a match (because then the first · will have been left behind by the previous stage) and we need the second one in case there wasn't a match (to join the two lines together and thereby append the toggle string to the main string).

Title: Toggle a string

Body:
Retina, <s>38</s> 31 bytes

Byte count assumes ISO 8859-1 encoding.

(.+)(?=.*¶\1$)
·
1>`·|¶.+

T`·¶

The trailing linefeed is significant. Input format is both strings separated with a linefeed.

Try it online! The first line allows running several test cases at once (for the test suite, use ; to separate the strings and linefeeds to separate test cases; the first line takes care of the conversion).

Explanation

(.+)(?=.*¶\1$)
·

In this first step we replace all occurrences of the toggle string in the main string with ·. We need to insert these markers so that we can determine afterwards if any substitution happened.

1>`·|¶.+

This is another substitution which removes a · marker, or the second line (including the separating linefeed). However, the 1> is a limit which means that only matches after the first are considered. Hence, if the toggle string did not occur in the main string, we won't have inserted any ·, so the second line will be the first match and won't be removed. Otherwise, we remove the second line along with all but the first marker.

T`·¶

While this uses a transliteration stage, it's also used simply for removing characters. In particular, we move both · and linefeeds. We need the first one, in case there was a match (because then the first · will have been left behind by the previous stage) and we need the second one in case there wasn't a match (to join the two lines together and thereby append the toggle string to the main string).


问:
Toggle a string

The challenge involve simply toggling a string within another string.

Explanation

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

Rules

All string are composed of printable ASCII characters

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

The main string can be empty.

The toggle string cannot be empty.

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

The shortest answer wins.

Examples

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

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

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

Tests cases

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

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

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

答:
Python (3.4): <s>55</s> <s>54</s> <s>47</s> 44 Bytes

```<code>lambda m,t:m.replace(t,'')if t in m else m+t
</code>```

Testing:

```<code>toggle=lambda m,t:m.replace(t,'')if t in m else m+t
print('', 'a', toggle('','a'))
print('a', 'a', toggle('a','a'))
print('b', 'a', toggle('b','a'))
print('ab', 'a', toggle('ab','a'))
print('aba', 'a', toggle('aba','a'))
print('ababa', 'aba', toggle('ababa','aba'))
</code>```

The Test output

```<code> a a
a a
b a ba
ab a b
aba a b
ababa aba ba
</code>```

<s>Using a def would be longer because you have to use a return statement, if it were possible without return it would save 2 Bytes</s>
Since explicit declaration of the function is not needed (sorry I didn't know that) 7 Bytes were saved.

ContentLicense: CC BY-SA 3.0

Title: Toggle a string

Body:
Python (3.4): <s>55</s> <s>54</s> <s>47</s> 44 Bytes

lambda m,t:m.replace(t,'')if t in m else m+t

Testing:

toggle=lambda m,t:m.replace(t,'')if t in m else m+t
print('', 'a', toggle('','a'))
print('a', 'a', toggle('a','a'))
print('b', 'a', toggle('b','a'))
print('ab', 'a', toggle('ab','a'))
print('aba', 'a', toggle('aba','a'))
print('ababa', 'aba', toggle('ababa','aba'))

The Test output

 a a
a a
b a ba
ab a b
aba a b
ababa aba ba

<s>Using a def would be longer because you have to use a return statement, if it were possible without return it would save 2 Bytes</s>
Since explicit declaration of the function is not needed (sorry I didn't know that) 7 Bytes were saved.


答:
Java 8, 65 bytes

```<code>BinaryOperator<String>l=(m,t)->m.contains(t)?m.replace(t,""):m+t;
</code>```

The same logic as the Java 7 solution, written with a lambda.

Try it here

Title: Toggle a string

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

Explanation

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

Rules

All string are composed of printable ASCII characters

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

The main string can be empty.

The toggle string cannot be empty.

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

The shortest answer wins.

Examples

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

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

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

Tests cases

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

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

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

Body:
Java 8, 65 bytes

BinaryOperator<String>l=(m,t)->m.contains(t)?m.replace(t,""):m+t;

The same logic as the Java 7 solution, written with a lambda.

Try it here


问:
Randomly Assign People to Tasks
The challenge is to assign people to tasks randomly~.
From stdin you get 2 lines. Line one is a comma-separated list of names. Line 2 is a comma-separated list of jobs.
The output required is one line per task person combo.
The line should be formatted as Name:task.
If there are not enough people for jobs or vice verse then they will not be output.

~ Randomly is defined as each run with the same input has a reasonably different output.

Example Input:

```<code>Bob,John,Susan,Josie,Kim,Tom
Bins,Floor,Windows
</code>```

Example Output:

```<code>Bob:Windows
Susan:Bins
Kim:Floor
</code>```

答:
Java 7, <s>240</s> <s>239</s> 238 bytes

```<code>import java.util.*;class M{public static void main(String[]a){String[]p=a[0].split(",");List j=new ArrayList(Arrays.asList(a[1].split(",")));for(int i=0;j.size()>0;)System.out.println(p[i++]+":"+j.remove((int)(Math.random()*j.size())));}}
</code>```

Can most likely be golfed more with some arrays magic, instead of List j=new ArrayList(Arrays.asList(a[1].split(",")));..

Ungolfed:

Try it here

```<code>import java.util.*;

class M{
    public static void main(String[] a){
        String[] p = a[0].split(",");
        List j = new ArrayList(Arrays.asList(a[1].split(",")));
        for(int i = 0; j.size() > 0;){
            System.out.println(p[i++] + ":" + j.remove((int)(Math.random() * j.size())));
        }
    }
}
</code>```

Title: Randomly Assign People to Tasks

Body:
Java 7, <s>240</s> <s>239</s> 238 bytes

import java.util.*;class M{public static void main(String[]a){String[]p=a[0].split(",");List j=new ArrayList(Arrays.asList(a[1].split(",")));for(int i=0;j.size()>0;)System.out.println(p[i++]+":"+j.remove((int)(Math.random()*j.size())));}}

Can most likely be golfed more with some arrays magic, instead of List j=new ArrayList(Arrays.asList(a[1].split(",")));..

Ungolfed:

Try it here

import java.util.*;

class M{
    public static void main(String[] a){
        String[] p = a[0].split(",");
        List j = new ArrayList(Arrays.asList(a[1].split(",")));
        for(int i = 0; j.size() > 0;){
            System.out.println(p[i++] + ":" + j.remove((int)(Math.random() * j.size())));
        }
    }
}


问:
"Hello, World!"
So... uh... this is a bit embarrassing. But we don't have a plain "Hello, World!" challenge yet (despite having 35 variants tagged with hello-world, and counting). While this is not the most interesting code golf in the common languages, finding the shortest solution in certain esolangs can be a serious challenge. For instance, to my knowledge it is not known whether the shortest possible Brainfuck solution has been found yet.

Furthermore, while all of <s>Wikipedia</s> (the Wikipedia entry has been deleted but there is a copy at archive.org
), esolangs and Rosetta Code have lists of "Hello, World!" programs, none of these are interested in having the shortest for each language (there is also this GitHub repository). If we want to be a significant site in the code golf community, I think we should try and create the ultimate catalogue of shortest "Hello, World!" programs (similar to how our basic quine challenge contains some of the shortest known quines in various languages). So let's do this!

The Rules

Each submission must be a full program.

The program must take no input, and print Hello, World! to STDOUT (this exact byte stream, including capitalization and punctuation) plus an optional trailing newline, and nothing else.

The program must not write anything to STDERR.

If anyone wants to abuse this by creating a language where the empty program prints Hello, World!, then congrats, they just paved the way for a very boring answer.

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.

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 "Hello, World!" program. This is about finding the shortest "Hello, World!" program in every language. Therefore, I will not mark any answer as "accepted".

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 Brainfuck-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.

As a side note, please don't downvote boring (but valid) answers in languages where there is not much to golf - these are still useful to this question as it tries to compile a catalogue as complete as possible. However, do primarily upvote answers in languages where the authors actually had to put effort into golfing the code.

For inspiration, check the Hello World Collection.

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 = 55422; // 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

```

答:
Scratch, 15 bytes

(scoring used)

Makes the sprite say "Hello, World!"  Can't get much simpler than that.

ContentLicense: CC BY-SA 4.0

Title: "Hello, World!"


答:
Jelly, 7 bytes

```<code>œṣȮ⁸e⁹ẋ
</code>```

Try it online!

How it works

```<code>œṣȮ⁸e⁹ẋ  Main link. Arguments: s (string), t (toggle string)

œṣ       Split s at occurrences of t.
  Ȯ      Print the result.
   ⁸e    Check if s occurs in the split s. Yields 1 (true) or 0 (false).
     ⁹ẋ  Repeat t that many times.
</code>```

Title: Toggle a string

Body:
Jelly, 7 bytes

œṣȮ⁸e⁹ẋ

Try it online!

How it works

œṣȮ⁸e⁹ẋ  Main link. Arguments: s (string), t (toggle string)

œṣ       Split s at occurrences of t.
  Ȯ      Print the result.
   ⁸e    Check if s occurs in the split s. Yields 1 (true) or 0 (false).
     ⁹ẋ  Repeat t that many times.


答:
Ruby, <s>35</s> <s>37</s> 28 bytes

->m,t{m[t]?m.gsub(t,''):m+t}
```

Hooray for string interpolation! It even works in regexes. The rest is simple: if the string in t matches to m, replace t with '', else return m+t.

Edit: Fixed a bug.

Edit: I applied Kevin Lau's suggestion, but it appears that I have reached the same algorithm as the one used in Luis Masuelli's answer.

Title: Toggle a string

Body:
Ruby, <s>35</s> <s>37</s> 28 bytes

->m,t{m[t]?m.gsub(t,''):m+t}

Hooray for string interpolation! It even works in regexes. The rest is simple: if the string in t matches to m, replace t with '', else return m+t.

Edit: Fixed a bug.

Edit: I applied Kevin Lau's suggestion, but it appears that I have reached the same algorithm as the one used in Luis Masuelli's answer.


答:
Scala, 72 70 bytes

```<code>def x(m:String,s:String)={val r=m.replaceAll(s,"");if(r==m)m+s else r}
</code>```

Online interpreter: www.tryscala.com

Title: Toggle a string

Body:
Scala, 72 70 bytes

def x(m:String,s:String)={val r=m.replaceAll(s,"");if(r==m)m+s else r}

Online interpreter: www.tryscala.com


答:
Julia, <s>33</s> 31 bytes

s|t=(r=replace(s,t,""))t^(s==r)
```

Try it online!

Title: Toggle a string

Body:
Julia, <s>33</s> 31 bytes

s|t=(r=replace(s,t,""))t^(s==r)

Try it online!


答:
TSQL, 143 129 121 Bytes

```<code>DECLARE @1 VARCHAR(10)='',@2 VARCHAR(10)='a'SELECT CASE WHEN @1 LIKE'%'+@2+'%'THEN REPLACE(@1,@2,'')ELSE CONCAT(@1,@2)END
</code>```

Readable:

```<code>   DECLARE @1 VARCHAR(10) = ''
    , @2 VARCHAR(10) = 'a'

SELECT CASE WHEN @1 LIKE '%' + @2 + '%'
            THEN REPLACE(@1, @2, '')
            ELSE CONCAT (@1, @2)
            END
</code>```

Live Demo

114 Bytes with strictly 1 character input

```<code>DECLARE @1 CHAR(1) = 'a'
    , @2 CHAR(1) = '.'

SELECT CASE WHEN @1 LIKE '%' + @2 + '%'
            THEN REPLACE(@1, @2, '')
            ELSE CONCAT (@1, @2) END
</code>```

Title: Toggle a string

Body:
TSQL, 143 129 121 Bytes

DECLARE @1 VARCHAR(10)='',@2 VARCHAR(10)='a'SELECT CASE WHEN @1 LIKE'%'+@2+'%'THEN REPLACE(@1,@2,'')ELSE CONCAT(@1,@2)END

Readable:

   DECLARE @1 VARCHAR(10) = ''
    , @2 VARCHAR(10) = 'a'

SELECT CASE WHEN @1 LIKE '%' + @2 + '%'
            THEN REPLACE(@1, @2, '')
            ELSE CONCAT (@1, @2)
            END

Live Demo

114 Bytes with strictly 1 character input

DECLARE @1 CHAR(1) = 'a'
    , @2 CHAR(1) = '.'

SELECT CASE WHEN @1 LIKE '%' + @2 + '%'
            THEN REPLACE(@1, @2, '')
            ELSE CONCAT (@1, @2) END


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

Each of these will hit (True):

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

>O.
...

v....
O....

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

These will miss (False):

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

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

.O.
...
.v.

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

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

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

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

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

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

```

答:
Julia (no regex), 98

```<code>a->(c=rotr90(a,findlast("i1Q/",sum(a-46)));
    f(n)=find(any(c.!='.',n));b=c[f(2),f(1)];
    (b'*b)[1]==97)
</code>```

Function operating on an array of chars, normalizing by rotation, removing rows and columns containing only dots by range indexing and finally checking for location of 'O' taking into account if the remainder b is a column or row vector using matrix multiplication.

Try it online

Title: Will the beam hit?

Body:
Julia (no regex), 98

a->(c=rotr90(a,findlast("i1Q/",sum(a-46)));
    f(n)=find(any(c.!='.',n));b=c[f(2),f(1)];
    (b'*b)[1]==97)

Function operating on an array of chars, normalizing by rotation, removing rows and columns containing only dots by range indexing and finally checking for location of 'O' taking into account if the remainder b is a column or row vector using matrix multiplication.

Try it online


问:
Three Indistinguishable Dice

Given three dice rolls (integer values from 1-6) in sorted order (so as to be indistinguishable), convert them to the sum of two fair dice with an identical distribution.

The answer for three to one is summing them all, modulo 6. The end-result is a perfectly flat distribution, where each of the six numbers are equally likely (just like a single die).

It's easy to do this for three-to-one, by summing them all modulo 6. The end-result is a perfectly flat distribution, where each of the six numbers are equally likely (just like a single die).  Your challenge is to do the same for three-to-two.

Inspired by standupmath's The Three Indistinguishable Dice Puzzle. A follow-up "solution" video was also posted, but arguing about "elegance" of one way or another is a bit subjective. Counting characters isn't. :D

Instructions

Write a program or function that accepts three sorted integers/digits, 1-6, and outputs or returns a single integer, 2-12, such that, for the 216 possible inputs, the outputs are distributed as:

```<code> 222222
 333333333333
 444444444444444444
 555555555555555555555555
 666666666666666666666666666666
 777777777777777777777777777777777777
 888888888888888888888888888888
 999999999999999999999999
 AAAAAAAAAAAAAAAAAA
 BBBBBBBBBBBB
 CCCCCC
</code>```

(I've used hex to keep to single characters; decimal output is fine)

Because the dice are indistinguishable, there is no intrinsic order to them, hence the sorted input. You cannot simply "drop the third" because that would be ambiguous.

Details

Score is the length of the program in bytes

The program can be a function that's called somehow, or executable script that reads from stdin, or whatever's convienent.

No "rerolling" by getting entropy from another source

Example (and test)

Rather than doing any sort of probabilistic testing, it's easy enough to rip through the 216 (6³) cases of all the three dice and assert that your function returns each value as many times as it should. It will be called with identical parameters (e.g. the cases 1, 2, 3 and 3, 2, 1, ... are presumed indistinguishable and are (arbitrarily) converted to 1, 2, 3).

An example answer (extremely brute-force and inefficient) and test suite is provided below in Python. Hopefully the test bits are clear enough to port to your language of choice, though doing stdin/stdout would be a bit different. The testing code is just for testing and not scored (though if you want to provide it for other users of your language or I/O method, that might be useful).

```<code># 6x6 lists of numbers with digits sorted
LUT = [
    [[124], [133, 166], [346], [223, 355], [256], [115, 445]],
    [[233, 266], [125], [224, 455], [134], [116, 446], [356]],
    [[126], [111, 333, 555, 225], [234], [144, 366], [456], [135]],
    [[112, 244], [235], [334, 466], [145], [226, 556], [136]],
    [[146], [122, 155], [236], [113, 344], [245], [335, 566]],
    [[246], [123], [114, 336], [345], [222, 444, 666, 255], [156]],
]

def three2two(rolls):
    look_for = int('{}{}{}'.format(*sorted(rolls)))
    for i in range(6):
        for j in range(6):
            if look_for in LUT[i][j]:
                return i + j + 2

# fair distribution of the sum of two dice multiplied by 6 (because each should be hit 6x)
expected_counts = {
    2: 6,   12: 6,
    3: 12,  11: 12,
    4: 18,  10: 18,
    5: 24,   9: 24,
    6: 30,   8: 30,
    7: 36,
}

d = [1, 2, 3, 4, 5, 6]
for i in d:
    for j in d:
        for k in d:
            ijk = sorted([i, j, k])
            result = three2two(ijk)
            expected_counts[result] -= 1

for key in expected_counts:
    assert expected_counts[key] == 0
</code>```

答:
CJam, 37 35 bytes

Probably not golfed well. But beat Pyth.

```<code>8aq~\;[_2$>8+@7+@:U2+1$([8U4$7]])er
</code>```

Try it here.

Title: Three Indistinguishable Dice

Body:
CJam, 37 35 bytes

Probably not golfed well. But beat Pyth.

8aq~\;[_2$>8+@7+@:U2+1$([8U4$7]])er

Try it here.


答:
Clojure (no regex), 293 bytes

```<code>(defn z[f](let[v(sort(keep-indexed(fn[i v](if(some #{v}[\v\>\<\^\O])[(if(= v\O)\& v)i]))f))l(+(.indexOf f"\n")1)d((nth v 1)0)q((nth v 1)1)p((nth v 0)1)r(=(quot p l)(quot q l))i(> q p)](cond(= d\^)(and i(=(mod(- q p)l)0))(= d\v)(and(not i)(=(mod(- p q)l)0))(= d\>)(and(not i)r):else(and i r))))
</code>```

Doesn't feel great. Straightforward solution, finding the index of corresponding characters and calculating if they're on the same line.

You can try it here https://ideone.com/m4f2ra

Title: Will the beam hit?

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

Each of these will hit (True):

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

>O.
...

v....
O....

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

These will miss (False):

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

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

.O.
...
.v.

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

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

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

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

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

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

```

Body:
Clojure (no regex), 293 bytes

(defn z[f](let[v(sort(keep-indexed(fn[i v](if(some #{v}[\v\>\<\^\O])[(if(= v\O)\& v)i]))f))l(+(.indexOf f"\n")1)d((nth v 1)0)q((nth v 1)1)p((nth v 0)1)r(=(quot p l)(quot q l))i(> q p)](cond(= d\^)(and i(=(mod(- q p)l)0))(= d\v)(and(not i)(=(mod(- p q)l)0))(= d\>)(and(not i)r):else(and i r))))

Doesn't feel great. Straightforward solution, finding the index of corresponding characters and calculating if they're on the same line.

You can try it here https://ideone.com/m4f2ra


答:
Python 3, 38 bytes

```<code>lambda s,t:(s+t,s.replace(t,""))[t in s]
</code>```

Title: Toggle a string

Body:
Python 3, 38 bytes

lambda s,t:(s+t,s.replace(t,""))[t in s]


问:
Find the number I/O shortest algorithm
Find the shortest function/algorithm to translate these numbers to the ones after the dash:

```<code>0 - 0
1 - 10
2 - 20
3 - 30
4 - 40
5 - 50
6 - 60
7 - 70
8 - 80
9 - 90
10 - 100
11 - 115
12 - 130
13 - 150
14 - 175
15 - 200
16 - 230
17 - 260
18 - 300
19 - 350
20 - 400
</code>```

Every integer higher than 20 is calculated by subtracting 10, calculating the corresponding number like done above and then multiplying that by 4.

Some examples (input will be between []):

```<code>[10] -> 100
[17] -> 260
[21] -> 4*115 -> 460
[32] -> 4*[22] -> 4*(4*130)) -> 2080
</code>```

var QUESTION_ID=80271,OVERRIDE_USER=53878;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="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

```

Title: Find the number I/O shortest algorithm

Body:
Python, 81 bytes

f=lambda n:n>19and 4*f(n-10)or n>10and[23,26,30,35,40,46,52,60,70][n-11]*5or 10*n


答:
Pyth, <s>47</s> 46 bytes

1 byte deletion inspired by Python's deletion of the final item in the lookup table.

```<code>J9L?gb20*4y-bT+?>bT*5@.u+NYj6045983J1-bhT0*Tby
</code>```

Test suite.

Principle

The lookup table I built is [1, 2, 3, 3, 4, 4, 6, 8].

If we start from 1, and then add cumulatively that table:

```<code>1                   = 1
1+1                 = 2
1+1+2               = 4
1+1+2+3             = 7
1+1+2+3+3           = 10
1+1+2+3+3+4         = 14
1+1+2+3+3+4+4       = 18
1+1+2+3+3+4+4+6     = 24
1+1+2+3+3+4+4+6+8   = 32
</code>```

Previous 53-byte solution:

```<code>L?tb+ytbeSmlf!%ydTSydStb1L?>b20*4'-bT+?>bT*5y-bT0*Tb'
</code>```

This needs to be golf... very further. Maybe it would cost less to build a lookup table directly.

Test suite.

Principle

If we subtract ten times the first number from the second number:

```<code>115-110 = 5   = 5*1
130-120 = 10  = 5*2
150-130 = 20  = 5*4
175-140 = 35  = 5*7
200-150 = 50  = 5*10
230-160 = 70  = 5*14
260-170 = 90  = 5*18
300-180 = 120 = 5*24
350-190 = 160 = 5*32
400-200 = 200 = 5*40
</code>```

It corresponds with A120679: 1,2,4,7,10,14,18,24,32,40,...

Title: Find the number I/O shortest algorithm

Body:
Find the shortest function/algorithm to translate these numbers to the ones after the dash:

```<code>0 - 0
1 - 10
2 - 20
3 - 30
4 - 40
5 - 50
6 - 60
7 - 70
8 - 80
9 - 90
10 - 100
11 - 115
12 - 130
13 - 150
14 - 175
15 - 200
16 - 230
17 - 260
18 - 300
19 - 350
20 - 400
</code>```

Every integer higher than 20 is calculated by subtracting 10, calculating the corresponding number like done above and then multiplying that by 4.

Some examples (input will be between []):

```<code>[10] -> 100
[17] -> 260
[21] -> 4*115 -> 460
[32] -> 4*[22] -> 4*(4*130)) -> 2080
</code>```

var QUESTION_ID=80271,OVERRIDE_USER=53878;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="lang-css prettyprint-override"><code>body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
</code>```

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

```

Body:
Pyth, <s>47</s> 46 bytes

1 byte deletion inspired by Python's deletion of the final item in the lookup table.

J9L?gb20*4y-bT+?>bT*5@.u+NYj6045983J1-bhT0*Tby

Test suite.

Principle

The lookup table I built is [1, 2, 3, 3, 4, 4, 6, 8].

If we start from 1, and then add cumulatively that table:

1                   = 1
1+1                 = 2
1+1+2               = 4
1+1+2+3             = 7
1+1+2+3+3           = 10
1+1+2+3+3+4         = 14
1+1+2+3+3+4+4       = 18
1+1+2+3+3+4+4+6     = 24
1+1+2+3+3+4+4+6+8   = 32

Previous 53-byte solution:

L?tb+ytbeSmlf!%ydTSydStb1L?>b20*4'-bT+?>bT*5y-bT0*Tb'

This needs to be golf... very further. Maybe it would cost less to build a lookup table directly.

Test suite.

Principle

If we subtract ten times the first number from the second number:

115-110 = 5   = 5*1
130-120 = 10  = 5*2
150-130 = 20  = 5*4
175-140 = 35  = 5*7
200-150 = 50  = 5*10
230-160 = 70  = 5*14
260-170 = 90  = 5*18
300-180 = 120 = 5*24
350-190 = 160 = 5*32
400-200 = 200 = 5*40

It corresponds with A120679: 1,2,4,7,10,14,18,24,32,40,...


答:
CJam, <s>25</s> 24 bytes

```<code>6Zm*{$e`z}$q~:(a#6bW2t1b
</code>```

This is a port of my Jelly answer.

Try it online! or simulate all 216 outcomes.

Thanks to @jimmy23013 for golfing off 1 byte!

Title: Three Indistinguishable Dice

Body:
Given three dice rolls (integer values from 1-6) in sorted order (so as to be indistinguishable), convert them to the sum of two fair dice with an identical distribution.

The answer for three to one is summing them all, modulo 6. The end-result is a perfectly flat distribution, where each of the six numbers are equally likely (just like a single die).

It's easy to do this for three-to-one, by summing them all modulo 6. The end-result is a perfectly flat distribution, where each of the six numbers are equally likely (just like a single die).  Your challenge is to do the same for three-to-two.

Inspired by standupmath's The Three Indistinguishable Dice Puzzle. A follow-up "solution" video was also posted, but arguing about "elegance" of one way or another is a bit subjective. Counting characters isn't. :D

Instructions

Write a program or function that accepts three sorted integers/digits, 1-6, and outputs or returns a single integer, 2-12, such that, for the 216 possible inputs, the outputs are distributed as:

```<code> 222222
 333333333333
 444444444444444444
 555555555555555555555555
 666666666666666666666666666666
 777777777777777777777777777777777777
 888888888888888888888888888888
 999999999999999999999999
 AAAAAAAAAAAAAAAAAA
 BBBBBBBBBBBB
 CCCCCC
</code>```

(I've used hex to keep to single characters; decimal output is fine)

Because the dice are indistinguishable, there is no intrinsic order to them, hence the sorted input. You cannot simply "drop the third" because that would be ambiguous.

Details

Score is the length of the program in bytes

The program can be a function that's called somehow, or executable script that reads from stdin, or whatever's convienent.

No "rerolling" by getting entropy from another source

Example (and test)

Rather than doing any sort of probabilistic testing, it's easy enough to rip through the 216 (6³) cases of all the three dice and assert that your function returns each value as many times as it should. It will be called with identical parameters (e.g. the cases 1, 2, 3 and 3, 2, 1, ... are presumed indistinguishable and are (arbitrarily) converted to 1, 2, 3).

An example answer (extremely brute-force and inefficient) and test suite is provided below in Python. Hopefully the test bits are clear enough to port to your language of choice, though doing stdin/stdout would be a bit different. The testing code is just for testing and not scored (though if you want to provide it for other users of your language or I/O method, that might be useful).

```<code># 6x6 lists of numbers with digits sorted
LUT = [
    [[124], [133, 166], [346], [223, 355], [256], [115, 445]],
    [[233, 266], [125], [224, 455], [134], [116, 446], [356]],
    [[126], [111, 333, 555, 225], [234], [144, 366], [456], [135]],
    [[112, 244], [235], [334, 466], [145], [226, 556], [136]],
    [[146], [122, 155], [236], [113, 344], [245], [335, 566]],
    [[246], [123], [114, 336], [345], [222, 444, 666, 255], [156]],
]

def three2two(rolls):
    look_for = int('{}{}{}'.format(*sorted(rolls)))
    for i in range(6):
        for j in range(6):
            if look_for in LUT[i][j]:
                return i + j + 2

# fair distribution of the sum of two dice multiplied by 6 (because each should be hit 6x)
expected_counts = {
    2: 6,   12: 6,
    3: 12,  11: 12,
    4: 18,  10: 18,
    5: 24,   9: 24,
    6: 30,   8: 30,
    7: 36,
}

d = [1, 2, 3, 4, 5, 6]
for i in d:
    for j in d:
        for k in d:
            ijk = sorted([i, j, k])
            result = three2two(ijk)
            expected_counts[result] -= 1

for key in expected_counts:
    assert expected_counts[key] == 0
</code>```

Body:
CJam, <s>25</s> 24 bytes

6Zm*{$e`z}$q~:(a#6bW2t1b

This is a port of my Jelly answer.

Try it online! or simulate all 216 outcomes.

Thanks to @jimmy23013 for golfing off 1 byte!


答:
C++11, <s>104</s> <s>95</s> 91 bytes

```<code>int f(int n){int x={23,26,30,35,40,46,52,60,70};return n<11?n*10:n<20?x[n-11]*5:f(n-10)*4;}
</code>```

Simple lookup table and ternary operator fun.

[edit]Thanks!
[edit2]I'm feeling extra stoopid today. Thanks again!

Title: Find the number I/O shortest algorithm

Body:
C++11, <s>104</s> <s>95</s> 91 bytes

int f(int n){int x={23,26,30,35,40,46,52,60,70};return n<11?n*10:n<20?x[n-11]*5:f(n-10)*4;}

Simple lookup table and ternary operator fun.

[edit]Thanks!
[edit2]I'm feeling extra stoopid today. Thanks again!


答:
Java, <s>93</s> 89 bytes

int f(int n){String x="!$(-28>FP";return n<11?n*10:n<20?(x.charAt(n-11)-10)*5:f(n-10)*4;}
```

<p>A translation of the answer in Python combined with the answer in C++, also inspired by this answer in Python.</p>

<h2>Full program:</h2>

<pre class="lang-java prettyprint-override"><code>public class Q80271 {
    int f(int n){String x="!$(-28>FP";return n<11?n*10:n<20?(x.charAt(n-11)-10)*5:f(n-10)*4;}
    public static void main(String args[]){
        int[] testcases = new int[]{
            0,1,2,3,4,5,6,7,8,9,
            10,11,12,13,14,15,16,17,18,19,
            20,21,32
        };
        for(int i=0;i<testcases.length;i++){
            System.out.println(new Q80271().f(testcases[i]));
        }
    }
}
</code>```

Output:

0
10
20
30
40
50
60
70
80
90
100
115
130
150
175
200
230
260
300
350
400
460
2080
```

Title: Find the number I/O shortest algorithm

Body:
Java, <s>93</s> 89 bytes

int f(int n){String x="!$(-28>FP";return n<11?n*10:n<20?(x.charAt(n-11)-10)*5:f(n-10)*4;}

A translation of the answer in Python combined with the answer in C++, also inspired by this answer in Python.

Full program:

public class Q80271 {
    int f(int n){String x="!$(-28>FP";return n<11?n*10:n<20?(x.charAt(n-11)-10)*5:f(n-10)*4;}
    public static void main(String args[]){
        int[] testcases = new int[]{
            0,1,2,3,4,5,6,7,8,9,
            10,11,12,13,14,15,16,17,18,19,
            20,21,32
        };
        for(int i=0;i<testcases.length;i++){
            System.out.println(new Q80271().f(testcases[i]));
        }
    }
}

Output:

0
10
20
30
40
50
60
70
80
90
100
115
130
150
175
200
230
260
300
350
400
460
2080


答:
CJam, 9

```<code>q~:B/2Be]
</code>```

Try it online. Thanks jimmy23013 for chopping off 1 byte :)

Explanation:

```<code>q~     read and evaluate the input (given as 2 quoted strings)
:B     store the toggle string in B
/      split the main string by the toggle string
2Be]   pad the array of pieces to the right with B, up to length 2 (if shorter)
</code>```

Title: Toggle a string

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

Explanation

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

Rules

All string are composed of printable ASCII characters

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

The main string can be empty.

The toggle string cannot be empty.

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

The shortest answer wins.

Examples

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

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

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

Tests cases

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

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

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

Body:
CJam, 9

q~:B/2Be]

Try it online. Thanks jimmy23013 for chopping off 1 byte :)

Explanation:

q~     read and evaluate the input (given as 2 quoted strings)
:B     store the toggle string in B
/      split the main string by the toggle string
2Be]   pad the array of pieces to the right with B, up to length 2 (if shorter)


答:
Javascript ES6, <s>104 103 100 97</s> 93 bytes

```<code> h=a=>{return a<11?a*10:a<20?a*10+c[a-11][1/2,1,2,7/2,5,7,9,12,16]*10:4*h(a-10);},u=p=>h(p[0])
</code>```

usage: call u with the input enclosed in brackets like the OP said. Will golf later.

84 bytes if input is not enclosed in brackets and h() is called directly

thanks to kenny lau -6 bytes

Title: Find the number I/O shortest algorithm

Body:
Javascript ES6, <s>104 103 100 97</s> 93 bytes

 h=a=>{return a<11?a*10:a<20?a*10+c[a-11][1/2,1,2,7/2,5,7,9,12,16]*10:4*h(a-10);},u=p=>h(p[0])

usage: call u with the input enclosed in brackets like the OP said. Will golf later.

84 bytes if input is not enclosed in brackets and h() is called directly

thanks to kenny lau -6 bytes


答:
Auo, 21 bytes

```<code>i.o:['Hello, World!']
</code>```

Title: "Hello, World!"

Body:
So... uh... this is a bit embarrassing. But we don't have a plain "Hello, World!" challenge yet (despite having 35 variants tagged with hello-world, and counting). While this is not the most interesting code golf in the common languages, finding the shortest solution in certain esolangs can be a serious challenge. For instance, to my knowledge it is not known whether the shortest possible Brainfuck solution has been found yet.

Furthermore, while all of <s>Wikipedia</s> (the Wikipedia entry has been deleted but there is a copy at archive.org
), esolangs and Rosetta Code have lists of "Hello, World!" programs, none of these are interested in having the shortest for each language (there is also this GitHub repository). If we want to be a significant site in the code golf community, I think we should try and create the ultimate catalogue of shortest "Hello, World!" programs (similar to how our basic quine challenge contains some of the shortest known quines in various languages). So let's do this!

The Rules

Each submission must be a full program.

The program must take no input, and print Hello, World! to STDOUT (this exact byte stream, including capitalization and punctuation) plus an optional trailing newline, and nothing else.

The program must not write anything to STDERR.

If anyone wants to abuse this by creating a language where the empty program prints Hello, World!, then congrats, they just paved the way for a very boring answer.

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.

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 "Hello, World!" program. This is about finding the shortest "Hello, World!" program in every language. Therefore, I will not mark any answer as "accepted".

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 Brainfuck-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.

As a side note, please don't downvote boring (but valid) answers in languages where there is not much to golf - these are still useful to this question as it tries to compile a catalogue as complete as possible. However, do primarily upvote answers in languages where the authors actually had to put effort into golfing the code.

For inspiration, check the Hello World Collection.

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 = 55422; // 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:
Auo, 21 bytes

i.o:['Hello, World!']


答:
Grin, 15 bytes

```<code>(Hello, World!)
</code>```

Grin is a BF-based language that aims to make it slightly less of a Turing Tarpit.

Title: "Hello, World!"

Body:
Grin, 15 bytes

(Hello, World!)

Grin is a BF-based language that aims to make it slightly less of a Turing Tarpit.


答:
Jelly, 42 bytes

```<code>7568b3+\+\
_⁵ị¢×5+×⁵$
Çµ_⁵ß4×µ20>$?×⁵$>⁵$?
</code>```

Try it online!

Test suite.

Uses the same principle as my answer in Pyth, just that the array is further reduced to [1, 1, 0, 1, 0, 2, 2], which can generate [1, 2, 3, 3, 4, 4, 6, 8], which can generate [1, 2, 4, 7, 10, 14, 18, 24, 32].

Title: Find the number I/O shortest algorithm

Body:
Jelly, 42 bytes

7568b3+\+\
_⁵ị¢×5+×⁵$
Çµ_⁵ß4×µ20>$?×⁵$>⁵$?

Try it online!

Test suite.

Uses the same principle as my answer in Pyth, just that the array is further reduced to [1, 1, 0, 1, 0, 2, 2], which can generate [1, 2, 3, 3, 4, 4, 6, 8], which can generate [1, 2, 4, 7, 10, 14, 18, 24, 32].


问:
Tips for golfing in CJam
CJam is a GolfScript-inspired stack-based golfing language, created by PPCG user aditsu.

So, in the vein of other language-specific tips questions:

What general tips do you have for golfing in CJam? Please post one tip per answer.

答:
Modify an element instead of deleting it

If you need the sum of a list except for the last element, increased by T, instead of:

```<code>W<:+T+
</code>```

You can use:

```<code>WTt:+
</code>```

Or if you just need the sum of a list except for element K, which isn't the first or last element, you can use:

```<code>K0t:+
</code>```

Except for the case there are only 3 elements and K=1, where this is shorter:

```<code>2%:+
</code>```

Title: Tips for golfing in CJam

Body:
Modify an element instead of deleting it

If you need the sum of a list except for the last element, increased by T, instead of:

W<:+T+

You can use:

WTt:+

Or if you just need the sum of a list except for element K, which isn't the first or last element, you can use:

K0t:+

Except for the case there are only 3 elements and K=1, where this is shorter:

2%:+


答:
Haskell, <s>71</s> 66 bytes

```<code>h n|n<11=n*10|n<20=sum$5<$['.'.."DGKPU[ais"!!(n-11)]|1<2=4*h(n-10)
</code>```

Usage example: h 32 -> 2080.

The Haskell version of the algorithm found in many other answers. The results in the middle part for the numbers 11..19 are encoded as strings of consecutive ASCII characters:

```<code>11:   from . to D  (23 chars)
12:   from . to G  (26 chars)
13:   from . to K  (30 chars)
...
</code>```

Every character in the string is mapped to a 5 and summed up.

Edit: @Lynn helped saving 4 bytes. Thanks!

Title: Find the number I/O shortest algorithm

Body:
Haskell, <s>71</s> 66 bytes

h n|n<11=n*10|n<20=sum$5<$['.'.."DGKPU[ais"!!(n-11)]|1<2=4*h(n-10)

Usage example: h 32 -> 2080.

The Haskell version of the algorithm found in many other answers. The results in the middle part for the numbers 11..19 are encoded as strings of consecutive ASCII characters:

11:   from . to D  (23 chars)
12:   from . to G  (26 chars)
13:   from . to K  (30 chars)
...

Every character in the string is mapped to a 5 and summed up.

Edit: @Lynn helped saving 4 bytes. Thanks!


答:
JavaScript (ES6), <s>39</s> 37 bytes

```<code>(s,t,u=s.split(t).join``)=>u==s?s+t:u
</code>```

Title: Toggle a string

Body:
JavaScript (ES6), <s>39</s> 37 bytes

(s,t,u=s.split(t).join``)=>u==s?s+t:u


Title: Find the number I/O shortest algorithm

Body:
PHP, 101 bytes

function f($i){$a=array(23,26,30,35,40,46,52,60,70);return $i<11?$i*10:$i<20?$a[$i-11]*5:f($i-10)*4;}

Huzzah for nested conditional operator!


答:
C#, 63

```<code>string F(string s,string t)=>s.Contains(t)?s.Replace(t,""):s+t;
</code>```

Better than Java :)

Test code:

```<code>public static void Main()
{
    Console.WriteLine(F("", "a"));
    Console.WriteLine(F("a", "a"));
    Console.WriteLine(F("b", "a"));
    Console.WriteLine(F("ab", "a"));
    Console.WriteLine(F("aba", "a"));
    Console.WriteLine(F("ababa", "aba"));
    Console.ReadLine();
}
</code>```

Output:

```<code>a

ba
b
b
ba
</code>```

Title: Toggle a string

Body:
C#, 63

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

Better than Java :)

Test code:

public static void Main()
{
    Console.WriteLine(F("", "a"));
    Console.WriteLine(F("a", "a"));
    Console.WriteLine(F("b", "a"));
    Console.WriteLine(F("ab", "a"));
    Console.WriteLine(F("aba", "a"));
    Console.WriteLine(F("ababa", "aba"));
    Console.ReadLine();
}

Output:

a

ba
b
b
ba


答:
CJam (no regex), 25

Earlier versions were wrong, this will have to do for now:

```<code>q~_z]{'.-HbI%}f%[HF].&~+,
</code>```

Try it online

Explanation:

```<code>q~         read and evaluate the input (given as an array of strings)
_z         copy and transpose
]          put the original grid and transposed grid in an array
{…}f%      map the block to each grid (applying it to each string in each grid)
  '.-      remove all dots (obtaining a string of 0 to 2 chars)
  Hb       convert to base H=17, e.g. ">O" -> 62*17+79=1133
  I%       calculate modulo I=18
[HF]       make an array [17 15]
.&         set-intersect the first array (mapped grid) with 17 and 2nd one with 15
~+         dump and concatenate the results
,          get the array length
</code>```

I tried a few mathematical formulas for distinguishing between "good" and "bad" strings, and for each type of formula I tried plugging in various numbers. I ended up with the HbI% above.

"good" strings for the original grid are ">O" and "O<" and they give the result 17

"good" strings for the transposed grid are "vO" and "O^" and they give the result 15

"bad" strings for both grids are: ">", "<", "^", "v", "O", "", "O>", "Ov", "<O", "^O" and they give the results 8, 6, 4, 10, 7, 0, 1, 3, 1, 3

Title: Will the beam hit?

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

Each of these will hit (True):

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

>O.
...

v....
O....

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

These will miss (False):

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

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

.O.
...
.v.

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

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

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

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

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

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

```

Body:
CJam (no regex), 25

Earlier versions were wrong, this will have to do for now:

q~_z]{'.-HbI%}f%[HF].&~+,

Try it online

Explanation:

q~         read and evaluate the input (given as an array of strings)
_z         copy and transpose
]          put the original grid and transposed grid in an array
{…}f%      map the block to each grid (applying it to each string in each grid)
  '.-      remove all dots (obtaining a string of 0 to 2 chars)
  Hb       convert to base H=17, e.g. ">O" -> 62*17+79=1133
  I%       calculate modulo I=18
[HF]       make an array [17 15]
.&         set-intersect the first array (mapped grid) with 17 and 2nd one with 15
~+         dump and concatenate the results
,          get the array length

I tried a few mathematical formulas for distinguishing between "good" and "bad" strings, and for each type of formula I tried plugging in various numbers. I ended up with the HbI% above.

"good" strings for the original grid are ">O" and "O<" and they give the result 17

"good" strings for the transposed grid are "vO" and "O^" and they give the result 15

"bad" strings for both grids are: ">", "<", "^", "v", "O", "", "O>", "Ov", "<O", "^O" and they give the results 8, 6, 4, 10, 7, 0, 1, 3, 1, 3


答:
JavaScript (ES6), <s>64</s> 51 bytes

```<code>f=n=>n>15?f(n-5)*2:n<11?n*10:f(n-1)+5*"22344"[n-11]
</code>```

Much simpler now that I'm also using @xnor's observation.

Title: Find the number I/O shortest algorithm

Body:
Find the shortest function/algorithm to translate these numbers to the ones after the dash:

```<code>0 - 0
1 - 10
2 - 20
3 - 30
4 - 40
5 - 50
6 - 60
7 - 70
8 - 80
9 - 90
10 - 100
11 - 115
12 - 130
13 - 150
14 - 175
15 - 200
16 - 230
17 - 260
18 - 300
19 - 350
20 - 400
</code>```

Every integer higher than 20 is calculated by subtracting 10, calculating the corresponding number like done above and then multiplying that by 4.

Some examples (input will be between []):

```<code>[10] -> 100
[17] -> 260
[21] -> 4*115 -> 460
[32] -> 4*[22] -> 4*(4*130)) -> 2080
</code>```

var QUESTION_ID=80271,OVERRIDE_USER=53878;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="lang-css prettyprint-override"><code>body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
</code>```

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

```

Body:
JavaScript (ES6), <s>64</s> 51 bytes

f=n=>n>15?f(n-5)*2:n<11?n*10:f(n-1)+5*"22344"[n-11]

Much simpler now that I'm also using @xnor's observation.


问:
How should you arrange your chairs?
You teach a class of students with interesting preferences for how their chairs are arranged. There are 3 very specific requirements they have for how the chairs are arranged:

They most be arranged in a rectangle, even if it means some chairs go empty.

There must be as few empty chairs as possible.

They must be as "squarey" as possible. Squarey-ness is determined by the distance between the width and the height of the rectangle, lower is better. For example, a rectangle that is 4x7 has a squarey-ness of 3.

To be more specific, the "score" of an arrangement is the distance between the width and height plus the number of chairs that would go empty.

Let's take an example. Let's say you have 13 students. You could arrange the chairs any of these ways:

```<code>1x13
2x7
3x5
4x4
</code>```

1x13 is not very squarey. In fact, 1 and 13 are 12 apart, so we give this arrangement 12 points. It also has 0 empty chairs, so we add 0 points, giving this arrangement a score of 12. Not that great.

2x7 is certainly better. 2 and 7 are only 5 apart, so we give this arrangement 5 points. However, if you actually arranged 2 rows of seven chairs, that would take 14 chairs, meaning one chair would be empty. So we add one point, giving this arrangement a score of 6.

We could also do 3x5. 3 and 5 are 2 apart, so +2 points. It takes 15 chairs, meaning we'd have two extra chairs, so another +2 points, for a score of 4.

Last option, 4x4. 4 and 4 are 0 apart, so we give this +0 points. 4x4 takes 16 chairs, so 3 chairs go empty, for a total score of 3. This is the optimal solution.

In case of a tie, the optimal solution is the one with less empty chairs.

The challenge

You must write a program or function that takes an integer and outputs the optimal arrangement of chairs for that number of students. IO can be in any reasonable format. Here is sample output for any number of students from 1 to 100:

```<code>1:  (1, 1)
2:  (1, 2)
3:  (2, 2)
4:  (2, 2)
5:  (2, 3)
6:  (2, 3)
7:  (3, 3)
8:  (3, 3)
9:  (3, 3)
10: (2, 5)
11: (3, 4)
12: (3, 4)
13: (4, 4)
14: (4, 4)
15: (4, 4)
16: (4, 4)
17: (3, 6)
18: (3, 6)
19: (4, 5)
20: (4, 5)
21: (3, 7)
22: (5, 5)
23: (5, 5)
24: (5, 5)
25: (5, 5)
26: (4, 7)
27: (4, 7)
28: (4, 7)
29: (5, 6)
30: (5, 6)
31: (4, 8)
32: (4, 8)
33: (6, 6)
34: (6, 6)
35: (6, 6)
36: (6, 6)
37: (5, 8)
38: (5, 8)
39: (5, 8)
40: (5, 8)
41: (6, 7)
42: (6, 7)
43: (5, 9)
44: (5, 9)
45: (5, 9)
46: (7, 7)
47: (7, 7)
48: (7, 7)
49: (7, 7)
50: (5, 10)
51: (6, 9)
52: (6, 9)
53: (6, 9)
54: (6, 9)
55: (7, 8)
56: (7, 8)
57: (6, 10)
58: (6, 10)
59: (6, 10)
60: (6, 10)
61: (8, 8)
62: (8, 8)
63: (8, 8)
64: (8, 8)
65: (6, 11)
66: (6, 11)
67: (7, 10)
68: (7, 10)
69: (7, 10)
70: (7, 10)
71: (8, 9)
72: (8, 9)
73: (7, 11)
74: (7, 11)
75: (7, 11)
76: (7, 11)
77: (7, 11)
78: (9, 9)
79: (9, 9)
80: (9, 9)
81: (9, 9)
82: (7, 12)
83: (7, 12)
84: (7, 12)
85: (8, 11)
86: (8, 11)
87: (8, 11)
88: (8, 11)
89: (9, 10)
90: (9, 10)
91: (7, 13)
92: (8, 12)
93: (8, 12)
94: (8, 12)
95: (8, 12)
96: (8, 12)
97: (10, 10)
98: (10, 10)
99: (10, 10)
100: (10, 10)
</code>```

As usual, this is code-golf, so standard loopholes apply, and the winner is the shortest answer in bytes.

答:
PHP, 129 bytes

```<code>function f($i){$s=INF;for($x=1;$x<$i;$x++){if($s>$t=(abs($x-$e=ceil($i/$x))-$i+($e*$x))){$s=$t;$d[0]=$x;$d[1]=$e;}}var_dump($d);}
</code>```

Ungolfed:

```<code>function f ($i){
    $s=INF;
    for($x=1; $x<$i; $x++){ // for every number less than the input
        if( $s > $t=( abs($x-$e=ceil($i/$x))-$i+($e*$x) ) ){
            // determine the other dimension, the score, and compare to the minimum score
            $s=$t;
            $d[0]=$x;
            $d[1]=$e;
        }
    }
    var_dump($d);
}
</code>```

Title: How should you arrange your chairs?

Body:
PHP, 129 bytes

function f($i){$s=INF;for($x=1;$x<$i;$x++){if($s>$t=(abs($x-$e=ceil($i/$x))-$i+($e*$x))){$s=$t;$d[0]=$x;$d[1]=$e;}}var_dump($d);}

Ungolfed:

function f ($i){
    $s=INF;
    for($x=1; $x<$i; $x++){ // for every number less than the input
        if( $s > $t=( abs($x-$e=ceil($i/$x))-$i+($e*$x) ) ){
            // determine the other dimension, the score, and compare to the minimum score
            $s=$t;
            $d[0]=$x;
            $d[1]=$e;
        }
    }
    var_dump($d);
}


答:
PHP, 104 bytes

The algorithm that solves this problem is simple and it is probably used by other answers in languages similar to PHP (JavaScript, f.e.):

start with a large value for the initial score; n is large enough (where n is the input value); the score of the arrangement computed on the first iteration (1, n) is (n-1)+0;

iterate for all values of width between 1 and n; compute the minimum height as ceil(n/width), compute the arrangement score using the formula provided in the question (i.e. abs(width - height) + (width * height - n)); if the score is better than the previous best score then remember the width, the height and the new best score; on ties use the value of width * height - n for current arrangement and previous best arrangement to detect the new best arrangement;

that's all.

After golfing, this algorithm produces something like this (wrapped here for readability):

```<code>for($s=$h=$j=$n=$argv[$w=$i=1];$i<=$j;$j=ceil($n/++$i)
{$c=$j-$i+$i*$j-$n;if($c<$s||$c==$s&&$i*$j<$w*$h){$w=$i;$h=$j;$s=$c;}}
echo"$w,$h";
</code>```

It uses 137 bytes (when put on a single line) and it is far from the 104 bytes advertised in the title. The code can probably be shortened by another 2-3 bytes but the big source of improvement is somewhere else: in the details of the algorithm.

The revised algorithm:

There are several places where the algorithm can be improved by removing useless code.

there is no need to iterate the width from 1 to $n; for speed, the width ($i) must iterate between 1 and floor(sqrt($n)) but this makes the code even longer instead of shortening it; but if the width doesn't exceed sqrt($n), the minimum height ($j) will always be larger than sqrt($n) (their product must be at least $n);

the previous statement allows using $i <= $j (width <= height) as the termination condition for loop; this way, the width will iterate from 1 to floor(sqrt($n)) and the height will get values starting with $n and going down to ceil(sqrt($n)) (not necessarily all of them);

knowing that width is always smaller than or equal to the height allow us know that abs(width - height) is always height - width ($j-$i); 5 bytes saved this way;

the input value $n is used in the computation of score (the number of unoccupied seats is width * height - n) but it is not needed; the score does not need to be displayed, it is computed only for comparison of the arrangements; by removing - n from the score formula we save another 3 bytes (the PHP code is -$n) without losing anything;

given the last two statements, the score formula becomes height - width + width * height ($j-$i+$i*$j);

on ties (the score of the current arrangement is the same as the previous best score), the rules say to use the arrangement with less free seats; because width always increases and height always decreases, the height - width part of the score decreases on each step;

if the current score is equal with the previous best score, the previous statements tells us that the number of free seats of the current arrangement is larger than the one of the previous best arrangement; this means the previous best arrangement win the tie;

because the ties are always won by the previous best arrangement, a new arrangement becomes the new best arrangement only when its score is smaller than the previous best; the code that checks for ties is useless and can be removed (||$c==$s&&$i*$j<$w*$h -- a lot of bytes);

because of the removal of -$n from the score's formula, the score for the first arrangement (1x$n) is $n-1+1*$n (i.e. 2*$n-1); the initial value of the best score ($s) can be any value greater than or equal to 2*$n; the first iteration has a better score and it becomes the best arrangement letting the algorithm run without initialization problems.

The new code (104 bytes), after applying the improvements described above is:

```<code>for($s=2*$j=$n=$argv[$i=1];$i<=$j;$j=ceil($n/++$i))
if($s>$c=$j-$i+$i*$j){$w=$i;$h=$j;$s=$c;}echo"$w,$h";
</code>```

It is wrapped here for readability. Prepend the code above with the PHP marker <?php (technically, it is not part of the code), put it into a file (let's say arrange-your-chairs.php) and run it with an integer greater than zero as argument. It will display the width and height of the computed arrangement, separated by comma:

```<code>$ php arrange-your-chairs.php 1001
28,36
</code>```

Another solution (116 bytes)

Another solution that uses a different algorithm:

```<code>for($n=$argv[1];++$j<=$n;)for($i=0;++$i<=$j;)
if($n<=$k=$i*$j)$a["$i,$j"]=($j-$i+$k-$n)*$n+$k;asort($a);echo key($a);
</code>```

It puts all the combinations of at least $n seats into an associative list; the key is the text representation of the arrangement, the value is the arrangement's score. It then sorts the list (ascending by value) and gets the key of the first entry.

One more (115 bytes)

```<code>foreach(range(1,$m=$n=$argv[1])as$i)
if(($d=ceil($n/$i))<=$i&&$m>=$s=$i*$d-$n+$i-$d){$m=$s;$w=$d;$h=$i;}echo"$w,$h";
</code>```

This is the PHP version of @Neil's answer (JavaScript/ES6, 85 bytes).

There are some noticeable differences due to the features of each language:

the JS answer generates an array of n (undefined) values then uses its keys to iterate from 0 to n-1; it increments i (d=(n+i++)/i|0) to make it iterate from 1 to n; the PHP solution doesn't need to increment; it uses range() to generate an array then it uses the generated values (1 to n) to iterate;

the JS answer uses (n+i)/i then converts the value to integer using |0 to get the smallest integer larger than n/i; the PHP answer solves this issue easily with the PHP function ceil(); JavaScript also provides Math.ceil() but it uses 5 bytes more than the solution found by Neil;

PHP provides the function array_map() that is somehow similar with JS Array.map() but it doesn't help here; its syntax is verbose, a foreach produces shorter code; it is larger than the JS code, though;

merging the assignments into the conditions using || is not possible in PHP because it lacks the comma operator; I translated a||b||c into if(!a&&!b)c then, because a and b are comparisons, I negated their operators (replaced < with >=); this also produces larger code than the JS version;

another 23 bytes have to be added just because the names of variables in PHP have to be prefixed by $.

The ungolfed versions of all solutions and the test suite can be found on Github.

Title: How should you arrange your chairs?

Body:
You teach a class of students with interesting preferences for how their chairs are arranged. There are 3 very specific requirements they have for how the chairs are arranged:

They most be arranged in a rectangle, even if it means some chairs go empty.

There must be as few empty chairs as possible.

They must be as "squarey" as possible. Squarey-ness is determined by the distance between the width and the height of the rectangle, lower is better. For example, a rectangle that is 4x7 has a squarey-ness of 3.

To be more specific, the "score" of an arrangement is the distance between the width and height plus the number of chairs that would go empty.

Let's take an example. Let's say you have 13 students. You could arrange the chairs any of these ways:

```<code>1x13
2x7
3x5
4x4
</code>```

1x13 is not very squarey. In fact, 1 and 13 are 12 apart, so we give this arrangement 12 points. It also has 0 empty chairs, so we add 0 points, giving this arrangement a score of 12. Not that great.

2x7 is certainly better. 2 and 7 are only 5 apart, so we give this arrangement 5 points. However, if you actually arranged 2 rows of seven chairs, that would take 14 chairs, meaning one chair would be empty. So we add one point, giving this arrangement a score of 6.

We could also do 3x5. 3 and 5 are 2 apart, so +2 points. It takes 15 chairs, meaning we'd have two extra chairs, so another +2 points, for a score of 4.

Last option, 4x4. 4 and 4 are 0 apart, so we give this +0 points. 4x4 takes 16 chairs, so 3 chairs go empty, for a total score of 3. This is the optimal solution.

In case of a tie, the optimal solution is the one with less empty chairs.

The challenge

You must write a program or function that takes an integer and outputs the optimal arrangement of chairs for that number of students. IO can be in any reasonable format. Here is sample output for any number of students from 1 to 100:

```<code>1:  (1, 1)
2:  (1, 2)
3:  (2, 2)
4:  (2, 2)
5:  (2, 3)
6:  (2, 3)
7:  (3, 3)
8:  (3, 3)
9:  (3, 3)
10: (2, 5)
11: (3, 4)
12: (3, 4)
13: (4, 4)
14: (4, 4)
15: (4, 4)
16: (4, 4)
17: (3, 6)
18: (3, 6)
19: (4, 5)
20: (4, 5)
21: (3, 7)
22: (5, 5)
23: (5, 5)
24: (5, 5)
25: (5, 5)
26: (4, 7)
27: (4, 7)
28: (4, 7)
29: (5, 6)
30: (5, 6)
31: (4, 8)
32: (4, 8)
33: (6, 6)
34: (6, 6)
35: (6, 6)
36: (6, 6)
37: (5, 8)
38: (5, 8)
39: (5, 8)
40: (5, 8)
41: (6, 7)
42: (6, 7)
43: (5, 9)
44: (5, 9)
45: (5, 9)
46: (7, 7)
47: (7, 7)
48: (7, 7)
49: (7, 7)
50: (5, 10)
51: (6, 9)
52: (6, 9)
53: (6, 9)
54: (6, 9)
55: (7, 8)
56: (7, 8)
57: (6, 10)
58: (6, 10)
59: (6, 10)
60: (6, 10)
61: (8, 8)
62: (8, 8)
63: (8, 8)
64: (8, 8)
65: (6, 11)
66: (6, 11)
67: (7, 10)
68: (7, 10)
69: (7, 10)
70: (7, 10)
71: (8, 9)
72: (8, 9)
73: (7, 11)
74: (7, 11)
75: (7, 11)
76: (7, 11)
77: (7, 11)
78: (9, 9)
79: (9, 9)
80: (9, 9)
81: (9, 9)
82: (7, 12)
83: (7, 12)
84: (7, 12)
85: (8, 11)
86: (8, 11)
87: (8, 11)
88: (8, 11)
89: (9, 10)
90: (9, 10)
91: (7, 13)
92: (8, 12)
93: (8, 12)
94: (8, 12)
95: (8, 12)
96: (8, 12)
97: (10, 10)
98: (10, 10)
99: (10, 10)
100: (10, 10)
</code>```

As usual, this is code-golf, so standard loopholes apply, and the winner is the shortest answer in bytes.

Body:
PHP, 104 bytes

The algorithm that solves this problem is simple and it is probably used by other answers in languages similar to PHP (JavaScript, f.e.):

start with a large value for the initial score; n is large enough (where n is the input value); the score of the arrangement computed on the first iteration (1, n) is (n-1)+0;

iterate for all values of width between 1 and n; compute the minimum height as ceil(n/width), compute the arrangement score using the formula provided in the question (i.e. abs(width - height) + (width * height - n)); if the score is better than the previous best score then remember the width, the height and the new best score; on ties use the value of width * height - n for current arrangement and previous best arrangement to detect the new best arrangement;

that's all.

After golfing, this algorithm produces something like this (wrapped here for readability):

for($s=$h=$j=$n=$argv[$w=$i=1];$i<=$j;$j=ceil($n/++$i)
{$c=$j-$i+$i*$j-$n;if($c<$s||$c==$s&&$i*$j<$w*$h){$w=$i;$h=$j;$s=$c;}}
echo"$w,$h";

It uses 137 bytes (when put on a single line) and it is far from the 104 bytes advertised in the title. The code can probably be shortened by another 2-3 bytes but the big source of improvement is somewhere else: in the details of the algorithm.

The revised algorithm:

There are several places where the algorithm can be improved by removing useless code.

there is no need to iterate the width from 1 to $n; for speed, the width ($i) must iterate between 1 and floor(sqrt($n)) but this makes the code even longer instead of shortening it; but if the width doesn't exceed sqrt($n), the minimum height ($j) will always be larger than sqrt($n) (their product must be at least $n);

the previous statement allows using $i <= $j (width <= height) as the termination condition for loop; this way, the width will iterate from 1 to floor(sqrt($n)) and the height will get values starting with $n and going down to ceil(sqrt($n)) (not necessarily all of them);

knowing that width is always smaller than or equal to the height allow us know that abs(width - height) is always height - width ($j-$i); 5 bytes saved this way;

the input value $n is used in the computation of score (the number of unoccupied seats is width * height - n) but it is not needed; the score does not need to be displayed, it is computed only for comparison of the arrangements; by removing - n from the score formula we save another 3 bytes (the PHP code is -$n) without losing anything;

given the last two statements, the score formula becomes height - width + width * height ($j-$i+$i*$j);

on ties (the score of the current arrangement is the same as the previous best score), the rules say to use the arrangement with less free seats; because width always increases and height always decreases, the height - width part of the score decreases on each step;

if the current score is equal with the previous best score, the previous statements tells us that the number of free seats of the current arrangement is larger than the one of the previous best arrangement; this means the previous best arrangement win the tie;

because the ties are always won by the previous best arrangement, a new arrangement becomes the new best arrangement only when its score is smaller than the previous best; the code that checks for ties is useless and can be removed (||$c==$s&&$i*$j<$w*$h -- a lot of bytes);

because of the removal of -$n from the score's formula, the score for the first arrangement (1x$n) is $n-1+1*$n (i.e. 2*$n-1); the initial value of the best score ($s) can be any value greater than or equal to 2*$n; the first iteration has a better score and it becomes the best arrangement letting the algorithm run without initialization problems.

The new code (104 bytes), after applying the improvements described above is:

for($s=2*$j=$n=$argv[$i=1];$i<=$j;$j=ceil($n/++$i))
if($s>$c=$j-$i+$i*$j){$w=$i;$h=$j;$s=$c;}echo"$w,$h";

It is wrapped here for readability. Prepend the code above with the PHP marker <?php (technically, it is not part of the code), put it into a file (let's say arrange-your-chairs.php) and run it with an integer greater than zero as argument. It will display the width and height of the computed arrangement, separated by comma:

$ php arrange-your-chairs.php 1001
28,36

Another solution (116 bytes)

Another solution that uses a different algorithm:

for($n=$argv[1];++$j<=$n;)for($i=0;++$i<=$j;)
if($n<=$k=$i*$j)$a["$i,$j"]=($j-$i+$k-$n)*$n+$k;asort($a);echo key($a);

It puts all the combinations of at least $n seats into an associative list; the key is the text representation of the arrangement, the value is the arrangement's score. It then sorts the list (ascending by value) and gets the key of the first entry.

One more (115 bytes)

foreach(range(1,$m=$n=$argv[1])as$i)
if(($d=ceil($n/$i))<=$i&&$m>=$s=$i*$d-$n+$i-$d){$m=$s;$w=$d;$h=$i;}echo"$w,$h";

This is the PHP version of @Neil's answer (JavaScript/ES6, 85 bytes).

There are some noticeable differences due to the features of each language:

the JS answer generates an array of n (undefined) values then uses its keys to iterate from 0 to n-1; it increments i (d=(n+i++)/i|0) to make it iterate from 1 to n; the PHP solution doesn't need to increment; it uses range() to generate an array then it uses the generated values (1 to n) to iterate;

the JS answer uses (n+i)/i then converts the value to integer using |0 to get the smallest integer larger than n/i; the PHP answer solves this issue easily with the PHP function ceil(); JavaScript also provides Math.ceil() but it uses 5 bytes more than the solution found by Neil;

PHP provides the function array_map() that is somehow similar with JS Array.map() but it doesn't help here; its syntax is verbose, a foreach produces shorter code; it is larger than the JS code, though;

merging the assignments into the conditions using || is not possible in PHP because it lacks the comma operator; I translated a||b||c into if(!a&&!b)c then, because a and b are comparisons, I negated their operators (replaced < with >=); this also produces larger code than the JS version;

another 23 bytes have to be added just because the names of variables in PHP have to be prefixed by $.

The ungolfed versions of all solutions and the test suite can be found on Github.


答:
Python 2, 57 bytes

```<code>lambda n:5*[2*n,4**(n/10-1)*ord('♥♥♥♥#(.4<F'[n%10])][n>9]
</code>```

Replace the four hearts with the ASCII characters 20 (^T), 23 (^W), 26 (^Z), and 30 (^^).

Title: Find the number I/O shortest algorithm

Body:
Python 2, 57 bytes

lambda n:5*[2*n,4**(n/10-1)*ord('♥♥♥♥#(.4<F'[n%10])][n>9]

Replace the four hearts with the ASCII characters 20 (^T), 23 (^W), 26 (^Z), and 30 (^^).