答:
Mathematica 106 bytes

The code is fairly straightforward.  A palette is a floating window. The 100 circles are stored in an array. The first ryields coordinates; the second r yields a radius.

```<code>CreatePalette[{Graphics[Array[{RandomColor[],Disk[99~(r=RandomReal)~{2},r@5]}&,100],Background->Black]}]
</code>```

Title: Print 100 Circles

Body:
Goal: Create the smallest possible code to open a separate window, in which there are 100 circles of random sizes and colors.

Rules: All circles must be visible to the unassisted, naked eye, so in other words more than 2 pixels across, the background must be black, at least 5 different colors must be recognizable, and at all circles must fit within the window.

Body:
Mathematica 106 bytes

The code is fairly straightforward.  A palette is a floating window. The 100 circles are stored in an array. The first ryields coordinates; the second r yields a radius.

CreatePalette[{Graphics[Array[{RandomColor[],Disk[99~(r=RandomReal)~{2},r@5]}&,100],Background->Black]}]


问:
Print 100 Circles
Goal: Create the smallest possible code to open a separate window, in which there are 100 circles of random sizes and colors.

Rules: All circles must be visible to the unassisted, naked eye, so in other words more than 2 pixels across, the background must be black, at least 5 different colors must be recognizable, and at all circles must fit within the window.

答:
Python 2 PIL - 199 bytes

Making some assumptions of the rules based on OP's answer. Not optimally golfed in the sense that the image could be 5 pixels across and the circles could be all the same place with grayscale colors, but goes with the spirit of the rules.

```<code>import Image,ImageDraw,random
h=999
i=Image.new('RGB',(h,h))
g=random.randint
exec"r,x,y=g(0,50),g(0,h),g(0,h);ImageDraw.Draw(i).ellipse((x-r,y-r,x+r,y+r),(g(0,255),g(0,255),g(0,255)));"*100
i.show()
</code>```

ContentLicense: CC BY-SA 3.0

Title: Print 100 Circles

Body:
Python 2 PIL - 199 bytes

Making some assumptions of the rules based on OP's answer. Not optimally golfed in the sense that the image could be 5 pixels across and the circles could be all the same place with grayscale colors, but goes with the spirit of the rules.

import Image,ImageDraw,random
h=999
i=Image.new('RGB',(h,h))
g=random.randint
exec"r,x,y=g(0,50),g(0,h),g(0,h);ImageDraw.Draw(i).ellipse((x-r,y-r,x+r,y+r),(g(0,255),g(0,255),g(0,255)));"*100
i.show()


问:
Draw the national flag of France
There have been many other flag challenges posted but not one for the national flag of France. This week seems like an appropriate time.

Produce this flag in the fewest bytes possible:

The image must be in a ratio of 3:2, with size at least 78 pixels wide and 52 pixels tall.

Each stripe takes up one third of the width.

The stripe colors from left to right are RGB: (0, 85, 164), (255, 255, 255), (239, 65, 53).

The image can be saved to a file or piped raw to STDOUT in any common image file format, or it can be displayed.

Alternatively, output a block of text at least 78 characters wide made of non-whitespace characters that depicts the flag, using ANSI color codes to color it. (Use standard blue, white, and red.)

Built-in flag images/libraries are not allowed.

The shortest code in bytes wins.

Leaderboard

The Stack Snippet at the bottom of this post generates the leaderboard 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>## [><>](http://esolangs.org/wiki/Fish), 121 bytes
</code>```

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

Shortest Solution by Language

Language	User	Score

Leaderboard

	Author	Language	Size

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

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

```

ContentLicense: CC BY-SA 4.0

Title: Draw the national flag of France

Body:
ImageScript, 63 bytes

rgb(0,85,164)rect(0,0,200,400)rgb(239,65,53)rect(400,0,200,400)


问:
Filter this string!
Your task is to write a program that will filter out some characters in a string, so that the remaining spells out (part of) the other string.

Let's say we received the string "123456781234567812345678", and the second string is "314159".

First, we put a pointer on the second string:

```<code>314159
^
</code>```

So the pointer is now on 3, and we replace the not-3 characters with a hashtag until the first 3:

```<code>##3456781234567812345678
</code>```

We then move the pointer to the next character until we have iterated through the string.

Specs

You may use any character to replace "#", and the first string will not contain the hashtag (or the replaced hashtag).

The second string will always be longer than enough.

Both strings will only contain ASCII printable characters (U+0020-U+007F).

Testcases

```<code>input1: 123456781234567812345678
input2: 314159
output: ##3#####1##4####1###5###

input1: abcdefghijklmnopqrstuvwxyz
input2: dilemma
output: ###d####i##l##############
</code>```

答:
, 18 chars / 23 bytes

```<code>îⓢ⒨≔í⟨Ḁ?(Ḁ⧺,$):0)⨝
</code>```

Try it here (Firefox only).

Ayyy not bad. Uses 0 as the replacement char. It's just the same algorithm that I used in my JS answer.

Title: Filter this string!

Body:
, 18 chars / 23 bytes

îⓢ⒨≔í⟨Ḁ?(Ḁ⧺,$):0)⨝

Try it here (Firefox only).

Ayyy not bad. Uses 0 as the replacement char. It's just the same algorithm that I used in my JS answer.


答:
I realize that there's already another JS-based solution posted using the .replace method that's shorter, but I'd like to submit my answers anyways...

CoffeeScript, 55 bytes

Builds a string and returns it:

f=(a,b,i=0,s='')->s+=c==b[i]&&b[i++]||'#'for j,c of a;s
```

<h2>JavaScript, 53 bytes</h2>

<p>Operates on an array of characters from the original string:</p>

<pre class="lang-js prettyprint-override"><code>f=(a,b,i=0)=>[...a].map(c=>c==b[i]?b[i++]:`#`).join``
</code>```

Title: Filter this string!

Body:
Your task is to write a program that will filter out some characters in a string, so that the remaining spells out (part of) the other string.

Let's say we received the string "123456781234567812345678", and the second string is "314159".

First, we put a pointer on the second string:

```<code>314159
^
</code>```

So the pointer is now on 3, and we replace the not-3 characters with a hashtag until the first 3:

```<code>##3456781234567812345678
</code>```

We then move the pointer to the next character until we have iterated through the string.

Specs

You may use any character to replace "#", and the first string will not contain the hashtag (or the replaced hashtag).

The second string will always be longer than enough.

Both strings will only contain ASCII printable characters (U+0020-U+007F).

Testcases

```<code>input1: 123456781234567812345678
input2: 314159
output: ##3#####1##4####1###5###

input1: abcdefghijklmnopqrstuvwxyz
input2: dilemma
output: ###d####i##l##############
</code>```

Body:
I realize that there's already another JS-based solution posted using the .replace method that's shorter, but I'd like to submit my answers anyways...

CoffeeScript, 55 bytes

Builds a string and returns it:

f=(a,b,i=0,s='')->s+=c==b[i]&&b[i++]||'#'for j,c of a;s

JavaScript, 53 bytes

Operates on an array of characters from the original string:

f=(a,b,i=0)=>[...a].map(c=>c==b[i]?b[i++]:`#`).join``


问:
Between the Lines

While doodling around on square-ruled paper the other day, I came up with the above negative-space font for digits. In case you haven't spotted it yet, the spaces between the above shapes yield the golden ratio 1.618033988749. In this challenge, your task is to take a number as input and render it exactly as the example above shows.

Here is how these are created: all lines will be on a regular grid, so that the individual digits are made up of a small number of grid cells. Here are the shapes of the 10 digits (we'll ignore the decimal point for this challenge):

Yes, the 7 differs from the golden ratio example at the top. I kinda messed that up. We'll be going with this one.

Notice that each digit is five cells tall, and three cells wide. To render a number, you can imagine placing all its digits next to each other, such that there is exactly one empty column between each pair of digits. For example, taking 319 as input, we'd write:

Notice that we add one leading and trailing empty column. Now we invert the cells:

The output should then be the boundaries of the resulting polygons:

Of course you may generate the result in any other way, as long as the rendered output looks the same.

Input

You may write a program or function, taking input via STDIN (or closest alternative), command-line argument or function argument, as a string, or list of digits. (You can't take a number as that wouldn't allow you to support leading zeros.)

You may assume that there will be no more than 16 digits in the input.

Output

Output may either be displayed on screen or written to a file in a common image format.

You may use both raster and vector graphics.

In either case, the aspect ratio of the cells of the underlying grid needs to be 1 (that is, the cells should be squares).

In the case of raster graphics, each cell should cover at least 20 by 20 pixels.

The lines must be no wider than 10% of the cell size. I'm willing to give one or two pixels leeway due to aliasing here.

Lines and background can be any two clearly distinguishable colours, but the shapes created by the lines must not be filled (that is the insides should be the background colour as well).

There must be no gaps within each closed loop.

Of course, the entire result must be visible.

Test Cases

Here are 10 inputs, which together cover all possible pairs of adjacent digits, as well as every possible leading and trailing digit:

```<code>07299361548
19887620534
21456837709
39284106657
49085527316
59178604432
69471338025
79581224630
89674235011
97518264003
</code>```

And here are the expected results for those:

Make sure that your code also works when given a single digit (I don't want to include the expected results here, because they should be obvious, and the test case section is bloated enough as it is).

答:
BBC BASIC, 182 ASCII characters (tokenised filesize 175 bytes)

Download interpreter at http://www.bbcbasic.co.uk/bbcwin/bbcwin.html

```<code>I.n$
F.j=0TOLENn$*4p=ASCM."?@\@?[@_?DTP?TT@?pv@?PTD?@TD?||@?@T@?PT@",VALM.n$,j/4+1,1)*4+1+j MOD4)F.k=0TO4p*=2q=64A.p
V.537;q;0;2585;0;q;537;-q;0;2585;0;-q;25;0;64;
N.MOVEBY 64,-320N.
</code>```

Scoring: When the above program is pasted into the editor and run, the editor will expand the abbreviated keywords into full keywords onscreen, though they are actually only 1 byte after tokenisation. (Example I.=INPUT storage space 1 byte.)

Explanation

I will just explain what the VDU line does: it draws a box by  bit-flipping the current pixel colour on the screen. This means that (with a bit of care with the corners) it is possible simply to draw one cell next to each other, and the intervening edge will cancel out and disappear due to double drawing.

Close examination will reveal that the top right and bottom left corners of a cell are drawn but the top left and bottom right are missing ("rounded") in order to make this work.

After the cell is drawn, the graphics cursor is moved up 32 pixels ready for the next cell to be drawn.

The rest of the program is a fairly straightforward ASCII bitmap decompression. The dimensions of the cell are 64x64 units for golfing/compatability with the way the bitmap is decompressed. q controls the size of the cell that is plotted: 64x64 units for a cell that is present, 0x0 for a cell that is absent.

Ungolfed code

```<code>  m$="?@\@?[@_?DTP?TT@?pv@?PTD?@TD?||@?@T@?PT@" :REM bitmap for digits, including column of filled cells at left. BBC strings are 1-indexed
  INPUTn$                                       :REM user input
  FORj=0 TO LENn$*4                             :REM iterate 4 times per input digit, plus once more (plot column 0 of imaginary digit to finish)
    d=VAL MID$(n$,j/4+1,1)                      :REM extract digit from n$ (1-character string). VAL of empty string = 0, so 123->1,1,1,1,2,2,2,2,3,3,3,3,0
    p=ASC MID$(m$,d*4+1+j MOD4)                 :REM get column bitmap from m$ d*4 selects digit, j MOD4 selects correct column of digit, add 1 to convert to 1-index
    FORk=0TO4                                   :REM for each cell in the column
      p*=2                                      :REM bitshift p
      q=64ANDp                                  :REM find size of cell to draw. 64 for a filled cell, 0 for an absent cell.
      VDU537;q;0;                               :REM line q units right, inverting existing screen colour. Draw last pixel (will be inverted next line)
      VDU2585;0;q;                              :REM line q units up, inverting existing screen colour. Dont draw last pixel (will be filled in next line)
      VDU537;-q;0;                              :REM line q units left, inverting existing screen colour. Draw last pixel (will be inverted next line)
      VDU2585;0;-q;                             :REM line q units down, inverting existing screen colour. Dont draw last pixel (avoid inverting 1st pixel of 1st line)
      VDU25;0;64;                               :REM move up 64 units for cell above
    NEXT
    MOVEBY 64,-320                              :REM move right and down for next column.
  NEXT
</code>```

Output

The MOVEs are just get the output to appropriate heights on the screen. BBC basic uses 2 units = 1 pixel in this mode, so the cells are actually 32x32 pixels.

Title: Between the Lines

Body:
BBC BASIC, 182 ASCII characters (tokenised filesize 175 bytes)

Download interpreter at http://www.bbcbasic.co.uk/bbcwin/bbcwin.html

I.n$
F.j=0TOLENn$*4p=ASCM."?@\@?[@_?DTP?TT@?pv@?PTD?@TD?||@?@T@?PT@",VALM.n$,j/4+1,1)*4+1+j MOD4)F.k=0TO4p*=2q=64A.p
V.537;q;0;2585;0;q;537;-q;0;2585;0;-q;25;0;64;
N.MOVEBY 64,-320N.

Scoring: When the above program is pasted into the editor and run, the editor will expand the abbreviated keywords into full keywords onscreen, though they are actually only 1 byte after tokenisation. (Example I.=INPUT storage space 1 byte.)

Explanation

I will just explain what the VDU line does: it draws a box by  bit-flipping the current pixel colour on the screen. This means that (with a bit of care with the corners) it is possible simply to draw one cell next to each other, and the intervening edge will cancel out and disappear due to double drawing.

Close examination will reveal that the top right and bottom left corners of a cell are drawn but the top left and bottom right are missing ("rounded") in order to make this work.

After the cell is drawn, the graphics cursor is moved up 32 pixels ready for the next cell to be drawn.

The rest of the program is a fairly straightforward ASCII bitmap decompression. The dimensions of the cell are 64x64 units for golfing/compatability with the way the bitmap is decompressed. q controls the size of the cell that is plotted: 64x64 units for a cell that is present, 0x0 for a cell that is absent.

Ungolfed code

  m$="?@\@?[@_?DTP?TT@?pv@?PTD?@TD?||@?@T@?PT@" :REM bitmap for digits, including column of filled cells at left. BBC strings are 1-indexed
  INPUTn$                                       :REM user input
  FORj=0 TO LENn$*4                             :REM iterate 4 times per input digit, plus once more (plot column 0 of imaginary digit to finish)
    d=VAL MID$(n$,j/4+1,1)                      :REM extract digit from n$ (1-character string). VAL of empty string = 0, so 123->1,1,1,1,2,2,2,2,3,3,3,3,0
    p=ASC MID$(m$,d*4+1+j MOD4)                 :REM get column bitmap from m$ d*4 selects digit, j MOD4 selects correct column of digit, add 1 to convert to 1-index
    FORk=0TO4                                   :REM for each cell in the column
      p*=2                                      :REM bitshift p
      q=64ANDp                                  :REM find size of cell to draw. 64 for a filled cell, 0 for an absent cell.
      VDU537;q;0;                               :REM line q units right, inverting existing screen colour. Draw last pixel (will be inverted next line)
      VDU2585;0;q;                              :REM line q units up, inverting existing screen colour. Dont draw last pixel (will be filled in next line)
      VDU537;-q;0;                              :REM line q units left, inverting existing screen colour. Draw last pixel (will be inverted next line)
      VDU2585;0;-q;                             :REM line q units down, inverting existing screen colour. Dont draw last pixel (avoid inverting 1st pixel of 1st line)
      VDU25;0;64;                               :REM move up 64 units for cell above
    NEXT
    MOVEBY 64,-320                              :REM move right and down for next column.
  NEXT

Output

The MOVEs are just get the output to appropriate heights on the screen. BBC basic uses 2 units = 1 pixel in this mode, so the cells are actually 32x32 pixels.


问:
What is the most frequent word?

What is the most frequent word?

Given a sentence, your program must make its way through it, counting the frequencies of each word, then output the most used word. Because a sentence has no fixed length, and so can get very long, your code must be as short as possible.

Rules/Requirements

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

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

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

Your program must not write anything to STDERR.

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

Standard loopholes are forbidden.

Your program must be case-insensitive (tHe, The and the all contribute to the count of the).

If there is no most frequent word (see test case #3), your program should output nothing.

Definition of a 'word':

You get the list of words by splitting the input text on spaces. The input will never contain any other type of whitespace than plain spaces (in particular no newlines). However, the final words should only contain alphanumerics (a-z, A-Z, 0-9), hyphens (-) and apostrophes ('). You can make that so by removing all other characters or by replacing them by space before doing the word splitting. To remain compatible with previous versions of the rules, apostrophes are not required to be included.

Test Cases

```<code>The man walked down the road.
==> the

-----

Slowly, he ate the pie, savoring each delicious bite. He felt like he was truly happy.
==> he

-----

This sentence has no most frequent word.
==>

-----

"That's... that's... that is just terrible!" he said.
==> that's / thats

-----

The old-fashioned man ate an old-fashioned cake.
==> old-fashioned

-----

IPv6 looks great, much better than IPv4, except for the fact that IPv6 has longer addresses.
==> IPv6

-----

This sentence with words has at most two equal most frequent words.
==>
</code>```

Note: The third and seventh test cases have no output, you may choose either on the fourth.

Scoring

Programs are scored according to bytes. The usual character set is UTF-8, if you are using another please specify.

When the challenge finishes, the program with the least bytes (it's called code-golf), will win.

Submissions

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

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

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

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

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

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

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

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

Leaderboard

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

/* Configuration */

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

/* App */

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

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

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

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

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

getAnswers();

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

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

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

function process() {
  var valid = [];

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

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

  });

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

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

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

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

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

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

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

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

table thead {
  font-weight: bold;
}

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

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

```

答:
Ruby, <s>94</s> <s>92</s> 102 bytes

Gotta go fast (FGITW answer). Returns the word in all uppercase, or nil if there is no most frequent word.

Now updated to new specs, I think. However, I did manage to golf down a little so the byte count is the same!

```<code>->s{w=s.upcase.tr("_'",'').scan /[-\w]+/;q=->x{w.count x};(w-[d=w.max_by(&q)]).all?{|e|q[e]<q[d]}?d:p}
</code>```

Title: What is the most frequent word?

Body:
Ruby, <s>94</s> <s>92</s> 102 bytes

Gotta go fast (FGITW answer). Returns the word in all uppercase, or nil if there is no most frequent word.

Now updated to new specs, I think. However, I did manage to golf down a little so the byte count is the same!

->s{w=s.upcase.tr("_'",'').scan /[-\w]+/;q=->x{w.count x};(w-[d=w.max_by(&q)]).all?{|e|q[e]<q[d]}?d:p}


答:
Pyth, 32 bytes

```<code>p?tlJeM.MhZrS@Ls++\-GUTcrz0d8ksJ
</code>```

Test suite.

Title: What is the most frequent word?

Body:
What is the most frequent word?

Given a sentence, your program must make its way through it, counting the frequencies of each word, then output the most used word. Because a sentence has no fixed length, and so can get very long, your code must be as short as possible.

Rules/Requirements

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

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

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

Your program must not write anything to STDERR.

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

Standard loopholes are forbidden.

Your program must be case-insensitive (tHe, The and the all contribute to the count of the).

If there is no most frequent word (see test case #3), your program should output nothing.

Definition of a 'word':

You get the list of words by splitting the input text on spaces. The input will never contain any other type of whitespace than plain spaces (in particular no newlines). However, the final words should only contain alphanumerics (a-z, A-Z, 0-9), hyphens (-) and apostrophes ('). You can make that so by removing all other characters or by replacing them by space before doing the word splitting. To remain compatible with previous versions of the rules, apostrophes are not required to be included.

Test Cases

```<code>The man walked down the road.
==> the

-----

Slowly, he ate the pie, savoring each delicious bite. He felt like he was truly happy.
==> he

-----

This sentence has no most frequent word.
==>

-----

"That's... that's... that is just terrible!" he said.
==> that's / thats

-----

The old-fashioned man ate an old-fashioned cake.
==> old-fashioned

-----

IPv6 looks great, much better than IPv4, except for the fact that IPv6 has longer addresses.
==> IPv6

-----

This sentence with words has at most two equal most frequent words.
==>
</code>```

Note: The third and seventh test cases have no output, you may choose either on the fourth.

Scoring

Programs are scored according to bytes. The usual character set is UTF-8, if you are using another please specify.

When the challenge finishes, the program with the least bytes (it's called code-golf), will win.

Submissions

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

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

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

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

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

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

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

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

Leaderboard

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

/* Configuration */

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

/* App */

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

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

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

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

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

getAnswers();

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

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

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

function process() {
  var valid = [];

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

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

  });

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

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

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

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

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

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

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

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

table thead {
  font-weight: bold;
}

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

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

```

Body:
Pyth, 32 bytes

p?tlJeM.MhZrS@Ls++\-GUTcrz0d8ksJ

<a href="http://pyth.herokuapp.com/?code=p%3FtlJeM.MhZrS%40Ls%2B%2B%5C-GUTcrz0d8ksJ&test_suite=1&test_suite_input=The+man+walked+down+the+road.%0ASlowly%2C+he+ate+the+pie%2C+savoring+each+delicious+bite.+He+felt+like+he+was+truly+happy.%0AThis+sentence+has+no+most+frequent+word.%0A%22That%27s...+that%27s...+that+is+just+terrible!%22+he+said.%0AThe+old-fashioned+man+ate+an+old-fashioned+cake.%0AIPv6+looks+great%2C+much+better+than+IPv4%2C+except+for+the+fact+that+IPv6+has+longer+addresses.&debug=0" rel="nofollow noreferrer">Test suite.


答:
05AB1E, 30 bytes

Code:

```<code>lžj¨„ -«Ãð¡©Ùv®yQOˆ}®¯MQÏDg1Q×
</code>```

Uses CP-1252 encoding. Try it online!.

Title: What is the most frequent word?

Body:
05AB1E, 30 bytes

Code:

lžj¨„ -«Ãð¡©Ùv®yQOˆ}®¯MQÏDg1Q×

Uses CP-1252 encoding. Try it online!.


Title: What is the most frequent word?

Body:
Retina, 97 bytes

The rules keep changing...

T`L`l
[^-\w ]

O`[-\w]+
([-\w]+)( \1\b)*
$#2;$1
O#`[-\w;]+
.*\b(\d+);[-\w]+ \1;[-\w]+$

!`[-\w]+$

Try it online!

<a href="http://retina.tryitonline.net/#code=JShUYExgbApbXi1cdyBdCgpPYFstXHddKwooWy1cd10rKSggXDFcYikqCiQjMjskMQpPI2BbLVx3O10rCi4qXGIoXGQrKTtbLVx3XSsgXDE7Wy1cd10rJAoKIWBbLVx3XSsk&input=VGhlIG1hbiB3YWxrZWQgZG93biB0aGUgcm9hZC4KU2xvd2x5LCBoZSBhdGUgdGhlIHBpZSwgc2F2b3JpbmcgZWFjaCBkZWxpY2lvdXMgYml0ZS4gSGUgZmVsdCBsaWtlIGhlIHdhcyB0cnVseSBoYXBweS4KVGhpcyBzZW50ZW5jZSBoYXMgbm8gbW9zdCBmcmVxdWVudCB3b3JkLgoiVGhhdCdzLi4uIHRoYXQncy4uLiB0aGF0IGlzIGp1c3QgdGVycmlibGUhIiBoZSBzYWlkLgpUaGUgb2xkLWZhc2hpb25lZCBtYW4gYXRlIGFuIG9sZC1mYXNoaW9uZWQgY2FrZS4KSVB2NiBsb29rcyBncmVhdCwgbXVjaCBiZXR0ZXIgdGhhbiBJUHY0LCBleGNlcHQgZm9yIHRoZSBmYWN0IHRoYXQgSVB2NiBoYXMgbG9uZ2VyIGFkZHJlc3Nlcy4" rel="nofollow noreferrer">Test suite.


答:
Pyth - <s>23</s> 30 bytes

There has to be a better way to include digits and hyphens, but I just want to fix this right now.

```<code>Kc@s+++GUTd\-rzZ)I!tJ.M/KZ{KhJ
</code>```

Test Suite.

Title: What is the most frequent word?

Body:
Pyth - <s>23</s> 30 bytes

There has to be a better way to include digits and hyphens, but I just want to fix this right now.

Kc@s+++GUTd\-rzZ)I!tJ.M/KZ{KhJ

Test Suite.


答:
Octave, <s>115</s> 94 bytes

```<code>[a,b,c]=unique(regexp(lower(input('')),'[A-z]*','match'));[~,~,d]=mode(c); try disp(a{d{:}})
</code>```

Accounts for the case with no most frequent word by using try. In this case it outputs nothing, and "takes a break" until you catch the exception.

Saved 21(!) bytes thanks to Luis Mendo's suggestion (using the third output from mode to get the most common word).

The rules have changed quite a bit since I posted my original answer. I'll look into the regex later.

Title: What is the most frequent word?

Body:
Octave, <s>115</s> 94 bytes

[a,b,c]=unique(regexp(lower(input('')),'[A-z]*','match'));[~,~,d]=mode(c); try disp(a{d{:}})

Accounts for the case with no most frequent word by using try. In this case it outputs nothing, and "takes a break" until you catch the exception.

Saved 21(!) bytes thanks to Luis Mendo's suggestion (using the third output from mode to get the most common word).

The rules have changed quite a bit since I posted my original answer. I'll look into the regex later.


答:
05AB1E, 5 bytes

Code:

```<code>.o²g£
</code>```

Explanation:

```<code>.o     # Overlap function.
         12345 and 1456 yields:
         1  456
  ²    # Get the second input.
   g   # Take the length.
    £  # Take the substring [0:length] and implicitly output.

</code>```

Uses CP-1252 encoding. Try it online!

Title: Filter this string!

Body:
05AB1E, 5 bytes

Code:

.o²g£

Explanation:

.o     # Overlap function.
         12345 and 1456 yields:
         1  456
  ²    # Get the second input.
   g   # Take the length.
    £  # Take the substring [0:length] and implicitly output.

Uses CP-1252 encoding. Try it online!


问:
Draw a phi triangle
Clarification: Basically, you need to make this

Euler's totient function has the name phi.

Let's try to calculate phi(8)

First, list all numbers 8 and under backwards, not including 0 or under

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

Now find which numbers don't share a factor with 8 (1 doesn't count), and place a # in their place.

```<code>8
#
6
#
4
#
2
#
</code>```

Remove the numbers.

```<code>#

#

#

#
                                                 -
</code>```

Now do this, but string the outputs together in a triangle

```<code>        9
       88
      777
     6666
    55555
   444444
  3333333
 22222222
111111111
---------
123456789
</code>```

# out non-factor sharing numbers

```<code>        9
       8#
      7##
     6#66
    5####
   4#4#4#
  3##3##3
 2#2#2#2#
#########
</code>```

Remove numbers:

```<code>        #
       ##
      #
     ####
    # # #
   ## ##
  # # # #
#########
</code>```

This would be the output for input 9 (since 9 columns.)

Leading + trailing newlines allowed.

答:
Python 2 (120 bytes)

g=lambda m,n:m if n<1 else g(n,m%n)
r=range(input())
for i in r[:0:-1]:print''.join('# '[i>j+1 or g(i,j+1)>1]for j in r)
```

Title: Draw a phi triangle


Title: Filter this string!

Body:
C, 81 bytes

A[99];char*b=A,*a=A+50;main(){gets(a),gets(b);while(*a)putchar(*a++^*b?35:*b++);}


答:
Python 2, 218 bytes

Assumes more than 2 words. Getting rid of punctuation destroyed me...

import string as z
def m(s):a=[w.lower()for w in s.translate(z.maketrans('',''),z.punctuation).split()];a=sorted({w:a.count(w)for w in set(a)}.items(),key=lambda b:b[1],reverse=1);return a[0][0]if a[0][1]>a[1][1]else''
```

Title: What is the most frequent word?


答:
Pyke, <s>26</s> 25 bytes

```<code>l1dcD}jm/D3Sei/1qIi@j@
(;
</code>```

Try it here!

Or <s>23</s> 22 bytes (noncompeting, add node where kills stack if false)

```<code>l1cD}jm/D3Sei/1q.Ii@j@
</code>```

Try it here!

Or with punctuation, 23 bytes (I think this competes? Commit was before the edit)

```<code>l1.cD}jm/D3Sei/1q.Ii@j@
</code>```

Try it here!

Or 12 bytes (definitely noncompeting)

```<code>l1.cj.#jR/)e
</code>```

Try it here!

```<code>l1           -     input.lower()
  .c         -    punc_split(^)
    j        -   j = ^
     .#   )  -  sort(V(i) for i in ^)
       jR/   -   j.count(i)
           e - ^[-1]
</code>```

Title: What is the most frequent word?

Body:
Pyke, <s>26</s> 25 bytes

l1dcD}jm/D3Sei/1qIi@j@
(;

Try it here!

Or <s>23</s> 22 bytes (noncompeting, add node where kills stack if false)

l1cD}jm/D3Sei/1q.Ii@j@

Try it here!

Or with punctuation, 23 bytes (I think this competes? Commit was before the edit)

l1.cD}jm/D3Sei/1q.Ii@j@

Try it here!

Or 12 bytes (definitely noncompeting)

l1.cj.#jR/)e

Try it here!

l1           -     input.lower()
  .c         -    punc_split(^)
    j        -   j = ^
     .#   )  -  sort(V(i) for i in ^)
       jR/   -   j.count(i)
           e - ^[-1]


问:
Counting Quipu: Base 10 in the New World
Quipus are an ancient device used by the Inca in the Precolumbian era to record numbers in a base ten positional system of knots on a cord, which works as follows:

Each cluster of knots is a digit, and there are three main types of knots: simple overhand knots; "long knots", consisting of an overhand knot with one or more additional turns; and figure-eight knots.

Powers of ten are shown by position along the string, and this position is aligned between successive strands.

Digits in positions for 10 and higher powers are represented by clusters of simple knots (e.g., 40 is four simple knots in a row in the "tens" position).

Digits in the "ones" position are represented by long knots (e.g., 4 is a knot with four turns). Because of the way the knots are tied, the digit 1 cannot be shown this way and is represented in this position by a figure-of-eight knot.

Zero is represented by the absence of a knot in the appropriate position.

Details

For this challenge, each strand of a quipu represents a single number (though, as the Wikipedia article states, you can represent many numbers on one strand, in this challenge, we shall not).

Knots

Each knot will be represented by a single ASCII character.

. represents a simple knot

: represents a one turn of a long knot

8 represents a figure-eight knot

| represents the absence of a knot as well as a delimiter between the digits.

Constructing Quipus

Quipu are constructed following these rules.

Strands run top to bottom in descending order of position (as in, the units digit will be at the bottom end of a strand). Digits along a strand are separated by the character (|).

The power of 10 a digit represents is determined by its position along the strand in the same way a digit's power of 10 would be calculated using its index in a number with our number system. That is, 24 with a 2 in the tens place and a 4 in the units place, will be represented by two knots, a delimiter (|), then four knots.

Digits in the same position are aligned towards the bottom of the strand. If one digit in a position will have less knots than other digits of other numbers in the same position, the absence of those knots is represented by (|).

Consecutive simple knots (.) represent a value in their position.

Every digit is represented by at least 1 character. When a digits value is 0 for all numbers in a quipu, it is represented by the absence of a knot (|).

The units place is treated specially. A one in the units place is represented by a figure-eight knot (8). A value of two or more in the units place is represented by consecutive long knots (:).

When the units digit is 0 for all numbers in a quipu the absence of a knot is not printed but, the trailing delimiter for the tens digit is preserved.

There is no delimiter following the units digit.

Rules

Input will consist of a non-empty list of non-negative integers that may be received through any of the default input methods. You may assume that these integers are all less than or equal to 2147483647 or 2^31-1. While the test cases are space-delimited, your input format can separate inputs in any way that is convenient for your language, whether that be comma-separated, newline-separated, in an array, and so on.

Output consists of a single Quipu constructed according to the rules described above. Output may be given through any of the default output methods.

Your code should be a program or a function, though it does not need to be a named function.

Knots take some time to tie so to save time, your code as short as possible.

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

Examples

Input:

```<code>5 3 1 0
</code>```

Output:

```<code>:|||
:|||
::||
::||
::8|
</code>```

Input:

```<code>50 30 10 0
</code>```

Output:

```<code>.|||
.|||
..||
..||
...|
||||
</code>```

Input:

```<code>330
</code>```

Output:

```<code>.
.
.
|
.
.
.
|
</code>```

Input:

```<code>204 1
</code>```

Output:

```<code>.|
.|
||
||
||
:|
:|
:|
:8
</code>```

Input:

```<code>201 0 100 222
</code>```

Output:

```<code>.||.
.|..
||||
|||.
|||.
||||
|||:
8||:
</code>```

Input:

```<code>:|||
:|||
::||
::||
::8|
</code>```0

Output:

```<code>:|||
:|||
::||
::||
::8|
</code>```1

Input:

```<code>:|||
:|||
::||
::||
::8|
</code>```2

Output:

```<code>|
</code>```

Longer test cases

Further Reading

Ancientscripts: Quipu

The Quipu, Pre-Inca Data Structure

答:
Pyth, 64 bytes

```<code>=QjRTQjCmj\|+:R"[8:]"\.PdedCmm+*\|-h.MZdk*?tk\:\8kdC.[L0h.MZlMQQ
</code>```

Try it online!

How it works

```<code>=QjRTQ   Converts each number in input to decimal (as a list)
         123 becomes [1,2,3]

----

jCmj\|+:R"[8:]"\.PdedCmm+*\|-h.MZdk*?tk\:\8kdC.[L0h.MZlMQQ

                                              .[L0       Q  0-leftpad each #
                                                  h.MZlMQ   (max length) times

                                             C              transpose

                      mm                    d    for each digit:
                        +                        [convert to] sum of
                         *\|                     "|" repeated
                            -                    the difference of
                             h.MZd               maximum digit in same row
                                  k              and itself.. that many times
                                   *?tk\:\8      and (digit > 1 then ":" or "8") repeated
                                           k     itself many times

the list:
[11,23,52]
->[[1,1],[2,3],[5,2]]
->[[1,2,5],[1,3,2]]
->[["||||8","|||::",":::::"],["||8",":::","|::"]]

                     C      transpose

->[["||||8","||8"],["|||::",":::"],[":::::","|::"]]

  m                          for each number
      +                      [convert to] sum of
                 Pd          every element but the last
       :R"[8:]"\.            with "8" and ":" replaced by "."
                   ed        and the last element
   j\|                       joined with "|"

  C                          transpose
 j                           join (with newlines)
</code>```

Body:
Pyth, 64 bytes

=QjRTQjCmj\|+:R"[8:]"\.PdedCmm+*\|-h.MZdk*?tk\:\8kdC.[L0h.MZlMQQ

Try it online!

How it works

=QjRTQ   Converts each number in input to decimal (as a list)
         123 becomes [1,2,3]

----

jCmj\|+:R"[8:]"\.PdedCmm+*\|-h.MZdk*?tk\:\8kdC.[L0h.MZlMQQ

                                              .[L0       Q  0-leftpad each #
                                                  h.MZlMQ   (max length) times

                                             C              transpose

                      mm                    d    for each digit:
                        +                        [convert to] sum of
                         *\|                     "|" repeated
                            -                    the difference of
                             h.MZd               maximum digit in same row
                                  k              and itself.. that many times
                                   *?tk\:\8      and (digit > 1 then ":" or "8") repeated
                                           k     itself many times

the list:
[11,23,52]
->[[1,1],[2,3],[5,2]]
->[[1,2,5],[1,3,2]]
->[["||||8","|||::",":::::"],["||8",":::","|::"]]

                     C      transpose

->[["||||8","||8"],["|||::",":::"],[":::::","|::"]]

  m                          for each number
      +                      [convert to] sum of
                 Pd          every element but the last
       :R"[8:]"\.            with "8" and ":" replaced by "."
                   ed        and the last element
   j\|                       joined with "|"

  C                          transpose
 j                           join (with newlines)


问:
Mode (most common element) of a list
Write a snippet to calculate the mode (most common number) of a list of positive integers.

For example, the mode of

```<code>d = [4,3,1,0,6,1,6,4,4,0,3,1,7,7,3,4,1,1,2,8]
</code>```

is 1, because it occurs the maximum of 5 times.

You may assume that the list is stored in a variable such as d and has a unique mode.

e.g.: Python, 49

```<code>max(((i,d.count(i))for i in set(d)), key=lambda x:x[1])
</code>```

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

答:
Pyke, 10 bytes

```<code>D3m/DSe@R@
</code>```

Try it here!

Title: Mode (most common element) of a list

Body:
Pyke, 10 bytes

D3m/DSe@R@

Try it here!


答:
Python 3, 197 bytes

I was determined to solve this with regex, and I did. I did not really think it would be short.

```<code>def f(n,h):r=re.match(("([^{}]*)(.)"*len(n)).format(*n),h).groups();return"".join([i if i in n else"#"for i in"".join(["".join(d)for d in zip(["#"*len(i)for i in r[::2]],r[::-1][::2][::-1])])])
</code>```

Ungolfed:

```<code>def fs(needle, haystack):
    rx = "([^{}]*)(.)"
    rx *= len(needle)
    rx = rx.format(*needle)
    r  = re.match(rx, haystack).groups()
    nd = r[::-1][::2][::-1]
    hs = r[::2]
    hs = ["#" * len(i) for i in hs]
    nh = "".join([i if i in needle else "#" for i in "".join(["".join(d) for d in zip(hs, nd)])])
    return nh
</code>```

I wanted to do it with regex so I can do it again in Factor which, as a point-free functional language, does not do explicit looping. Haskell also does not do explicit looping and the Haskell solution does not use pattern matching but I don't understand the Haskell solution.

Here's what I used to come up with the regex.

Title: Filter this string!

Body:
Python 3, 197 bytes

I was determined to solve this with regex, and I did. I did not really think it would be short.

def f(n,h):r=re.match(("([^{}]*)(.)"*len(n)).format(*n),h).groups();return"".join([i if i in n else"#"for i in"".join(["".join(d)for d in zip(["#"*len(i)for i in r[::2]],r[::-1][::2][::-1])])])

Ungolfed:

def fs(needle, haystack):
    rx = "([^{}]*)(.)"
    rx *= len(needle)
    rx = rx.format(*needle)
    r  = re.match(rx, haystack).groups()
    nd = r[::-1][::2][::-1]
    hs = r[::2]
    hs = ["#" * len(i) for i in hs]
    nh = "".join([i if i in needle else "#" for i in "".join(["".join(d) for d in zip(hs, nd)])])
    return nh

I wanted to do it with regex so I can do it again in Factor which, as a point-free functional language, does not do explicit looping. Haskell also does not do explicit looping and the Haskell solution does not use pattern matching but I don't understand the Haskell solution.

Here's what I used to come up with the regex.


问:
Implement Amb and Require

The Challenge

Implement amb and its sister statement require in whatever language you wish. See http://community.schemewiki.org/?amb for an example implementation in Scheme. You can rename them to a and r.

amb statements select a value passed to it arbitrarily, and require statements written after amb contain conditionals that limit the possibilities that amb will return, as the conditionals must evaluate to true. statements The pseudocode

```<code>fun rand() {
    return amb(1, 2, 3, 4)
}
</code>```

will return whatever the computer feels like as long as it is 1, 2, 3 or 4. However the pseudocode

```<code>fun arbitary2 {
    x = amb(1, 2, 3, 4)
    y = square(x)
    require(even(y))
    return x
}
</code>```

can only ever eventually return 2 or 4, but a user may not know which one will return. Depending on implementation, 2 may always be returned, or 4, or 2 is returned 3% of the time and so on. require can be called any time after amb is called as long as both statements are in the same program, even outside of the scope of amb, so

```<code>fun foo() {
    amb(1,2,3,4)
}
x = foo()
y = foo()
require(x > y)
</code>```

is valid and x will never be less than y when the program successfully terminates. The degree to which this is possible varies language by language, so try your best to implement this. The following code should not successfully terminate:

```<code>amb(1, 2, 3, read("notes.txt"))
require(false)
print("this will never be printed")
</code>```

The actual names and exact syntax of amb and require don't matter. For example, if your implementation is in assembly, then having amb read from predefined registers is legitimate as long as the essence of amb is preserved, and require can checked whether a certain register contains a certain value.

Try your best and have fun!

Scoring

This has been changed from popcon to code-golf, so make your implementations short! Least number of characters wins. Don't cheat and rename existing implementations. Any submission which does something to the effect of:

```<code>#define r rename
#define a amb
</code>```

will be disqualified.

答:
Mathematica, 143 bytes

```<code>a={{}};b=e@Length@Last[a=Join@@Outer[Append,a,#,1]]&;c@z_:=a=Select[a,#~f~z&];d@z_:=RandomChoice[#~f~z&/@a];f=#2/.Thread[e/@Range@Length@#->#]&
</code>```

This code defines three functions. b (amb) and c (require) do what you expect, with amb taking a List of values and require taking an expression. d converts an amb expression to a human-readable value. As an upside, amb expressions act exactly like their values, with the final result being lazily evaluated during the d call. Gets slow when more than 3 amb expressions are entered. Could probably be golfed further.

Title: Implement Amb and Require

Body:
Mathematica, 143 bytes

a={{}};b=e@Length@Last[a=Join@@Outer[Append,a,#,1]]&;c@z_:=a=Select[a,#~f~z&];d@z_:=RandomChoice[#~f~z&/@a];f=#2/.Thread[e/@Range@Length@#->#]&

This code defines three functions. b (amb) and c (require) do what you expect, with amb taking a List of values and require taking an expression. d converts an amb expression to a human-readable value. As an upside, amb expressions act exactly like their values, with the final result being lazily evaluated during the d call. Gets slow when more than 3 amb expressions are entered. Could probably be golfed further.


问:
The rice and chess problem
An Indian legend tells the story of the alleged inventor of the chess game, who impressed the emperor of India with his game so much that he would get rewarded with anything asked.

The man said he wanted to be paid in rice. He wanted a grain of rice for the first square of the chessboard, two for the second, four for the third, eight for the fourth, and so on, until the 64th square.

The emperor was amazed that the man asked for such a small reward, but as his mathematicians started counting, he ended up losing one of his provinces.

Task

Given the length of the side of a hypothetical chessboard (which is 8 on a default chessboard) and the multiplier between squares (which is 2 in the legend), calculate the number of grains of rice the emperor must pay to the man.

Notes

The side length will always be a positive integer. The multiplier could instead be any kind of rational number.

If your language of choice can't display very large numbers, it's okay as long as your program can correctly process smaller inputs.

Also if your language of choice rounds larger values (with exponential notations), it's okay if those values are approximately correct.

Testcases

```<code>Input (side length, multiplier) => Output
8, 2                            => 18446744073709551615
3, 6                            => 2015539
7, 1.5                          => 850161998.2854
5, -3                           => 211822152361
256, 1                          => 65536
2, 2                            => 15
2, -2                           => -5
</code>```

Please note that the explicit formula

```<code>result = (multiplier ^ (side ^ 2) - 1) / (multiplier - 1)
</code>```

Performs wrong on multiplier = 1, as

```<code>1 ^ (side ^ 2) - 1 = 0
1 - 1 = 0
0 / 0 != side ^ 2 (as it should be)
</code>```

Scoring

This is code-golf. Shortest answer in bytes wins.

Title: The rice and chess problem

Body:
J, 17 bytes

A non-tacit solution, by defining a dyad:

f=:4 :'+/y^i.x^2'

e.g.

8x f 2

18446744073709551615


答:
Python 3.5, 67

```<code>def f(a,b):b=[*b];return"".join(y==b[0]and b.pop(0)or"#"for y in a)
</code>```

Ungolfed:

```<code>def f(a, b):
    b = [*b] #Convert string to list; yeah Python 3.5
    c = []
    for y in a:
       if y==b[0]:
          c.append(b.pop(0))
       else:
          c.append("#")
    return "".join(c)
</code>```

Try it here

Title: Filter this string!

Body:
Your task is to write a program that will filter out some characters in a string, so that the remaining spells out (part of) the other string.

Let's say we received the string "123456781234567812345678", and the second string is "314159".

First, we put a pointer on the second string:

```<code>314159
^
</code>```

So the pointer is now on 3, and we replace the not-3 characters with a hashtag until the first 3:

```<code>##3456781234567812345678
</code>```

We then move the pointer to the next character until we have iterated through the string.

Specs

You may use any character to replace "#", and the first string will not contain the hashtag (or the replaced hashtag).

The second string will always be longer than enough.

Both strings will only contain ASCII printable characters (U+0020-U+007F).

Testcases

```<code>input1: 123456781234567812345678
input2: 314159
output: ##3#####1##4####1###5###

input1: abcdefghijklmnopqrstuvwxyz
input2: dilemma
output: ###d####i##l##############
</code>```

Body:
Python 3.5, 67

def f(a,b):b=[*b];return"".join(y==b[0]and b.pop(0)or"#"for y in a)

Ungolfed:

def f(a, b):
    b = [*b] #Convert string to list; yeah Python 3.5
    c = []
    for y in a:
       if y==b[0]:
          c.append(b.pop(0))
       else:
          c.append("#")
    return "".join(c)

Try it here


答:
Scala, 406/377 Bytes

I offer two golfed versions of my implementation, one that chooses the value randomly and one that (somehow) abuses the task description and always returns the first legal value. It's up to you, with one to consider (the latter one is shorter, obviously):

```<code>trait A[X]{def g=scala.util.Random.shuffle(l).head;def l:Seq[X];def -(d:X)};class M{def a[X](e:Seq[X])=new A[X]{var s=e;def l=s;def -(d:X)=s=s.filter(_!=d)};def r(v:A[Boolean])=v-false;def p[X,Y](a:A[X],b:A[Y])=new A[(X,Y)]{var x=List[Any]();def l=(for(e<-a.l;f<-b.l)yield(e,f)).diff(x);def -(d:(X,Y))=x::=d};def o[X,Y](v:A[X],f:X=>Y)=new A[Y]{def l=v.l.map(f);def -(d:Y)=v.l.filter(f(_)==d).foreach(v.-)}}
trait A[X]{def g=l(0);def l:Seq[X];def -(d:X)};class M{def a[X](e:Seq[X])=new A[X]{var s=e;def l=s;def -(d:X)=s=s.filter(_!=d)};def r(v:A[Boolean])=v-false;def p[X,Y](a:A[X],b:A[Y])=new A[(X,Y)]{var x=List[Any]();def l=(for(e<-a.l;f<-b.l)yield(e,f)).diff(x);def -(d:(X,Y))=x::=d};def o[X,Y](v:A[X],f:X=>Y)=new A[Y]{def l=v.l.map(f);def -(d:Y)=v.l.filter(f(_)==d).foreach(v.-)}}
</code>```

This versions are more or less just golfed versions of my initial submission (some implementations have changed slightly, but the interfaces were quite stable). Therefore I will not explain it any further but refer to my initial post. Just have in mind that everything that was "for convenience" now disappeared. And a lot of renaming happened. The only difference is that pairs are now a bit like new amb-values: If you define conditions on top of pairs this will never effect the underlying values (nevertheless, manipulating the underlying values will still affect the pairs).

To give you a hint on how to use this versions, here is a short testing code I used while golfing:

```<code>  val m = new M
  val a1 = m.a(List(1, 2, 3, 4, 5))
  val a2 = m.a(List(4, 5, 6))
  val a12 = m.p(a1, a2)
  m.r(m.o(a12, (p:(Int, Int)) => p._1 > p._2))
  m.r(m.o(a1, (e: Int) => e%2==1))

  println(a1.l)
  println(a2.l)
  println(a12.l)
  println(a12.g)
</code>```

As you can see, the offered functions are now instance-methods, hence, you need an instance of M to interact with my library (this saved me one glorious byte).

Note that my ungolfed version (which I will not update any more) now includes natural syntax for the most common Int- and Boolean-operations.

(my initial submission)

Right before posting this answer the Mathematica answer was stated and it looks as if my solution is based on similar assumptions. Nevertheless, I will offer my solution, too, because I didn't copied the former answer as it wasn't there when I started.

I didn't tried to recreate a natural syntax (like: (amb(1, 2, 3) + 3) * 5, etc), but this would be possible if you like to implement the necessary implicit conversions. I chose the functional way as you will see later.

Let's start with the two keywords:

```<code>import ambiguous.AmbOps.op

object Amb {
  def amb[A](args: A*): AmbType[A] =
        new BasicAmb[A](args.toList)
  def require(amb: AmbType[Boolean]): Unit =
        amb.del(false)
  def require[A](amb: AmbType[A], predicate: A => Boolean): Unit =
        require(op(amb, predicate))
  def require[A, B](amb: AmbType[(A, B)], predicate: (A, B) => Boolean): Unit =
        require(op(amb, predicate))
}
</code>```

The amb-method is quite straight forward, you provide some values and get some container, that may return a value back (more on that later).
I offer three require methods but they are all based on the first one, so the others are just for convenience. Let me explain the first one (the others will become clear as you read on): If you have some boolean amb-Container and call require, all false values are eliminated.

But how is an amb-value of arbitrary type converted into a boolean value? By offering a conversion-policy:

```<code>object AmbOps {
  def op[A, B](amb: AmbType[A], op: A => B): AmbType[B] =
        new OpAmb[B, A](amb, op)
  def op[A, B, C](amb: AmbType[(A, B)], op: (A, B) => C): AmbType[C] =
        new OpAmb[C, (A, B)](amb, p => op(p._1, p._2))
  def pair[A, B](ambA: AmbType[A], ambB: AmbType[B]): AmbType[(A, B)] =
        new AmbPair[A, B](ambA, ambB)
}
</code>```

Assume we have some numerical amb-value and want to square each element, then just call op with a corresponding function: op(amb(1, 2, 4), (e: Int) => e * e) // returns a value equivalent to amb(1, 4, 16) Following the same scheme you can convert the elements to boolean values for example with op(amb(1, 2, 4), (e: Int) => e%2 == 0)

If you have several amb-values and you want to define conditions between them, it isn't that easy to do with my approach when only using amb, require and op. Therefore I defined the method pair. With pair you can create tuples/pairs out of two amb-values (or any number if you again pair pairs with other values or pairs). If you then define conditions on top of this tuples, the illegal pairs will be eliminated. But the original values aren't always manipulated. Only if this process leads to the situation that one element from one of the initial amb-values is no longer legal in any tuple, than this value is completely eliminated from the initial amb-value. If now some other amb-value (or pair) is based on this manipulated amb-value, the dependent value will also miss the deleted element.

That means that if you need a pair of values fulfilling a condition, you have to get an element from the pair-value and you cannot always rely on the original values, but I think this is a acceptable limitation.

Just for convenience there is an additional op-method for tuples.

Now we have to dig deeper into the technical details of the amb-containers:

```<code>import scala.util.Random

trait AmbType[A] {
  def get: A = {
    if (list.isEmpty)
      throw new IllegalStateException("no value left")
    else list(Random.nextInt(list.length))}
  private[ambiguous] def list: List[A]
  private[ambiguous] def del(a: A): Unit
}

class BasicAmb[A](private var args: List[A]) extends AmbType[A] {
  override private[ambiguous] def list: List[A] = args
  override private[ambiguous] def del(a: A): Unit = { args = args.filterNot(_ == a)}
}

class OpAmb[A, B](amb: AmbType[B], op: B => A) extends AmbType[A] {
  override private[ambiguous] def list: List[A] = amb.list.map(op)
  override private[ambiguous] def del(a: A): Unit = amb.list.filter(op(_) == a).foreach(amb.del)
}

class AmbPair[A, B](ambA: AmbType[A], ambB: AmbType[B]) extends AmbType[(A, B)] {
  private var deleted: List[(A, B)] = List()
  override private[ambiguous] def list: List[(A, B)] =
    ambA.list.flatMap(a => ambB.list.map(b => (a, b))).diff(deleted)
  override private[ambiguous] def del(a: (A, B)): Unit = {
    deleted ::= a
    ambA.list.filter(a => !list.exists(_._1 == a)).foreach(a => {ambA.del(a); deleted = deleted.filterNot(_._1 == a)})
    ambB.list.filter(b => !list.exists(_._2 == b)).foreach(b => {ambB.del(b); deleted = deleted.filterNot(_._2 == b)})
  }
}
</code>```

I don't want to say too much about the classes but one thing is worth mentioning: If you create pairs of two amb-values and define some conditions on top of them and afterwards define some further conditions on top of one of the original values, the pair-class misses to check if an element of the not-changed original value may be deleted as it doesn't appear as part of one pair any more. So some further observer-pattern would be great.

Now let's take a look on how to use this:

```<code>// create amb-values by invoking amb
val a = amb(1, 2, 3, 4)

// do some maths on a value
val b = op(a, (e: Int) => e + 2)

// define some conditions
require(b, (e: Int) => e%3 == 0)
// or first apply the condition to the value and afterwards pass the value to require
val filtered = op(b, (e: Int) => e%3 == 0)
require(filtered)

// pair values
val paired = pair(a, amb("hello", "welcome"))
// note that the amb-value a now only contains the elements 1 and 4 as the former requirement eliminated the other two

// state a condition on pairs
require(paired, (a: Int, b: String) => b.length % a == 0)
// now the amb-value a only contains the element 1 as there was no string with length divisible by 4

// query a value from our pairs (by calling get)
val selected = paired.get
// at this point only two pairs are left, so selected will always be either (1, "hello") or (1, "welcome")
val number = selected._1
val greetings = selected._2
</code>```

Title: Implement Amb and Require

Body:
The Challenge

Implement amb and its sister statement require in whatever language you wish. See http://community.schemewiki.org/?amb for an example implementation in Scheme. You can rename them to a and r.

amb statements select a value passed to it arbitrarily, and require statements written after amb contain conditionals that limit the possibilities that amb will return, as the conditionals must evaluate to true. statements The pseudocode

```<code>fun rand() {
    return amb(1, 2, 3, 4)
}
</code>```

will return whatever the computer feels like as long as it is 1, 2, 3 or 4. However the pseudocode

```<code>fun arbitary2 {
    x = amb(1, 2, 3, 4)
    y = square(x)
    require(even(y))
    return x
}
</code>```

can only ever eventually return 2 or 4, but a user may not know which one will return. Depending on implementation, 2 may always be returned, or 4, or 2 is returned 3% of the time and so on. require can be called any time after amb is called as long as both statements are in the same program, even outside of the scope of amb, so

```<code>fun foo() {
    amb(1,2,3,4)
}
x = foo()
y = foo()
require(x > y)
</code>```

is valid and x will never be less than y when the program successfully terminates. The degree to which this is possible varies language by language, so try your best to implement this. The following code should not successfully terminate:

```<code>amb(1, 2, 3, read("notes.txt"))
require(false)
print("this will never be printed")
</code>```

The actual names and exact syntax of amb and require don't matter. For example, if your implementation is in assembly, then having amb read from predefined registers is legitimate as long as the essence of amb is preserved, and require can checked whether a certain register contains a certain value.

Try your best and have fun!

Scoring

This has been changed from popcon to code-golf, so make your implementations short! Least number of characters wins. Don't cheat and rename existing implementations. Any submission which does something to the effect of:

```<code>#define r rename
#define a amb
</code>```

will be disqualified.

Body:
Scala, 406/377 Bytes

I offer two golfed versions of my implementation, one that chooses the value randomly and one that (somehow) abuses the task description and always returns the first legal value. It's up to you, with one to consider (the latter one is shorter, obviously):

trait A[X]{def g=scala.util.Random.shuffle(l).head;def l:Seq[X];def -(d:X)};class M{def a[X](e:Seq[X])=new A[X]{var s=e;def l=s;def -(d:X)=s=s.filter(_!=d)};def r(v:A[Boolean])=v-false;def p[X,Y](a:A[X],b:A[Y])=new A[(X,Y)]{var x=List[Any]();def l=(for(e<-a.l;f<-b.l)yield(e,f)).diff(x);def -(d:(X,Y))=x::=d};def o[X,Y](v:A[X],f:X=>Y)=new A[Y]{def l=v.l.map(f);def -(d:Y)=v.l.filter(f(_)==d).foreach(v.-)}}
trait A[X]{def g=l(0);def l:Seq[X];def -(d:X)};class M{def a[X](e:Seq[X])=new A[X]{var s=e;def l=s;def -(d:X)=s=s.filter(_!=d)};def r(v:A[Boolean])=v-false;def p[X,Y](a:A[X],b:A[Y])=new A[(X,Y)]{var x=List[Any]();def l=(for(e<-a.l;f<-b.l)yield(e,f)).diff(x);def -(d:(X,Y))=x::=d};def o[X,Y](v:A[X],f:X=>Y)=new A[Y]{def l=v.l.map(f);def -(d:Y)=v.l.filter(f(_)==d).foreach(v.-)}}

This versions are more or less just golfed versions of my initial submission (some implementations have changed slightly, but the interfaces were quite stable). Therefore I will not explain it any further but refer to my initial post. Just have in mind that everything that was "for convenience" now disappeared. And a lot of renaming happened. The only difference is that pairs are now a bit like new amb-values: If you define conditions on top of pairs this will never effect the underlying values (nevertheless, manipulating the underlying values will still affect the pairs).

To give you a hint on how to use this versions, here is a short testing code I used while golfing:

  val m = new M
  val a1 = m.a(List(1, 2, 3, 4, 5))
  val a2 = m.a(List(4, 5, 6))
  val a12 = m.p(a1, a2)
  m.r(m.o(a12, (p:(Int, Int)) => p._1 > p._2))
  m.r(m.o(a1, (e: Int) => e%2==1))

  println(a1.l)
  println(a2.l)
  println(a12.l)
  println(a12.g)

As you can see, the offered functions are now instance-methods, hence, you need an instance of M to interact with my library (this saved me one glorious byte).

Note that my ungolfed version (which I will not update any more) now includes natural syntax for the most common Int- and Boolean-operations.

(my initial submission)

Right before posting this answer the Mathematica answer was stated and it looks as if my solution is based on similar assumptions. Nevertheless, I will offer my solution, too, because I didn't copied the former answer as it wasn't there when I started.

I didn't tried to recreate a natural syntax (like: (amb(1, 2, 3) + 3) * 5, etc), but this would be possible if you like to implement the necessary implicit conversions. I chose the functional way as you will see later.

Let's start with the two keywords:

import ambiguous.AmbOps.op

object Amb {
  def amb[A](args: A*): AmbType[A] =
        new BasicAmb[A](args.toList)
  def require(amb: AmbType[Boolean]): Unit =
        amb.del(false)
  def require[A](amb: AmbType[A], predicate: A => Boolean): Unit =
        require(op(amb, predicate))
  def require[A, B](amb: AmbType[(A, B)], predicate: (A, B) => Boolean): Unit =
        require(op(amb, predicate))
}

The amb-method is quite straight forward, you provide some values and get some container, that may return a value back (more on that later).
I offer three require methods but they are all based on the first one, so the others are just for convenience. Let me explain the first one (the others will become clear as you read on): If you have some boolean amb-Container and call require, all false values are eliminated.

But how is an amb-value of arbitrary type converted into a boolean value? By offering a conversion-policy:

object AmbOps {
  def op[A, B](amb: AmbType[A], op: A => B): AmbType[B] =
        new OpAmb[B, A](amb, op)
  def op[A, B, C](amb: AmbType[(A, B)], op: (A, B) => C): AmbType[C] =
        new OpAmb[C, (A, B)](amb, p => op(p._1, p._2))
  def pair[A, B](ambA: AmbType[A], ambB: AmbType[B]): AmbType[(A, B)] =
        new AmbPair[A, B](ambA, ambB)
}

Assume we have some numerical amb-value and want to square each element, then just call op with a corresponding function: op(amb(1, 2, 4), (e: Int) => e * e) // returns a value equivalent to amb(1, 4, 16) Following the same scheme you can convert the elements to boolean values for example with op(amb(1, 2, 4), (e: Int) => e%2 == 0)

If you have several amb-values and you want to define conditions between them, it isn't that easy to do with my approach when only using amb, require and op. Therefore I defined the method pair. With pair you can create tuples/pairs out of two amb-values (or any number if you again pair pairs with other values or pairs). If you then define conditions on top of this tuples, the illegal pairs will be eliminated. But the original values aren't always manipulated. Only if this process leads to the situation that one element from one of the initial amb-values is no longer legal in any tuple, than this value is completely eliminated from the initial amb-value. If now some other amb-value (or pair) is based on this manipulated amb-value, the dependent value will also miss the deleted element.

That means that if you need a pair of values fulfilling a condition, you have to get an element from the pair-value and you cannot always rely on the original values, but I think this is a acceptable limitation.

Just for convenience there is an additional op-method for tuples.

Now we have to dig deeper into the technical details of the amb-containers:

import scala.util.Random

trait AmbType[A] {
  def get: A = {
    if (list.isEmpty)
      throw new IllegalStateException("no value left")
    else list(Random.nextInt(list.length))}
  private[ambiguous] def list: List[A]
  private[ambiguous] def del(a: A): Unit
}

class BasicAmb[A](private var args: List[A]) extends AmbType[A] {
  override private[ambiguous] def list: List[A] = args
  override private[ambiguous] def del(a: A): Unit = { args = args.filterNot(_ == a)}
}

class OpAmb[A, B](amb: AmbType[B], op: B => A) extends AmbType[A] {
  override private[ambiguous] def list: List[A] = amb.list.map(op)
  override private[ambiguous] def del(a: A): Unit = amb.list.filter(op(_) == a).foreach(amb.del)
}

class AmbPair[A, B](ambA: AmbType[A], ambB: AmbType[B]) extends AmbType[(A, B)] {
  private var deleted: List[(A, B)] = List()
  override private[ambiguous] def list: List[(A, B)] =
    ambA.list.flatMap(a => ambB.list.map(b => (a, b))).diff(deleted)
  override private[ambiguous] def del(a: (A, B)): Unit = {
    deleted ::= a
    ambA.list.filter(a => !list.exists(_._1 == a)).foreach(a => {ambA.del(a); deleted = deleted.filterNot(_._1 == a)})
    ambB.list.filter(b => !list.exists(_._2 == b)).foreach(b => {ambB.del(b); deleted = deleted.filterNot(_._2 == b)})
  }
}

I don't want to say too much about the classes but one thing is worth mentioning: If you create pairs of two amb-values and define some conditions on top of them and afterwards define some further conditions on top of one of the original values, the pair-class misses to check if an element of the not-changed original value may be deleted as it doesn't appear as part of one pair any more. So some further observer-pattern would be great.

Now let's take a look on how to use this:

// create amb-values by invoking amb
val a = amb(1, 2, 3, 4)

// do some maths on a value
val b = op(a, (e: Int) => e + 2)

// define some conditions
require(b, (e: Int) => e%3 == 0)
// or first apply the condition to the value and afterwards pass the value to require
val filtered = op(b, (e: Int) => e%3 == 0)
require(filtered)

// pair values
val paired = pair(a, amb("hello", "welcome"))
// note that the amb-value a now only contains the elements 1 and 4 as the former requirement eliminated the other two

// state a condition on pairs
require(paired, (a: Int, b: String) => b.length % a == 0)
// now the amb-value a only contains the element 1 as there was no string with length divisible by 4

// query a value from our pairs (by calling get)
val selected = paired.get
// at this point only two pairs are left, so selected will always be either (1, "hello") or (1, "welcome")
val number = selected._1
val greetings = selected._2


问:
'Add' up the letters in a word
My dad is a retired teacher, and he used to give combined spelling and math quizzes, where the student would spell a word, and then 'score' the word by adding up the letters, where a=1, b=2, etc. (e.g. cat = 3+1+20=24).  This made grading the quizzes easier, as he would just have to check for incorrect 'scores' rather than incorrectly spelled words, and had the added benefit of testing 2 skills at once.

He hired a friend of mine to write a program that would score words for him, so he could generate lengthy answer keys without error.  This problem is inspired by that program.

Requirements:

Accept any word with uppercase and lowercase letters

Return an error for any special characters, i.e. spaces, hyphens, @^%# etc.

a=1, b=2,... and A=1, B=2,...

Print the score of the word

(Optional) check that the word is in a dictionary after scoring, and print a warning if it is not.

No importing an external letter->number dictionary.  You must generate it yourself.

Any language is acceptable. This is similar to the 'digital root battle,' but much simpler.

答:
JavaScript, 60 bytes

```<code>s=>[...s.toUpperCase()].reduce((a,b)=>a+b.charCodeAt()-64,0)
</code>```

If the program must return an error on invalid inputs, then 80 bytes:

```<code>s=>/[^a-z]/i.test(s)?_:[...s.toUpperCase()].reduce((a,b)=>a+b.charCodeAt()-64,0)
</code>```

If an input is invalid, then the console will say that _ is not defined (there must not already be a variable defined called _).

Title: 'Add' up the letters in a word

Body:
JavaScript, 60 bytes

s=>[...s.toUpperCase()].reduce((a,b)=>a+b.charCodeAt()-64,0)

If the program must return an error on invalid inputs, then 80 bytes:

s=>/[^a-z]/i.test(s)?_:[...s.toUpperCase()].reduce((a,b)=>a+b.charCodeAt()-64,0)

If an input is invalid, then the console will say that _ is not defined (there must not already be a variable defined called _).


答:
Perl 6, 80 bytes

```<code>{$_>1&&.[0].value==.[1].value??""!!.[0].key given .lc.words.Bag.sort:{-.value}}
</code>```

Let's split the answer into two parts...

```<code>given .lc.words.Bag.sort:{-.value}
</code>```

given is a control statement (like if or for). In Perl 6, they're allowed as postfixes. (a if 1, or like here, foo given 3). given puts its topic (right-hand side) into the special variable $_ for its left-hand side.

The "topic" itself lowercases (lc), splits by word (words), puts the values into a Bag (set with number of occurences), then sorts by value (DESC). Since sort only knows how to operate on lists, the Bag is transformed into a List of Pairs here.

```<code>$_>1&&.[0].value==.[1].value??""!!.[0].key
</code>```

a simple conditional (?? !! are used in Perl 6, instead of ? :).

```<code>$_ > 1
</code>```

Just checks that the list has more than one element.

```<code>.[0].value==.[1].value
</code>```

Accesses to $_ can be shortened... By not specifying the variable. .a is exactly like $_.a. So this is effectively "do both top elements have the same number of occurences" – If so, then we print '' (the empty string).

Otherwise, we print the top element's key (the count): .[0].key.

Title: What is the most frequent word?

Body:
What is the most frequent word?

Given a sentence, your program must make its way through it, counting the frequencies of each word, then output the most used word. Because a sentence has no fixed length, and so can get very long, your code must be as short as possible.

Rules/Requirements

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

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

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

Your program must not write anything to STDERR.

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

Standard loopholes are forbidden.

Your program must be case-insensitive (tHe, The and the all contribute to the count of the).

If there is no most frequent word (see test case #3), your program should output nothing.

Definition of a 'word':

You get the list of words by splitting the input text on spaces. The input will never contain any other type of whitespace than plain spaces (in particular no newlines). However, the final words should only contain alphanumerics (a-z, A-Z, 0-9), hyphens (-) and apostrophes ('). You can make that so by removing all other characters or by replacing them by space before doing the word splitting. To remain compatible with previous versions of the rules, apostrophes are not required to be included.

Test Cases

```<code>The man walked down the road.
==> the

-----

Slowly, he ate the pie, savoring each delicious bite. He felt like he was truly happy.
==> he

-----

This sentence has no most frequent word.
==>

-----

"That's... that's... that is just terrible!" he said.
==> that's / thats

-----

The old-fashioned man ate an old-fashioned cake.
==> old-fashioned

-----

IPv6 looks great, much better than IPv4, except for the fact that IPv6 has longer addresses.
==> IPv6

-----

This sentence with words has at most two equal most frequent words.
==>
</code>```

Note: The third and seventh test cases have no output, you may choose either on the fourth.

Scoring

Programs are scored according to bytes. The usual character set is UTF-8, if you are using another please specify.

When the challenge finishes, the program with the least bytes (it's called code-golf), will win.

Submissions

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

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

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

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

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

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

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

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

Leaderboard

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

/* Configuration */

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

/* App */

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

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

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

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

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

getAnswers();

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

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

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

function process() {
  var valid = [];

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

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

  });

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

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

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

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

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

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

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

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

table thead {
  font-weight: bold;
}

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

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

```

Body:
Perl 6, 80 bytes

{$_>1&&.[0].value==.[1].value??""!!.[0].key given .lc.words.Bag.sort:{-.value}}

Let's split the answer into two parts...

given .lc.words.Bag.sort:{-.value}

given is a control statement (like if or for). In Perl 6, they're allowed as postfixes. (a if 1, or like here, foo given 3). given puts its topic (right-hand side) into the special variable $_ for its left-hand side.

The "topic" itself lowercases (lc), splits by word (words), puts the values into a Bag (set with number of occurences), then sorts by value (DESC). Since sort only knows how to operate on lists, the Bag is transformed into a List of Pairs here.

$_>1&&.[0].value==.[1].value??""!!.[0].key

a simple conditional (?? !! are used in Perl 6, instead of ? :).

$_ > 1

Just checks that the list has more than one element.

.[0].value==.[1].value

Accesses to $_ can be shortened... By not specifying the variable. .a is exactly like $_.a. So this is effectively "do both top elements have the same number of occurences" – If so, then we print '' (the empty string).

Otherwise, we print the top element's key (the count): .[0].key.


答:
Jelly, 25 bytes

```<code>ṣ⁶f€ØB;”-¤Œl©Qµ®ċÐ€ĠṪịµẋE
</code>```

Try it online! or verify all test cases.

Title: What is the most frequent word?

Body:
Jelly, 25 bytes

ṣ⁶f€ØB;”-¤Œl©Qµ®ċÐ€ĠṪịµẋE

Try it online! or <a href="http://jelly.tryitonline.net/#code=4bmj4oG2ZuKCrMOYQjvigJ0twqTFkmzCqVHCtcKuxIvDkOKCrMSg4bmq4buLwrXhuotFCsOH4oKsauKBtw&input=&args=WycnJ1RoZSBtYW4gd2Fsa2VkIGRvd24gdGhlIHJvYWQuJycnLCAnJydTbG93bHksIGhlIGF0ZSB0aGUgcGllLCBzYXZvcmluZyBlYWNoIGRlbGljaW91cyBiaXRlLiBIZSBmZWx0IGxpa2UgaGUgd2FzIHRydWx5IGhhcHB5LicnJywgJycnVGhpcyBzZW50ZW5jZSBoYXMgbm8gbW9zdCBmcmVxdWVudCB3b3JkLicnJywgJycnVGhhdCdzLi4uIHRoYXQncy4uLiB0aGF0IGlzIGp1c3QgdGVycmlibGUhIiBoZSBzYWlkLicnJywgJycnVGhlIG9sZC1mYXNoaW9uZWQgbWFuIGF0ZSBhbiBvbGQtZmFzaGlvbmVkIGNha2UuJycnLCAnJydJUHY2IGxvb2tzIGdyZWF0LCBtdWNoIGJldHRlciB0aGFuIElQdjQsIGV4Y2VwdCBmb3IgdGhlIGZhY3QgdGhhdCBJUHY2IGhhcyBsb25nZXIgYWRkcmVzc2VzLicnJ10">verify all test cases.


答:
JavaScript, 68 Bytes

This can almost certainly be golfed more

w=>[...w.toLowerCase()].map(v=>v.charCodeAt()-96).reduce((a,b)=>a+b)
```

<h2>With dictionary check (Node.js & Unix Descendants only) 195 Bytes</h2>

<p>Uses <code>/usr/share/dict/words</code>, and can definitely be shortened (see the warn message)</p>

<pre class="lang-js prettyprint-override"><code>w=>(require("fs").readFile("/usr/share/dict/words",(e,t)=>!(t+"").split`
`.includes(w=w.toLowerCase())&&console.warn(w+" not found in dict")),[...w].map(v=>v.charCodeAt()-96).reduce((a,b)=>a+b))
</code>```

Title: 'Add' up the letters in a word

Body:
My dad is a retired teacher, and he used to give combined spelling and math quizzes, where the student would spell a word, and then 'score' the word by adding up the letters, where a=1, b=2, etc. (e.g. cat = 3+1+20=24).  This made grading the quizzes easier, as he would just have to check for incorrect 'scores' rather than incorrectly spelled words, and had the added benefit of testing 2 skills at once.

He hired a friend of mine to write a program that would score words for him, so he could generate lengthy answer keys without error.  This problem is inspired by that program.

Requirements:

Accept any word with uppercase and lowercase letters

Return an error for any special characters, i.e. spaces, hyphens, @^%# etc.

a=1, b=2,... and A=1, B=2,...

Print the score of the word

(Optional) check that the word is in a dictionary after scoring, and print a warning if it is not.

No importing an external letter->number dictionary.  You must generate it yourself.

Any language is acceptable. This is similar to the 'digital root battle,' but much simpler.

Body:
JavaScript, 68 Bytes

This can almost certainly be golfed more

w=>[...w.toLowerCase()].map(v=>v.charCodeAt()-96).reduce((a,b)=>a+b)

With dictionary check (Node.js & Unix Descendants only) 195 Bytes

Uses /usr/share/dict/words, and can definitely be shortened (see the warn message)

w=>(require("fs").readFile("/usr/share/dict/words",(e,t)=>!(t+"").split`
`.includes(w=w.toLowerCase())&&console.warn(w+" not found in dict")),[...w].map(v=>v.charCodeAt()-96).reduce((a,b)=>a+b))


问:
Binary representation of a number is palindrome or not?
Write a full program  to find whether the binary representation of a number is palindrome or not?

```<code>Sample Input
5

Sample Output
YES
</code>```

Print YES if binary representation is palindrome and NO otherwise.

Body:
J: 24

((-:|.)#:x){2 3$'NO YES'

eg:

   ((-:|.)#:5){2 3$'NO YES'
YES
   ((-:|.)#:12){2 3$'NO YES'
NO
   ((-:|.)#:125){2 3$'NO YES'
NO
   ((-:|.)#:63){2 3$'NO YES'
YES

ContentLicense: CC BY-SA 2.5


答:
Matlab (225)

Rules chaneged :/

.

```<code>      function c=f(a),t=@(x)feval(@(y)y(y>32),num2str(lower(x)-0));f=@(x)num2str(nnz(x)+1);e=str2num(regexprep(a,'([\w''-]+)',' ${t($1)} ${f($`)} ${f([$`,$1])}'));[u,r,d]=mode(e);try c=find(e==d{:});c=a((e(c(1)+1)):(e(c(1)+2)));end
</code>```

Toolbox is necessary to run this.

How does this work, one of the nicest privileges of regex replace in matlab this it field-executes tokens by calling external-environmental functions parameterized by the tokens caught in the inner environment, so any sequence of "Word_A Word_B .." is replaced by integers "A0 A1 A2 B0 B1 B2 ..." where the first integer is the numerica ascii signature of the word, the second is the starting index, the third is the ending index, these last two integers dont reduplicate in the whole sequence so i took this advantage to transpose it to an array, then  mode it then search the result in that array, so the starting/ending indices will consequently follow.

Edit: after changing some details, the program is called function by a string parameter.

20 bytes saved thanks to @StewieGriffin, 30 bytes added reproaches to common-agreed loopholes.

Title: What is the most frequent word?

Body:
Matlab (225)

Rules chaneged :/

.

      function c=f(a),t=@(x)feval(@(y)y(y>32),num2str(lower(x)-0));f=@(x)num2str(nnz(x)+1);e=str2num(regexprep(a,'([\w''-]+)',' ${t($1)} ${f($`)} ${f([$`,$1])}'));[u,r,d]=mode(e);try c=find(e==d{:});c=a((e(c(1)+1)):(e(c(1)+2)));end

Toolbox is necessary to run this.

How does this work, one of the nicest privileges of regex replace in matlab this it field-executes tokens by calling external-environmental functions parameterized by the tokens caught in the inner environment, so any sequence of "Word_A Word_B .." is replaced by integers "A0 A1 A2 B0 B1 B2 ..." where the first integer is the numerica ascii signature of the word, the second is the starting index, the third is the ending index, these last two integers dont reduplicate in the whole sequence so i took this advantage to transpose it to an array, then  mode it then search the result in that array, so the starting/ending indices will consequently follow.

Edit: after changing some details, the program is called function by a string parameter.

20 bytes saved thanks to @StewieGriffin, 30 bytes added reproaches to common-agreed loopholes.


答:
Python, 132 bytes

import collections as C,re
def g(s):(a,i),(b,j)=C.Counter(re.sub('[^\w\s-]','',s.lower()).split()).most_common(2);return[a,''][i==j]
```

Above code assumes that input has at least two words.

Title: What is the most frequent word?

Body:
Python, 132 bytes

import collections as C,re
def g(s):(a,i),(b,j)=C.Counter(re.sub('[^\w\s-]','',s.lower()).split()).most_common(2);return[a,''][i==j]

Above code assumes that input has at least two words.


答:
JavaScript (ES6), 155 bytes

```<code>s=>(m=new Map,s.toLowerCase().replace(/[^- 0-9A-Z]/gi,'').split(/\ +/).map(w=>m.set(w,-~m.get(w))),[[a,b],[c,d]]=[...m].sort(([a,b],[c,d])=>d-b),b==d?'':a)
</code>```

Based on @Blue's Python answer.

Title: What is the most frequent word?

Body:
JavaScript (ES6), 155 bytes

s=>(m=new Map,s.toLowerCase().replace(/[^- 0-9A-Z]/gi,'').split(/\ +/).map(w=>m.set(w,-~m.get(w))),[[a,b],[c,d]]=[...m].sort(([a,b],[c,d])=>d-b),b==d?'':a)

Based on @Blue's Python answer.


答:
Python 3.5, 142 137 134 112 117 <s>110</s> 127 bytes:

(+17 bytes, because apparently even if there are words more frequent than the rest, but they have the same frequency, nothing should still be returned.)

def g(u):import re;q=re.findall(r"\b['\-\w]+\b",u.lower());Q=q.count;D=[*map(Q,{*q})];return['',max(q,key=Q)][1in map(D.count,D)]
```
<p>Should now satisfy all conditions. This submission assumes that at least 1 word is input.</p>
<p>Try It Online! (Ideone)</p>
<p>Also, if you want one, here is another version of my function devoid of any regular expressions at the cost of about 43 bytes, though this one is non-competitive anyways, so it does not really matter. I just put it here for the heck of it:</p>
<pre class="lang-py prettyprint-override"><code>def g(u):import re;q=''.join([i for i in u.lower()if i in[*map(chr,range(97,123)),*"'- "]]).split();Q=q.count;D=[*map(Q,{*q})];return['',max(q,key=Q)][1in map(D.count,D)]
</code>```

Try this New Version Online! (Ideone)

Title: What is the most frequent word?

Body:
Python 3.5, 142 137 134 112 117 <s>110</s> 127 bytes:

(+17 bytes, because apparently even if there are words more frequent than the rest, but they have the same frequency, nothing should still be returned.)

def g(u):import re;q=re.findall(r"\b['\-\w]+\b",u.lower());Q=q.count;D=[*map(Q,{*q})];return['',max(q,key=Q)][1in map(D.count,D)]

Should now satisfy all conditions. This submission assumes that at least 1 word is input.

Try It Online! (Ideone)

Also, if you want one, here is another version of my function devoid of any regular expressions at the cost of about 43 bytes, though this one is non-competitive anyways, so it does not really matter. I just put it here for the heck of it:

def g(u):import re;q=''.join([i for i in u.lower()if i in[*map(chr,range(97,123)),*"'- "]]).split();Q=q.count;D=[*map(Q,{*q})];return['',max(q,key=Q)][1in map(D.count,D)]

Try this New Version Online! (Ideone)


答:
Python 3, <s>58</s> 55

```<code>print(sum(ord(x)%32for x in input()if x.isalpha()or z))
</code>```

without dictionary or stolen idea but still unhelpful error ;)

thx @Eᴀsᴛᴇʀʟʏ

Test here.

Title: 'Add' up the letters in a word

Body:
Python 3, <s>58</s> 55

print(sum(ord(x)%32for x in input()if x.isalpha()or z))

without dictionary or stolen idea but still unhelpful error ;)

thx @Eᴀsᴛᴇʀʟʏ

Test here.