text:
My Pet Peeve Challenge
There's something (well, many things ) that really annoys me. It is when dictionaries (English, not Pythonic) use the defining word itself to define the word, also called circular definitions. Example:

reticence: the quality of being reticent

-- Apple Dictionary

Circular definition: a definition that is circular

-- Wikipedia (in jest)
Anyway,
Challenge
You are given a set of dictionary definitions. Your program should output the number of circular definitions in the input. As usual, code golf, lowest bytes wins, no standard loopholes, yada yada.
Input
Input can be in any reasonable form, including:

A dictionary (oh, the irony)
A list of strings
Line-by-line input, from STDIN or equivalent

You will be given the defined word (it is a single word without spaces) and its definition, possibly containing the defined word itself.
Circular definitions?
A definition is circular for the purposes of this challenge if it satisfies one of the following conditions:

The definition contains the defined word
The definition contains the defined word minus one of these suffixes:

-ing
-ed
-ly

The definition contains the defined word plus one of the above suffixes

Output
You should output an integer stating the number of circular definitions in the input. If there are none, you can output zero, a falsy, or a nully.
Good luck!
Leaderboards
Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language.
To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:
# Language Name, N bytes

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:
# Ruby, <s>104</s> <s>101</s> 96 bytes

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:
# Perl, 43 + 2 (-p flag) = 45 bytes

You can also make the language name a link which will then show up in the leaderboard snippet:
# [><>](http://esolangs.org/wiki/Fish), 121 bytes

/* Configuration */

var QUESTION_ID = 100007; // Obtain this from the url
// It will be likes://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page
var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";
var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk";
var OVERRIDE_USER = 47670; // 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);
  }

}
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;
}

<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

Wow, 100007! Is ID counting network wide or site wide?

It's ironic (adj: using or characterized by irony) that your first example definition (reticence) would not count as circular by your rules ;)

The count is site-wide. We reached 100,000 posts just an hour ago :-) If it was network-wide, we'd be around 50 million...

Yeah... just trying to simplify things a bit @Geobits!

I don't believe the second example definition (Circular definition) counts as circular either, unless you want a much more complex level of language processing than the question implies...

On a related note: 1) Do we have to worry about upper/lowercase? 2) Will there ever be spaces in defined "words"?

@Dlosc, 1st: I simplified what constitutes a circular definition for the purposes of this challenge; that would have been a lot of suffixes and grammar rules to account for! I didn't even touch on prefixes. 2nd: 1) Words are case-insensitive; Hello is the same as hello. 2) No.

Can I take the input as a list of lists?

Pyth, 28 bytes
Really want to condense the logic.
sm}hKm:k"(ing|ed|ly)$";cd;tK

Try it online here.

Congrats! Good answer!

["test - testing"] returns True

@OldBunny2800 oh, that's cuz True is 1 in python

OK then. I can't break it, and that's a good thing!

Python, 187 185, self-disqualified!
EDIT: I've decided to disqualify this due to its bugginess, but its good for the pun.

Takes a Pythonic dictionary (hehe) and outputs the number to the console. This is quite buggy, though, should've done more tests...
def c(i):
 for k, v in i.items():
  l,c,t,y="",0,k[-2:],k[:-2]
  if t=="ed":l=y
  if t=="ly":l=y
  if k[-3:]=="ing":l=k[:-3]
  if" "+k+" "in v:c+=1
  if" "+l in v:c+=1
 print(c)

Nice! Quick answer.

c({"a":"aed","bed":"b"}) returns 0, it should return 2.

Golfed code, Python 2 only. Still as buggy as your current code, though :)

I believe it's buggy because it treats each entry as a single word, so "c: ced." would break. It also doesn't check entries.

Python, 129 bytes
Takes a list of two item lists where the first item is the word and the second is the definition. It returns the amount circular definitions it found.
def f(d,n=0):
 for k,v in d:k,v=k.lower(),v.lower();n+=any(k+_ in v or k.rstrip(_)in v for _ in("","ing","ed","ly"))
 return n

What is the def f(d,n=0): part for? What is the input in n used for?

It creates the variable n and sets it to 0 in 1 less character than setting it on its own line. You don't pass a value for it.

Errors: f({"test":"testing","wondered":"wonder"}) -- ValueError: too many values to unpack, f({"a":"b","c":"d","e":"f"}) -- ValueError: need more than one value to unpack

It doesn't take a dictionary, it takes a list of two item lists like so: f([ ["test", "testing"], ["wondered", "wonder"] ])

Would it be easier to use repeatable args? eg: def f(*d,n=0) Then you won't have to worry about the lists of a list thing.

But that would add a byte.


text:
Check if rectangles fill a rectangular space without gaps or overlaps
This challenge is based on another similar challenge. Because finding the most efficient packing of rectangles is NP-hard (that is, its solution is easy to check but hard to find), this challenge is a lot easier than this one here
This Challenge
Given a bunch of rectangles, figure out whether or not they fill a rectangular space with no gaps or overlaps.
Input
Input can be in two forms, one of which carries a scoring penalty.
The first: it contains a list of sublists, each with length 4. This list contains 4 integers which are the coordinates of opposite vertexes. Since all rectangles will be horizontal/vertical, there is no ambiguity as to where the rectangle is. Each sublist will contain four integers, which, in order, are the x-coordinate of the first vertex, the y-coordinate of the first vertex, the x-coordinate of the second vertex, and the y-coordinate of the second vertex.
The second: it contains four lists of integers with the same length. The four lists represent the different coordinates. If you imagine input option 1 as a matrix, the input here is just the transpose of the matrix. This input carries a +20% byte penalty.
Output
Simple truthy/falsy output.
Specifications
If there is a rectangle with area 0 (that is, x1 == x2 || y1 == y2), disregard this rectangle (so [0 0 1 1], [2 2 3 2] is valid). This specification is in place to make it harder for people to simply get the min/max x/y values.
x1 <= x2 and y1 <= y2 are not always true. If x1 > x2 || y1 > y2, the rectangle is not a zero-area rectangle; rather, it occupies the rectangular space between (x1, y1) and (x2, y2).
Coordinates can be negative, in which case they still occupy the space between the coordinates.
The top-left-most rectangle is not always at (0, 0); thus, the rectangular space that is filled doesn't necessarily have its top-left corner at (0, 0).
(Thanks to @xnor for pointing out these ambiguities)
Please specify how you want your input and how your output will be represented.
Scoring
Score is the size of the code in bytes, plus a byte penalty if applicable. Lowest score as of December 15th wins.
Test Cases
0 0 1 2
1 0 3 1 ==> true
1 1 3 2

0 0 2 2
0 0 1 1 ==> false
0 0 0 0

0 0 1 1
2 2 2 2 ==> true
0 1 2 1

Good luck, happy golfing!

Must the rectangle have a corner at (0,0)? Can the coordinates be negative?

Are we guaranteed that each rectangle has x1 <= x2 and y1 <= y2? Is an area 0 rectangle with x1 == x2 and y1 <= y2 possible?

@xnor These are all little things I failed to consider. Thanks for pointing them out, I will clarify in an edit. My answers to those questions are no, yes, no, yes.

I'd recommend the Sandbox for hammering out details like this is advance. Your test cases should cover as many of these corner cases as possible. I'm still unclear though on "Thus, the list will look like [x1, y1, x2, y2], where (x1, y1) and (x2, y2) represent the top-left and bottom-right vertexes". If x1 > x2 and y1 > y2, is this an area-zero rectangle because the coordinates are switched?

Someone watched numberphile?

Just one comment about NP-hard: When the edge positions are integers in a given range (e.g. 0 to 2^16-1) this problem can be solved in linear time using a monochrome bitmap. However using less than ~100.000 rectangles the exponential-time algorithm will be way faster than the linear time algorithm.

I fail to see how the first "true" test case is so.
the bounding rectangle has to be (0,0)-(3,2); but it will have a gap (0,1)-(3,1)

@EyalLev My bad, I edited the test case.

JavaScript (ES6), 249 bytes
with(Math)a=>!(a=a.map(([l,t,r,b])=>[l<r?l:r,t<b?t:b,l>r?l:r,t>b?t:b]).filter(g=([l,t,r,b])=>(r-l)*(b-t))).reduce((s,b)=>s-g(b),g([min,min,max,max].map((f,i)=>f(...a.map(a=>a[i])))))>a.some(([l,t,r,b],i)=>a.some(([m,u,s,c],j)=>i!=j&l<s&m<r&t<c&u<b))

Note: To use this, either evaluate it as a string and assign the result to a variable, or insert the assignment after the with(Math). Explanation:
with(Math)a=>!( Bring min and max into scope.
a=a.map(([l,t,r,b])=>[l<r?l:r,t<b?t:b,l>r?l:r,t>b?t:b]) Normalise the coordinates
.filter(g=([l,t,r,b])=>(r-l)*(b-t))) Remove empty rectangles, also defining a function to calculate area
.reduce((s,b)=>s-g(b), Subtract the areas of all the rectangles
g([min,min,max,max].map((f,i)=>f(...a.map(a=>a[i]))))) from the area of the bounding box
>a.some(([l,t,r,b],i)=>a.some(([m,u,s,c],j)=>i!=j&l<s&m<r&t<c&u<b)) and check that no rectangles overlap.

I'm having trouble testing this. Could you clarify what you mean by "insert the assignment"? (I have no ES6 experience whatsoever). Or if possible, could you provide a link to some test cases? Thanks.

@AlexL. I mean you need to write e.g. with(Math)f=a=> etc. - putting the f= at the beginning won't work.

Okay. I see what you mean, but the online compilers I tried all gave me various errors. Could you provide a compiler that actually works (the other compilers are being weird)?

@AlexL. Ah, I think I typoed one of my edits; I've double-checked and you should be OK now.

I'm marking this as accepted now. I'll trust you with the test results, and I'll keep trying to verify it.

Mathematica, 194 bytes
(r=Select[#,(#-#3)(#2-#4)&@@#>0&];m={#~Min~#3,#2~Min~#4,#~Max~#3,#2~Max~#4}&@@Transpose@r;b=Boole[(x-#)(x-#3)<0&&(y-#2)(y-#4)<0]&;Integrate[(Plus@@(b@@@r)-b@@m)^2,{x,#,#3}&@@m,{y,#2,#4}&@@m]<1)&

An ungolfed version:
1  (r = Select[#1, (#1 - #3) (#2 - #4) & @@ #1 > 0 &];
2   m = {Min[#1, #3], Min[#2, #4], Max[#1, #3], Max[#2, #4]} & @@ Transpose[r];
3   b = Boole[(x - #1) (x - #3) < 0 && (y - #2) (y - #4) < 0] &;
4   Integrate[
5     (Plus @@ (b @@@ r) - b @@ m)^2 ,
6     {x, #1, #3} & @@ m ,
7     {y, #2, #4} & @@ m
8   ] < 1
9  ) &

Line 1 defines r to be the set of nontrivial rectangles from the given input. (There's a lot of & @@ going on in this code; that's just so we can use #1,#2,#3,#4 for the four elements of a list instead of #[[1]],#[[2]],#[[3]],#[[4]].) Then line 2 defines m to be the coordinates of the smallest rectangle bounding all of the ones listed in r; so if the input rectangles tile a large rectangle, that large rectangle must be m.
Line 3 defines function b which, when applied to a quadruple representing a rectangle, produces a function of two variables x and y that equals 1 if the point (x,y) is inside the rectangle and 0 if it's not. Line 5 produces many of these functions, one for each rectangle in r (all added together) and one last one for the large rectangle m (subtracted); that complicated two-variable function is then squared.
The key, at this point, is that that two-variable function is identically 0 if the small rectangles tile the large rectangle, but it will have some positive values if two small rectangles overlap, or some negative values (before squaring) if some part of the large rectangle isn't covered. We detect this by literally integrating(!) the two-variable function over the large rectangle (the limits of integration are given in lines 6-7): if we obtain 0, then the tiling was perfect, and if we obtain a positive value, then there was a problem somewhere. Since everything in sight is an integer, we save one final byte by using < 1 instead of == 0 in line 8.
(I think it's pretty fun that we can exploit Mathematica's ability to do calculus to solve this combinatorial problem.)

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
Magic mirror madness
Introduction
I have a room full of magic mirrors.
They are mysterious artifacts that can duplicate any item, except another magic mirror.
More explicitly, a duplicate version of the item will appear on the other side of the mirror, at the same distance.
However, if there is another magic mirror in the way on either side, between the duplicating mirror and either item (original or duplicate), the duplicate is not formed.
The original item can be either left or right of the mirror, and the duplicate will appear on the other side.
Also, the duplicate item can itself be duplicated by another mirror.
Items never block the duplication of other items (except by being directly on the position of the would-be duplicate).
Input
Your input is a string consisting of the characters .#|, which represent empty space, items, and magic mirrors.
There will always be at least one magic mirror in the input.
Output
Your output shall be another string where each magic mirror has duplicated every item it can, according to the rules above.
You can assume that there will always be an empty space on the spot where a duplicate item appears (so they will no go out of bounds).
Examples
Consider the input string
.#.|.....|......#
 A B     C      D

where we have marked some positions for clarity.
The mirror B duplicates item A, which ends up to its right:
.#.|.#...|......#
 A B     C      D

Mirror C then duplicates the new item:
.#.|.#...|...#..#
 A B     C      D

Mirror C cannot duplicate item A, since mirror B is in the way.
It also cannot duplicate item D, since mirror B is in the way on the other side.
Likewise, mirror B cannot duplicate item D or the duplicate next to it, since mirror C is in the way, so this is the correct output.
For another example, consider the input
.##..#...|#..##...|..##....#.
 AB  C   DE  FG   H  IJ    K

Mirror D can duplicate A and B to the right, and E and G to the left.
C and F are already duplicates of each other.
The string becomes
.##.##..#|#..##.##|..##....#.
 AB  C   DE  FG   H  IJ    K

Mirror H can duplicate E, F, and the duplicates of A and B to the right, and I to the left.
G and J are already duplicates of each other, and mirror D is in the way of K.
Now we have
.##.##..#|#..#####|#####..##.
 AB  C   DE  FG   H  IJ    K

Finally, mirror D can duplicate the duplicate of I to the left.
We end up with
.#####..#|#..#####|#####..##.
 AB  C   DE  FG   H  IJ    K

Rules and scoring
You can write either a full program or a function.
The lowest byte count wins.
Submissions that don't use regex engines compete separately from those that do, and may be marked with (no regex).
Test cases
"|" -> "|"
"..|.." -> "..|.."
".#.|..." -> ".#.|.#."
"..#|.#." -> ".##|##."
".#..|....|.." -> ".#..|..#.|.#"
".|..|.#....." -> "#|#.|.#....."
"...|.#...|....#" -> ".##|##...|...##"
"......#|......." -> "......#|#......"
".#.|.....|......#" -> ".#.|.#...|...#..#"
".......|...#.##|...." -> "##.#...|...#.##|##.#"
"...#..||.......#..#...#" -> "...#..||.......#..#...#"
".##|.#....||#||......#|.#" -> ".##|##....||#||.....##|##"
".##..#...|#..##...|..##....#." -> ".#####..#|#..#####|#####..##."
".#|...||...|#...|..##...|#...." -> ".#|#..||.##|##..|..##..#|#..##"
"....#.|...#.|..|.|.....|..#......" -> "..#.#.|.#.#.|.#|#|#.#..|..#.#...."
"..|....|.....#.|.....|...|.#.|..|.|...#......" -> ".#|#...|...#.#.|.#.#.|.#.|.#.|.#|#|#..#......"

Can we take an array of characters as input and/or output?

@ConorO'Brien No, unless that's the natural representation of a string in your language.

Retina, 50 bytes
+`([#.])(([#.])*\|(?>(?<-3>[#.])*))(?!\1)[#.]
#$2#

Try it online! (The first line enables a linefeed-separated test suite.)
I guess this is the opposite of a (no regex) submission.
Explanation
This is simply a regex substitution, which is applied repeatedly (+) until the string stops changing. I'm using balancing groups to make sure that the two mirrored positions are the same distance from the given mirror (backreferences won't do, since the exact string on both sides of the | may be different).
([#.])            # Match and capture a non-mirror cell.
(                 # This will match and capture everything up to its corresponding
                  # cell so that we can write it back in the substitution.
  ([#.])*         #   Match zero or more non-mirror cells and push each one onto
                  #   group 3. This counts the distance from our first match to
                  #   the mirror.
  \|              #   Match the mirror.
  (?>             #   Atomic group to prevent backtracking.
    (?<-3>[#.])*  #     Match non-mirror while popping from group 3.
  )               #   There are three reasons why the previous repetition
                  #   might stop:
                  #   - Group 3 was exhausted. That's good, the next position
                  #     corresponds to the first character we matched.
                  #   - We've reached the end of the string. That's fine,
                  #     the last part of the regex will cause the match to fail.
                  #   - We've hit another mirror. That's also fine, because
                  #     the last part of the regex will still fail.
)
(?!\1)            # Make sure that the next character isn't the same as the first
                  # one. We're looking for .|# or #|., not for #|# or .|.
[#.]              # Match the last non-mirror character.

This is replaced with #$2# which simply replaces both the first and last character of the match with a #.

Perl, 49 bytes
Full credit to @Martin Ender for this one who suggested this regex 15 bytes shorter than mine.
47 bytes of code + -pl flags
s/([.#])(\||[^|](?2)[^|])(?!\1)[^|]/#$2#/&&redo

To run it :
perl -plE 's/([.#])(\||[^|](?2)[^|])(?!\1)[^|]/#$2#/&&redo' <<< ".##..#...|#..##...|..##....#."

The first (([.#])) and last ((?!\1)[^|]) parts are the same as in Retina answer (see the explanation over there).
The middle part ((\||[^|](?2)[^|])) uses perl recursion ((?2)) to match either a mirror (\|) or (|) two not-mirrors-characters ([^|]) separated by the very same pattern ((?2)).

My older (and uglier) version: s/([.#])(([^|]*)\|(??{$3=~s%.%[^|]%gr}))(?!\1)[^|]/#$2#/&&redo

Haskell (no regex), 117 bytes
r=reverse
s=span(<'|')
m=zipWith min
g a|(b,l:c)<-s a,(d,e)<-s c=b++l:g(m(r b++[l,l..])d++e)|0<1=a
f x=m(g x)$r.g.r$x

C, 176 bytes
void t(char*a){int x=0;for(int i=0;a[i];i++)if(a[i]=='|'){for(int j=x;a[j]&&j<=i*2-x;j++){if((a[j]==35)&&(a[2*i-j]==46)){a[2*i-j]=35;i=-1;}if((i-j)&&(a[j]=='|'))break;}x=i+1;}}

Ungolfed
void t(char*a)
{
    int x=0;
    for(int i=0;a[i];i++)
        if(a[i]=='|')
        {
            for(int j=x;a[j]&&j<=i*2-x;j++)
            {
                if((a[j]=='#')&&(a[2*i-j]=='.'))
                {
                    a[2*i-j]='#';
                    i=-1;
                    break;
                }
                if((i!=j)&&(a[j]=='|'))
                    break;
            }
            x=i+1;
        }
}

I think you can save a couple bytes by replacing '#' and '.' with 35 and 46 respectively.

This code can be golfed..a lot.

thanks artificialNull, that saved 3 byes.  '|' is 124, so that doesn't save anything (but maybe I should change that, so it will be consistent; not sure yet).
and @Mukul, I don't really see how, without greatly changing the logic flow of it.

check if this code runs fine x,i,j;void t(char*a){while(a[i]++)if(a[i]=='|'){for(j=x;a[j++]&&j<=i*2-x;j++){if((a[j]==35)&&(a[2*i-j]==46)){a[2*i-j]=35;i=-1;break;}if((i-j)&&(a[j]=='|'))break;}x=i+1;}} - 170 bytes

and one more thing, the break; in first if seems unnecessary...

in my comment while(a[i]++)  is while(a[i++]) and remove j++ from second loop ...bad type..

@Mukul
"C++ does not support default-int", so while the x,i,j deceleration is nice, it doesn't compile on my pc.  The break can be removed, as the negative value for i will cause the loop to exit; thanks.
in your code, you have a[i]++; guessing you meant it to be a[i++] (ok, seeing your second comment, so I was right), but that too may cause problems.

c++ does not but c does..so i ask you to either change the language you mention in your answer or run my code in a c compiler...

1more byte replace (i!=j) with (i-j) and if you are going to stick with c++then atleast define all int at one place...

PHP, 123 117 100 bytes
for($t=$argv[1];$t!=$s;)$t=preg_replace("%([.#])(\||[.#](?2)[.#])(?!\g1)[.#]%","#$2#",$s=$t);echo$t;

program takes command line argument, regex taken from @Martin Ender/Dada. Run with -r.

JavaScript (ES6), 170 bytes
s=>s.replace(/#/g,(c,i)=>(g(i,-1),g(i,1)),g=(i,d,j=h(i,d))=>j-h(j=j+j-i,-d)|s[j]!='.'||(s=s.slice(0,j)+'#'+s.slice(j+1),g(j,d)),h=(i,d)=>s[i+=d]=='|'?i:s[i]?h(i,d):-1)&&s

Ungolfed:
function mirror(s) {
    for (var i = 0; i < s.length; i++) {
        // Reflect each # in both directions
        if (s[i] == '#') s = reflect(reflect(s, i, true), i, false);
    }
    return s;
}
function reflect(s, i, d) {
    // Find a mirror
    var j = d ? s.indexOf('|', i) : s.lastIndexOf('|', i);
    if (j < 0) return s;
    // Check that the destination is empty
    var k = j + (j - i);
    if (s[k] != '.') return s;
    // Check for an intervening mirror
    var l = d ? s.lastIndexOf('|', k) : s.indexOf('|', k);
    if (l != j) return s;
    // Magically duplicate the #
    s = s.slice(0, k) + '#' + s.slice(k + 1);
    // Recursively apply to the new #
    return reflect(s, k, d);
}

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
Head, Shoulders, Knees and Toes, Knees and Toes
Introduction:
I think we all know it, and it has probably been translated in loads of different languages: the "Head, Shoulders, Knees and Toes" children song:

Head, shoulders, knees and toes, knees and toes
  Head, shoulders, knees and toes, knees and toes
  And eyes and ears and mouth and nose
  Head, shoulders, knees and toes, knees and toes
wikipedia

Challenge:
Input: A positive integer.
Output: Output one of the following words based on the input as n-th index:
head
shoulders
knees
toes
eyes
ears
mouth
nose

Here the body parts are appended with the indexes:
Head (0), shoulders (1), knees (2) and toes (3), knees (4) and toes  (5)
Head (6), shoulders (7), knees (8) and toes (9), knees (10) and toes (11)
And eyes (12) and ears (13) and mouth (14) and nose (15)
Head (16), shoulders (17), knees (18) and toes (19), knees (20) and toes (21)

Head (22), shoulders (23), knees (24) and toes (25), knees (26) and toes  (27)
Head (28), shoulders (29), knees (30) and toes (31), knees (32) and toes (33)
And eyes (34) and ears (35) and mouth (36) and nose (37)
Head (38), shoulders (39), knees (40) and toes (41), knees (42) and toes (43)

etc.

Challenge rules:

You are of course allowed to use 1-indexed input instead of 0-indexed. But please specify which one you've used in your answer.
The output is case insensitive, so if you want to output it in caps that's fine.
You should support input up to at least 1,000.

General rules:

This is code-golf, so shortest answer in bytes wins.
Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.
Standard rules apply for your answer, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters, full programs. Your call.
Default Loopholes are forbidden.
If possible, please add a link with a test for your code.
Also, please add an explanation if necessary.

Test cases (0-indexed):
Input:  Output:
0       head
1       shoulders
7       shoulders
13      ears
20      knees
35      ears
37      nose
98      knees
543     nose
1000    knees

Added the kolmogorov complexity tag since most answers will probably use the input as a cyclic index into a constant array, whose generation will dominate the byte count.

@MartinEnder Thanks. I, incorrectly, only used kolmogorov-complexity for answers that always have the same fixed output, but now I see that's it about fixed output-strings in the code, and finding patterns to golf it (or encode it like with @Enigma's 05AB1E answer). Thanks for adding it; I wasn't too sure what tags were relevant for this challenge, which was one of my (unfortunately unanswered) questions in the Sandbox.

Relevant meta post about usage of the tag.

I think I found where this one drew inspiration from...

@EriktheGolfer I had no idea someone else posted a similar question in the sandbox. I had searched for it on the non-meta site and couldn't find anything. I was actually inspired by it because a colleague of mine was in a very childish mood and was singing it (including actually touching the body parts.. >.>) Sorry @Neil, I really should learn to check the sandbox as well when I post a question.. (although yours is a bit different than the one I posted).

@KevinCruijssen At least your question caught some +1's :) (optimistic remark) You can search in the sandbox using inquestion:2140 shoulders.

Did anyone else got this song stuck in their head all day?...

The usual practise for singing this song when I was younger was to sing it repeatedly and remove additional words each time. So second time would be "heads, shoulders, knees and _, knees and _" and so on. Would be interesting to add that in also :-D

05AB1E, 36 35 34 bytes
“‡ä¾ØsÏ©s¸±s“#2ä¤«Ð“—íÖÇ©¢ÄÃ“#s)˜è

Try it online! or as a Test suite
Explanation
“‡ä¾ØsÏ©s¸±s“                        # dictionary string 'head shoulders knees toes'
             #                       # split on spaces
              2ä                     # split in 2 parts
                ¤                    # get the last part ['knees', 'toes']
                 «                   # concatenate and flatten
                                     # STACK: [['head', 'shoulders'], ['knees', 'toes'], 'knees', 'toes']
                  Ð                  # triplicate
                   “—íÖÇ©¢ÄÃ“        # dictionary string 'eyes ears mouth nose'
                             #s      # split on spaces and swap top 2 elements of stack
                               )˜    # wrap stack in a list and flatten
                                 è   # index into list with input

In short, we build the list
['head', 'shoulders', 'knees', 'toes', 'knees', 'toes', 'head', 'shoulders', 'knees', 'toes', 'knees', 'toes', 'eyes', 'ears', 'mouth', 'nose', 'head', 'shoulders', 'knees', 'toes', 'knees', 'toes'] and index into it with input (0-indexed).

@KevinCruijssen: An explanation is ofc coming :) It's pretty mandatory for golfing languages imo.

‡ä¾ØsÏ©s¸±s seems weird, considering that each word is 2 characters. Is it something else?

@EriktheGolfer: Yes, the 3 s's are there to pluralize shoulder, knee, toe which are singular in the dictionary. We don't need that with eyes, ears as they're already pluralized in the dictionary so that string has the expected even length.

Oh, they confused me. Thanks.

JavaScript (ES6), 91 88 87 bytes
n=>'knees,toes,head,shoulders,eyes,ears,mouth,nose'.split`,`[(245890>>(n%22&~1))&6|n%2]

How it works
We have 4 distinct pairs of words that always appear together: 'head' is always followed by 'shoulders', 'knees' is always followed by 'toes', etc.
Therefore, we can use the following index:
00: [ 'knees', 'toes' ]
01: [ 'head', 'shoulders' ]
10: [ 'eyes', 'ears' ]
11: [ 'mouth', 'nose' ]

And compress the whole sequence (in reverse order) into the following binary mask:
00 00 01 11 10 00 00 01 00 00 01

We use [ 'knees', 'toes' ] as the first pair to get as many leading zeros as possible.
We pad this sequence with an extra 0 so that the extracted value is premultiplied by 2, which leads to:
0b00000111100000010000010 = 245890

Hence the final formula for the correct word:
(245890 >> (n % 22 & ~1)) & 6 | n % 2

Test cases

let f =

n=>'knees,toes,head,shoulders,eyes,ears,mouth,nose'.split`,`[(245890>>(n%22&~1))&6|n%2]

console.log(f(0));    // head
console.log(f(1));    // shoulders
console.log(f(7));    // shoulders
console.log(f(13));   // ears
console.log(f(20));   // knees
console.log(f(35));   // ears
console.log(f(37));   // nose
console.log(f(98));   // knees
console.log(f(543));  // nose
console.log(f(1000)); // knees

Python 2, 158 148 137 128 114 109 104 bytes
Lookup table seems better. Also shortened the big string and reordered the items. -5 bytes thanks to Rod for using string as a list.
c=int('602323'*2+'4517602323'[input()%22])
print"smkteehnhonoyaeooueeerasutesssdelhs"[c::8]+"ders"*(c<1)

initial solution:
n=input()%22
n-=10*(n>15)
if n>=12:n-=8
else:n%=6;n-=2*(n>3)
print"hskteemnehnoyaooaoeeerusduessste ls   h  d       e       r       s"[n::8].strip()

Very original answer! +1. But, umm..., most answers that use the complete strings are shorter than this. Still, I like the afford you took to see some kind of pattern in the strings! Chapeau for that.

I think you can make this shoulder by making the string this: hskteemnehnoyaooaoeeerusduessste ls   h  d and then appending 'ers' if you know the word is supposed to be 'shoulders' :)

@Shebang Yeah, just had the same idea.

@KevinCruijssen Thanks. I'm working on reducing the size.

you can just use c=int('602323'*2+'4517602323'[input()%22]) and drop the h c:

@Rod Thanks, but in total it is 1 byte longer :<

@KarlNapf ??, I meant to replace the first 2 lines by that command, it's 5 bytes shorter.

@Rod h=[6,0]+[2,3]*2;c=(h*2+[4,5,1,7]+h)[i%22] = 41 bytes, c=int('602323'*2+'4517602323'[input()%22]) = 42 bytes.

[i%22] on the first, [input()%22] on the second

@Rod Ah sorry, if you look at your code long enough you get blind.

Perl, 74 bytes
73 bytes code + 1 for -p.
$_=(@a=(head,shoulders,(knees,toes)x2),@a,eyes,ears,mouth,nose,@a)[$_%22]

Uses 0-based indexing. Doesn't output a separator, but that could be amended with -l in the flags.
Try it online.

you can save 1 byte with x2)x2 instead of x2),@a

Java 7, 155 137 131 123 111 110 bytes
String c(int i){return"knees,toes,head,shoulders,eyes,ears,mouth,nose".split(",")[(245890>>(i%22&~1))&6|i%2];}

-12 bytes thanks to @Neil.
-1 byte by shamelessly creating a port of @Arnauld's amazing answer.
Java is 0-indexed, so that's what I've used.
Ungolfed & test code:
Try it here.
class M{
  static String c(int i){
    return "knees,toes,head,shoulders,eyes,ears,mouth,nose".split(",")
      [(245890>>(i%22&~1))&6|i%2];
  }

  public static void main(String[] a){
    System.out.println(c(0));
    System.out.println(c(1));
    System.out.println(c(7));
    System.out.println(c(13));
    System.out.println(c(20));
    System.out.println(c(35));
    System.out.println(c(37));
    System.out.println(c(98));
    System.out.println(c(543));
    System.out.println(c(1000));
  }
}

Output:
head
shoulders
shoulders
ears
knees
nose
ears
knees
nose
knees

String c(int i){return "head,shoulders,knees,toes,knees,toes,eyes,ears,mouth,nose".split(",")[(i+16)%22%16%10];} is only 112 bytes.

If you try to copy from the comment you get some extra invisible bytes courtesy of Stack Exchange.

@Neil Ok, I'm an idiot.. No idea how I've counted rougly 120 yesterday evening late.. It was probably too late.. >.> Anyway, I've edited it (plus 1 additional byte by removing the space), so thanks!

Python 2, 97 90 Bytes
There may be some math that makes it so I don't have to make the word list, but this works for now!
lambda n,k='head shoulders '+'knees toes '*2:(k*2+'eyes ears mouth nose '+k).split()[n%22]

Thanks to Flp.Tkc for saving 7 bytes :)

I got a similar solution, but used split() to make it shorter: k='head shoulders '+'knees toes '*2 print(k*2+'eyes ears mouth nose'+k).split()[input()%22]

sorry, there should be a space after the 'nose' there :)

@Flp.Tkc Yeah I had just realized that :) Updating in a second!

C, 153 bytes 141 bytes
*b[]={"head","shoulders","knees","toes","eyes","ears","mouth","nose"};i;char*g(a){a%=22;i=(a+4)%10;return b[a<4?a:(a&12)>8?a-8:i<2?i:a%2+2];}

Thanks to @cleblanc for 4 bytes.  Declaring b globally throws a ton of warnings about casting to int, but didn't break for me.
Ungolfed:
*b[]={"head","shoulders","knees","toes","eyes","ears","mouth","nose"};
i;
char* g(a) {
    a%=22;
    i=(a+4)%10;
    return b[a < 4        ? a
            :(a & 12) > 8 ? a-8
            :i < 2        ? i
            :               a % 2 + 2];
}

It's not the smallest answer, but I liked the technique, and had fun finding a few patterns.
Changelog:

Moved b to global to avoid char (4 bytes)
a > 11 && a < 16 => (a & 12) > 8 (2 bytes)
i=(a-6)%10 => i=(a+4)%10 so that i < 2 && i >= 0 => i < 2 (6 bytes)

You can golf this down a bit further.  By moving b[] to a global scope it can be declared without using char* like this *b[]={"head","shoulders","knees","toes","eyes","ears","mouth","nose"},i' and then replace the return b[...] with a puts(b[...]) you can get it down to 143 bytes

+1 And in addition to @cleblanc's suggestion, you can also change both && to &.

I'm curious how @cleblanc suggestion about declaring b globally works.  The compiler told me it would be an *int[], and I thought that the size difference would break the code.  It didn't though, so thanks!

JavaScript (ES6) 91 89 Bytes

f=
n=>((d='head:shoulders:'+(b='knees:toes:')+b)+d+'eyes:ears:mouth:nose:'+d).split`:`[n%22]

console.log(f.toString().length)
console.log(f(0) === 'head')
console.log(f(1) === 'shoulders')
console.log(f(7) === 'shoulders')
console.log(f(13) === 'ears')
console.log(f(20) === 'knees')
console.log(f(35) === 'ears')
console.log(f(37) === 'nose')
console.log(f(98) === 'knees')
console.log(f(543) === 'nose')
console.log(f(1000) === 'knees')

Nice! +1. When I port your answer to Java 7 it's a solid -7 bytes compared to @Arnauld's already-shorter-than-mine answer. ;) Thanks!

I saved a byte by being creative with my use of %: n=>\head:shoulders:knees:toes:knees:toes:eyes:ears:mouth:nose`.split`:`[(n+16)%22%16%10]`.

PHP, 91 102 118 128 129 Bytes
<?=[head,shoulders,knees,toes,eyes,ears,mouth,nose]['0123230123234567012323'[$argv[1]%22]];

0-Indexed
Down to 91 following removal of str_split, didn't realise PHP string were accessible as a char array (a PHP 5+ thing?)
Down to 102 thanks to insertusername suggestion for removing string quotes and allowing the notices

-16 bytes: remove all ' around words, like 'head' becomes head etc.

Not sure what the rules are with this, but with a default PHP install, I get the expected undefined constant warnings when doing that

Yes, but this is absolutely fine with the site's rules. Notices and warnings can be ignored.

@CT14.IT, that is not a warning, is a notice. “PHP 5.3 or later, the default value is E_ALL & ~E_NOTICE & ~E_STRICT & ~E_DEPRECATED. This setting does not show E_NOTICE, E_STRICT and E_DEPRECATED level errors.” – PHP documentation about error_reporting.

It seems that str_split() is useless

yes @Crypto <?=[head,shoulders,knees,toes,eyes,ears,mouth,nose]['0123230123234567012323'[$argv[1]%22]]; seems to work

R, 95 bytes
c(o<-c("head","shoulders",y<-c("knees","toes"),y),o,"eyes","ears","mouth","nose",o)[scan()%%22]

Creates a character vector to function as a lookup table. Takes input from stdin (1-indexed) and %%22 to find the corresponding body part.
Bonus: %% is vectorized which means that this will work with a vector inputs as well.
Test cases on R-fiddle (Note that this is a named function because scan doesn't work on R-fiddle)

jq, 80 characters
(77 characters code + 3 characters command line option)
((("head shoulders "+"knees toes "*2)*2+"eyes ears mouth nose ")*2/" ")[.%22]

Sample run:
bash-4.3$ jq -r '((("head shoulders "+"knees toes "*2)*2+"eyes ears mouth nose ")*2/" ")[.%22]' <<< 1000
knees

On-line test (Passing -r through URL is not supported – check Raw Output yourself.)

WinDbg, 207 157 151 bytes
ea2000000"headshoulderskneestoeseyesearsmouthnoseAEEJNFSENFSEAEEJNFSENFSEWE[E_FdEAEEJNFSENF";r$t4=(@$t0%16)*2+2000027;da1FFFFBF+by(@$t4) Lby(@$t4+1)-41

-50 bytes by encoding the offset/length of the body parts as ascii chars.
-6 bytes by using a local var when looking up the offset/length.
Input is done with a value set in the pseudo-register $t0.
How it works:
* Initialization, writes this string at address 0x2000000. The nonsense after the body parts
* are the offsets and lengths of the body parts in the first part of the string, each of
* which is incremented by 0x41 to make it a printable ascii character.
ea 2000000
        "headshoulderskneestoeseyesearsmouthnoseAEEJNFSENFSEAEEJNFSENFSEWE[E_FdEAEEJNFSENF";

* Display the output:
r$t4=(@$t0%16)*2+2000027
da1FFFFBF+by(@$t4) Lby(@$t4+1)-41

* Display output explanation:
r $t4 = (@$t0%16)*2+2000027   * Set $t4 = input, @$t0, mod 22, doubled +0x2000027
by(@$t4)                      * byte_at(@$t4)-0x41 is the {Offset} into the string
                              * for the start of output. The -0x41 is already subtracted
                              * from 0x2000000 to make 0x1FFFFBF.
Lby(@$t4+1)-41                * byte_at(@$t4+1)-0x41 is the {Length} of the output.
da 1FFFFBF+{Offset} L{Length} * Display {Length} chars from {Offset} of the above string.

Sample output:
0:000> r$t0=0
0:000> ea2000000"headshoulderskneestoeseyesearsmouthnoseAEEJNFSENFSEAEEJNFSENFSEWE[E_FdEAEEJNFSENF";r$t4=(@$t0%16)*2+2000027;da1FFFFBF+by(@$t4) Lby(@$t4+1)-41
02000000  "head"

0:000> r$t0=1
0:000> ea2000000"headshoulderskneestoeseyesearsmouthnoseAEEJNFSENFSEAEEJNFSENFSEWE[E_FdEAEEJNFSENF";r$t4=(@$t0%16)*2+2000027;da1FFFFBF+by(@$t4) Lby(@$t4+1)-41
02000004  "shoulders"

0:000> r$t0=7
0:000> ea2000000"headshoulderskneestoeseyesearsmouthnoseAEEJNFSENFSEAEEJNFSENFSEWE[E_FdEAEEJNFSENF";r$t4=(@$t0%16)*2+2000027;da1FFFFBF+by(@$t4) Lby(@$t4+1)-41
02000004  "shoulders"

0:000> r$t0=0n13
0:000> ea2000000"headshoulderskneestoeseyesearsmouthnoseAEEJNFSENFSEAEEJNFSENFSEWE[E_FdEAEEJNFSENF";r$t4=(@$t0%16)*2+2000027;da1FFFFBF+by(@$t4) Lby(@$t4+1)-41
0200001a  "ears"

0:000> r$t0=0n20
0:000> ea2000000"headshoulderskneestoeseyesearsmouthnoseAEEJNFSENFSEAEEJNFSENFSEWE[E_FdEAEEJNFSENF";r$t4=(@$t0%16)*2+2000027;da1FFFFBF+by(@$t4) Lby(@$t4+1)-41
0200000d  "knees"

0:000> r$t0=0n35
0:000> ea2000000"headshoulderskneestoeseyesearsmouthnoseAEEJNFSENFSEAEEJNFSENFSEWE[E_FdEAEEJNFSENF";r$t4=(@$t0%16)*2+2000027;da1FFFFBF+by(@$t4) Lby(@$t4+1)-41
0200001a  "ears"

0:000> r$t0=0n37
0:000> ea2000000"headshoulderskneestoeseyesearsmouthnoseAEEJNFSENFSEAEEJNFSENFSEWE[E_FdEAEEJNFSENF";r$t4=(@$t0%16)*2+2000027;da1FFFFBF+by(@$t4) Lby(@$t4+1)-41
02000023  "nose"

0:000> r$t0=0n98
0:000> ea2000000"headshoulderskneestoeseyesearsmouthnoseAEEJNFSENFSEAEEJNFSENFSEWE[E_FdEAEEJNFSENF";r$t4=(@$t0%16)*2+2000027;da1FFFFBF+by(@$t4) Lby(@$t4+1)-41
0200000d  "knees"

0:000> r$t0=0n543
0:000> ea2000000"headshoulderskneestoeseyesearsmouthnoseAEEJNFSENFSEAEEJNFSENFSEWE[E_FdEAEEJNFSENF";r$t4=(@$t0%16)*2+2000027;da1FFFFBF+by(@$t4) Lby(@$t4+1)-41
02000023  "nose"

0:000> r$t0=0n1000
0:000> ea2000000"headshoulderskneestoeseyesearsmouthnoseAEEJNFSENFSEAEEJNFSENFSEWE[E_FdEAEEJNFSENF";r$t4=(@$t0%16)*2+2000027;da1FFFFBF+by(@$t4) Lby(@$t4+1)-41
0200000d  "knees"

SQL 2005 747 Bytes
Golfed:
GO
CREATE PROCEDURE H @n INT AS BEGIN IF NOT EXISTS(SELECT*FROM R)BEGIN INSERT INTO R VALUES('head')INSERT INTO R VALUES('shoulders')INSERT INTO R VALUES('knees')INSERT INTO R VALUES('toes')INSERT INTO R VALUES('knees')INSERT INTO R VALUES('toes')INSERT INTO R VALUES('head')INSERT INTO R VALUES('shoulders')INSERT INTO R VALUES('knees')INSERT INTO R VALUES('toes')INSERT INTO R VALUES('knees')INSERT INTO R VALUES('toes')INSERT INTO R VALUES('eyes')INSERT INTO R VALUES('ears')INSERT INTO R VALUES('mouth')INSERT INTO R VALUES('nose')INSERT INTO R VALUES('head')INSERT INTO R VALUES('shoulders')INSERT INTO R VALUES('knees')INSERT INTO R VALUES('toes')INSERT INTO R VALUES('knees')INSERT INTO R VALUES('toes')END SELECT W FROM R WHERE I=@n%22 END

Ungolfed:
GO
CREATE PROCEDURE H
@n INT
AS
BEGIN IF NOT EXISTS(SELECT*FROM R)
BEGIN
INSERT INTO R VALUES('head')INSERT INTO R VALUES('shoulders')INSERT INTO R VALUES('knees')INSERT INTO R VALUES('toes')INSERT INTO R VALUES('knees')INSERT INTO R VALUES('toes')INSERT INTO R VALUES('head')INSERT INTO R VALUES('shoulders')INSERT INTO R VALUES('knees')INSERT INTO R VALUES('toes')INSERT INTO R VALUES('knees')INSERT INTO R VALUES('toes')INSERT INTO R VALUES('eyes')INSERT INTO R VALUES('ears')INSERT INTO R VALUES('mouth')INSERT INTO R VALUES('nose')INSERT INTO R VALUES('head')INSERT INTO R VALUES('shoulders')INSERT INTO R VALUES('knees')INSERT INTO R VALUES('toes')INSERT INTO R VALUES('knees')INSERT INTO R VALUES('toes')
END
SELECT W FROM R WHERE I=@n%22 END

Needs a table like this, where the first column is auto-incremented:

This is a one-indexed answer. The table is populated the first time stored procedure is created - it wouldn't let me do all the INSERT in one statement, disappointingly, this feature is only available in >=SQL 2008. After this, it uses the %22 trick from the other answers. Once the table has been populated, it only uses the last part:
SELECT W FROM R WHERE I=@n%22

Input:  Output:
R 1       head
R 2       shoulders
R 8       shoulders
R 14      ears
R 21      knees
R 36      ears
R 38      nose
R 99      knees
R 54      nose
R 1001    knees

"it wouldn't let me do all the INSERT in one statement" why? Shouldn't something like this be possible in SQL after 2008?

@KevinCruijssen I'm using SQL Server 2008 R2, so it is strange... I've just done some more Googling, apparently it's something to do with the "Compatibility Level" of the database, which I've just tried and failed to change - it's set to 2005 and this is the max value, so it hasn't got this feature. Should I either, specify the SQL version in my answer, or delete the answer if it can't be shortened properly? Gutted as that would save me a lot of text...

Either is fine by me, so it's your call. I personally usually golf in Java 7 which I specify, because in most cases shorter answers are available in Java 8. You could specify it's 2005 in the same way.

@KevinCruijssen Yeah, I've seen people doing that for Java and Python. Wouldn't really like to make the change without being able to test the code either, so I'll specify 2005, cheers :)

bash (with ed), 83 chars
1-indexed
ed<<<"a
head
shoulders
knees
toes
eyes
ears
mouth
nose
.
3,4t4
1,6y
6x
$(($1%22))"

Sample call:
 $ bash test.sh 1001
 knees

Jelly, 55 bytes
“¥ḷne“¥ṇṭḲ»ẋ2ṭ“¢1$“@⁼5⁼»µẋ2;“¥ḳVo“¥ḳ'k“£Qo“£³ạ»;⁸FḊḲ
ị¢

Try it online! (1-based index)
Come on! Really?
As a bonus, this is the compressed string I was supposed to use instead of the top line:
“¡¦ṡb[wfe=⁺żɦ4Gƈġhḳ"ẇ⁴ż>oH¹8ṡʠʠḟṀUṿḶ>¬Þ:ĖẇrṗṁɼlDṫỤ¬ȷ⁶Dḥci*⁻³GḲOÞạṖṃ\»

Both encode this string:
head shoulders knees toes knees toes head shoulders knees toes knees toes eyes ears mouth nose head shoulders knees toes knees toes

Guess I should go exercise now :P

Powershell, 91 Bytes, Zero-Indexed
$a='head shoulders '+'knees toes '*2;($a*2+'eyes ears mouth nose '+$a).Split()[$args[0]%22]

Very straightforward approach, generate the array of the first 22 items using some string multiplication where possible, by compiling them with spaces and splitting at the end. (splitting is 2 bytes shorter than the equivalent setup as an array) then just find the point in that array using the modulus of the input, not exactly interesting or language-specific.
Test Case:
PS C:\++\golf> 0..1000|%{.\hskt $_}
head
shoulders
knees
toes
knees
toes
head
shoulders
knees
toes
knees
toes
eyes
ears
mouth
nose
head
shoulders
knees
toes
knees
toes
head
shoulders
knees
toes
....

etc.

Befunge, 129 119 bytes
0-indexed
&29+2*%:2/v>00p>%#7_v
+%2\-"/"g2<|<:-1g007<"head*shoulders*knees*toes*eyes*ears*mouth*nose"p00
02202246022>$$:>7#:%#,_@

Try it online!
Explanation
As Arnauld pointed out, the words come in pairs, so we have an index of just 11 values and then add the word number % 2 to get the appropriate word in the pair. The words are pushed onto the stack as a single string separated by asterisks to save space. We test for word breaks by taking the char value modulo 7, since only the asterisk is a multiple of 7.
&29+2*%               n = getint() % 22             // % 22 to ensure it's in range
:2/2g                 i = index_array[n/2]          // we use n/2 because words are paired
-"/"                  i -= '/'                      // convert from ASCII to 1-based value
\2%+                  i += n%2                      // get the correct word in the pair
00p                   index = i                     // save for later

"head*shoulders*knees*toes*eyes*ears*mouth*nose"    // push all the words onto the stack

700g1-:|              while (index-1 != 0) {        // the 7 is used in the drop loop
  00p                   index = index-1
  >%#7_                 do while (pop() % 7)        // drop up to the next '*' (%7==0)
                      }

$$                    pop();pop()                   // get rid of index and extra 7

: 7 % _               while ((c = pop()) % 7)       // output up to the next '*' (%7==0)
 > : ,                  putchar(c)

ruby, 81 bytes
Lambda function using zero indexing.
->n{("head shoulders#{" knees toes "*2}eyes ears mouth nose".split*2)[n%22-6&15]}

explanation
We generate the following array, of which we use the first 16 elements, covering the correct lines 2,3,4 of the song:
%w{head shoulders knees toes knees toes
   eyes ears mouth nose
   head shoulders knees toes knees toes

   eyes ears mouth nose}                  #last 4 elements not used

We take n modulo 22 to reduce it to a single verse, then we subtract 6. Now the index 6 (for example) has been changed to 0 and points to the right word. Indicies 0..5 which point to the first line of the song are now negative. We use &15 (identical to %16 but avoids the need for brackets) to map the 1st line of the song to the 4th line. Thus index 0 -> -6 -> 10
in test program
f=->n{("head shoulders#{" knees toes "*2}eyes ears mouth nose".split*2)[n%22-6&15]}

#call as below to test index 0..43
44.times{|i|p f[i]}

Interesting index formula. But the same length can be achieved without it: ->n{(((%w{head shoulders}+%w{knees toes}*2)*2+%w{eyes ears mouth nose})*2)[n%22]}

dc, 135 bytes
6[head]6[:add6-r;ar:adA+r;ar:a]dshx7[shoulders]7lhx8[knees]8lhxA 2;aAlhx9[toes]9lhxB 3;aBlhx[eyes]C:a[ears]D:a[mouth]E:a[nose]F:a22%;ap

Try it online!
Arrays in dc have to be built an element at a time, which takes up the brunt of this exercise. Since 'eyes', 'ears', 'mouth', and 'nose' only appear once in our array, we just pop them in. But for the others, we save a few bytes by putting them on the stack like x[head]x, where x is the middle of its three values, then we run the macro [:add6-r;ar:adA+r;ar:a]dshx to put it in the array, pull it back, put it in at the same value less six, pull it back, and then put it in one last time at the original value plus ten. We use the middle value because dc allows us to use hex digits even in decimal mode, and subtracting A is one less byte than adding 16 - this also only works because all of the middle values are under fifteen. We have to do knees and toes twice, and making our macro smart enough to sort that out is more expensive than just running the macro twice; but we do save bytes here by loading a previously stored copy of the string instead of writing it out again (B 3;aB vs. B[toes]B - I think this saves 3 bytes total).
Once we have the array built, all we need to do is 22% and then ;ap to pull it from the array and print.

C#6, 138 bytes
string F(int i)=>(i+10)%22<4?"eyes,ears,mouth,nose".Split(',')[(i+10)%22%4]:"head,shoulders,knees,toes,knees,toes".Split(',')[(i+6)%22%6];

repl.it demo
Ungolfed + comments:
string F(int i)=>
    // Is it eyes/ears/mouth/nose?
    (i+10)%22<4
        // If yes, then set index to 4-word line and take modular 4
        // String array constructed by splitting comma-delimited words
        ? "eyes,ears,mouth,nose".Split(',')
            [(i+10)%22%4]
        // Else set index to last 6-word line and take modular 6
        : "head,shoulders,knees,toes,knees,toes".Split(',')
            [(i+6)%22%6];

You could combine the string and use a single Split, and have your same check as ternary (?:) inside the square-brackets (with +4 for the second part), like this: string F(int i)=>"eyes,ears,mouth,nose,head,shoulders,knees,toes,knees,toes".Split(',')[(i+10)%22<4?(i+10)%22%4:(i+6)%22%6+4]; (126 bytes)

Excel, 146 bytes
=MID("Head     ShouldersKnees    Toes     Eyes     Ears     Mouth    Nose",CHOOSE(MOD(MOD(MOD(B1+16,22),16),10)+1,1,10,19,28,19,28,37,46,55,64),9)

Uses @Neil's MOD(MOD(MOD(B1+16,22),16),10) to save 15 bytes.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
On this site we obey the laws of thermodynamics!
And in particular the second law: the entropy of an isolated system undergoing an irreversible process increases with time.
For this challenge,

An "isolated system" will be taken to be a program or function (abbreviated as "program" from now on);
The "irreversible process" will be execution of code;
The passing of "time" will correspond to iterated executions of the program's output, considered as a new program;
"Entropy" will be taken as Shannon's first-order entropy (to be defined below), which is a measure of how diverse the characters of the string are.

The challenge
Your program should produce a non-empty string that when executed as a program in the same language produces a string with more entropy than the previous one. Infinitely iterating this execute-the-output process must produce a strictly increasing sequence of entropy values.
The strings can contain any Unicode 9.0 characters. The sequence of strings must be deterministic (as opposed to random).
The entropy for a given string will be defined as follows. Identify its unique characters and their number of occurrences in the string. The frequency pi of the i-th unique character is the number of occurrences of that character divided by the length of the string. The entropy is then

where the sum is over all unique characters of the string. Technically, this corresponds to the entropy of a discrete random variable with distribution given by the frequencies observed in the string.
Let Hk denote the entropy of the string produced by the k-th program, and let H0 denote the entropy of the initial program's code. Also, let L0 denote the length of the initial program in characters. The sequence {Hk} is monotone as per the challenge requirements, and is bounded (because the number of existing characters is finite). Therefore it has a limit, H∞.
The score of a submission will be (H∞−H0)/L0:

The numerator, H∞−H0, reflects to what extent your code "obeys" the law of increasing entropy over an infinite time span.
The denonimator, L0, is the length of the initial code in characters (not in bytes).

The code with the highest score wins. Ties will be resolved in favour of the earliest submission/edit.
To compute the entropy of a string, you can use the JavaScript snippet (courtesy of @flawr and with corrections by @Dennis and @ETHproductions) at the end of this post.
If obtaining the limit H∞ is difficult in your specific case, you can use any lower bound, say H20, to compute the score (so you would use (H20−H0)/L0). But in any case, the infinite sequence of entropies must be strictly increasing.
Please include an explanation or short proof that the sequence of entropies is increasing, if that's not evident.
Example
In a fictional language, consider the code aabcab, which when run produces the string cdefgh, which when run produces cdefghi, which ...
The unique characters of the original code are a, b and c, with respective frequencies 3/6, 2/6 and 1/6. Its entropy is 1.4591. This is H0.
The string cdefgh has more entropy than aabcab. We can know this without computing it because for a given number of characters the entropy is maximized when all the frequencies are equal. Indeed, the entropy H1 is 2.5850.
The string cdefghi again has more entropy than the previous one. We can know without computing because adding a non-existing character always increases the entropy. Indeed, H2 is 2.8074.
If the next string were 42 the chain would be invalid, because H3 would be 1, smaller than 2.8074.
If, on the other hand, the sequence went on producing strings of increasing entropy with limit H∞ = 3, the score would be (3−1.4597)/6 = 0.2567.
Acknowledgments
Thanks to

@xnor for his help improving the challenge, and in particular for convincing me that infinite chains of increasing entropy obtained from iterated execution are indeed possible;

@flawr for several suggestions, including modifying the score function, and for writing the very useful snippet;

@Angs for pointing out an essential drawback in a previous definition of the score function;

@Dennis for a correction in the JavaScript snippet;

@ETHproductions for another correction in the snippet;

@PeterTaylor for a correction in the definition of entropy.

Snippet for calculating the entropy

function calculateEntropy() {
  var input = document.getElementById("input").value; // fetch input as string
  if (/[\uD800-\uDBFF]([^\uDC00-\uDFFF]|$)|([^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/.test(input)) {
    document.getElementById("output").innerHTML = " invalid (unmatched surrogates)";
    return;
  }
  var charArray = input.match(/[\uD800-\uDBFF][\uDC00-\uDFFF]|[^]/g);
  var frequency = {};
  for (var ind in charArray) {
    frequency[charArray[ind]] = 0;
  }
  var total = 0;
  for (var ind in charArray) {
    frequency[charArray[ind]] ++;
    total++;
  }
  var entropy = 0;
  for (var key in frequency) {
    var p = frequency[key] / total;
    entropy -= p * Math.log2(p);
  }
  document.getElementById("output").innerHTML = " " + entropy;
};
<button type="button" onClick="javascript:calculateEntropy();">calculate</button>Entropy: NaN

<textarea id="input">asdf asdf</textarea>

“On this site we obey the laws of thermodynamics!” [citation-needed]

Here is the source :-)

Is there any constraint on the length of the output? Like having the same amount of characters than the input for instance. I find this unclear.

I was hoping the question would be about "Hot" Network Questions.

@Osable The outputs can have any length you want

I was wondering... is it actually possible to infinitely strictly increase the entropy? If I take the output in its unsigned binary form, it's basically a sequence of integers in range [0,255]. If the entropy is optimal when all the characters are different (just an assumption), wouldn't it imply that the string with largest entropy is 256 bytes long? It's far from being infinite. Or my assumption is wrong.

@Osable Attach a copy of that string to itself and the entropy will be the same. Then remove one char and it will be slightly smaller. Invert the process and you have increased the entropy. If you manage to never reach the maximum entropy, you can keep on increasing forever

Hmm it's that last sentence that I did not figure out first. Now that's clear. I thought we had to produce something with an 'infinite' entropy.

@Osable Yes, quite a few people seem to be confused by that... :( But the challenge says "strictly increasing sequence" (not "strictly increasing sequence that tends to infinity"). And the example has limit entropy of 3

@LuisMendo Yes because we went a little too fast. Anyway can the input value be balanced (I mean, all characters have the same frequency)?

@Osable There On this challenge there is no input really. If you mean the initial string (initial program), it can be whatever you want

@Osable there's a concrete example now, if that helps.

I assume that that "pseudorandom" is not, for the purposes of this challenge, "deterministic"?

@Stephen The sequence of strings has to be the same for every chain of executions. Pseudorandom is acceptable if you can achieve that, for example using always the same seed

I realize the question is about coding rather than thermodynamics, but your statement of the 2nd law should read something like "the entropy of a [macroscopic] isolated system cannot decrease", rather than that it increases with time.  That's b/c the entropy of an isolated system at equilibrium doesn't change. Yes, there's no such thing as a fully isolated system in the real world, but, based on the def. of an isolated system, one can't make the general statement that its entropy will always increase with time.  [And implicit in all of this is that the 2nd law applies to macroscopic systems.]

@theorist Good point. I included "applied to irreversible processes" in the first paragraph (I need increasing entropy because the challenge is about strings with strictly increasing entropy)

OK, now you'll just want to clean up the language.  To the left of the colon you're referring to the process, while to the right you're referring to the system.  Since you're in fact you're referring to a combination of both, separating the two with the colon makes things a bit confusing.  I'd recommended instead writing:  "And in particular the second law, which says that the entropy of an isolated system undergoing an irreversible process increases with time."

@theorist Thanks, edited. I also extended the analogy to incorporate the "irreversible process", which corresponds to "code execution"

Jelly, 0.68220949
“ȷ6ȷ5rỌ,®Ṿ€ṁṾY⁾©v⁸⁵”©v⁵

H90 = 19.779597644909596802, H0 = 4.088779347361360882, L0 = 23
I used long doubles to compute H90. Double precision floats incorrectly reported that H47 < H46
The first program prints
“…”
“ȷ6ȷ5rỌ,®Ṿ€ṁṾY⁾©v⁸⁵”©v1010

where … serves as a placeholder for all Unicode characters with code points between 100,000 and 1,000,000. The actual length is 900,031 characters.
The seconds program prints
“…”
“ȷ6ȷ5rỌ,®Ṿ€ṁṾY⁾©v⁸⁵”
“…”
“ȷ6ȷ5rỌ,®Ṿ€ṁṾY⁾©v⁸⁵”©v101010

which, in turn, prints
“…”
“ȷ6ȷ5rỌ,®Ṿ€ṁṾY⁾©v⁸⁵”
“…”
“ȷ6ȷ5rỌ,®Ṿ€ṁṾY⁾©v⁸⁵”
“…”
“ȷ6ȷ5rỌ,®Ṿ€ṁṾY⁾©v⁸⁵”©v10101010

etc.
None of these programs works in the online interpreter, which has a 100 KB output limit. However, if we modify the program to print 0123456789 instead of the aforementioned 900,000 Unicode characters, you can Try it online!

MATLAB, 9.6923e-005 0.005950967872272
H0 =  2.7243140535197345, Hinf = 4.670280547752703, L0 = 327

This new version is an improved version of the first "proof of concept". In this version I get a great score increase from the first iteration. This was achieved by "blowing up" the output of the first program, that is replicated by all the subsequent ones. Then I also tried to find the minimal H0 by just appending the most common symbol of the code as many times as possible. (This had obviously a limit, since it does not only decrease H0 but also increases L0 at the same time. You can see the development of the score plotted against the size of the program where the size is varied by just adding or removing 1.) The subsequent iterations still are equivalent to the previous version below.
a=['ns}z2e1e1116k5;6111gE16:61kGe1116k6111gE16:6ek7;:61gg3E1g6:6ek7;:61gg3E1'];11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111;;disp(['[''',a+1,'''];',0,'a=[''',a,'''];',0,[a-10,']]);'],0,[a-10,']]);']]);

Previous version:
H0 = 4.22764479010266, Hinf = 4.243346286312808, L0 = 162

The following code is inspired by the matlab quine. It basically outputs just itself again twice. The clue is that for any iteration we have n lines of code and n-1 newline symbols \n. So as n approaches to infinity, the ratio of lines of code to newlines approaches 1, and at the same time this guarantees that we have a strictly monotonous growth in entropy. That also means we can easily calculate Hinf by just considering the zero-th generation code with equally many newlines as lines of code. (Which one can experimentally confirm, as it converges quite quickly.)
a=['ns}z2e1kGe1116k6111gE16;:61kGe1116k6111gE16;:6ek7;:61gg3E1g6;:6ek7;:61gg3E1'];
disp(['a=[''',a,'''];',10,'a=[''',a,'''];',10,[a-10,']]);'],10,[a-10,']]);']]);

Very nice! Would you gain something replacing 10 by 0 (and adjusting the rest of the code for that)? Char 0 is displayed as space by Matlab

Thanks for the suggestion! Let me try it, but I think there are some other improvements that would increase the score a lot more. This should first of all be a proof of concept :)

I included now your suggestion along with a bunch of other improvements.

I like that optimization graph :-)

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Sample a random non-decreasing sequence
Input: Two integers n and k given in any form that is convenient for your code
Output A random non-decreasing sequence of k integers, each in the range 1 to n.   The sample should be chosen uniformly from all non-decreasing sequences of k integers with integers in the range 1 to n.
The output can be in any reasonable format you find convenient.
You can use whatever pseudo-random generator your favorite library/language provides.
We can assume that the integers n,k > 0.
Example
Say n,k = 2. The non-decreasing sequences are
1,1
1,2
2,2

Each sequence should have probability 1/3 of being outputted.
Restriction
Your code should run in no more than a few seconds for k = 20 and n = 100.
What doesn't work
If you just sample each integer randomly from the range 1 to n and then sort the list you won't get a uniform distribution.

Outputting the number of non-decreasing sequences for n,k might make an interesting challenge on its own, if it hasn't already been done...

@ETHproductions Not really, it's just a binomial (related to this)

@Sp3000 Ah, OK. It was a fun challenge for me to figure out how to calculate it efficiently though.

Your requirement that each sequence have equal probability of being output is not possible to satisfy with most garden variety PRNGs which may have just 32 or 48 bit states. According to Wolfram, there are 535 quintillion 20 element subsequences of 1, ..., 100 (didn't check how many of them are nondecreasing). 2^64 is just 18 quintillion.

Actually, 14 12 bytes
This answer is based on Emigna's 05AB1E answer and the answers on this Math.SE question. Golfing suggestions welcome! Try it online!
;;ra+DR╚HS♀-

Ungolfing
      Implicit input n, then k.
;;    Duplicate k twice.
r     Push range [0...k] for later.
a     Invert the stack. Stack: n, k, k, [0...k]
+DR   Push the range [1..n+k-1].
╚     Shuffle the range. Stack: shuffled_range, k, [0...k]
H     Push the first k elements of shuffled_range. Call this increasing.
S     Sort increasing so the elements are actually increasing.
♀-    Subtract each element of [0...k] from each element of increasing.
      This gives us our non-decreasing sequence.
      Implicit return.

Python, 89 bytes
from random import*
lambda n,k:[x-i for i,x in enumerate(sorted(sample(range(1,n+k),k)))]

Generating an increasing sequence rather than a non-decreasing one would be straightforward: this is just a random subset of k numbers between 1 and n, sorted.
But, we can convert an increasing sequence to a non-decreasing one by shrinking each gap between consecutive numbers by 1. So, a gap of 1 becomes a gap of 0, making equal numbers. To do so, decrease the i'th largest value by i
r[0], r[1], ..., r[n-1]  =>  r[0]-0, r[1]-1, ..., r[n-1]-(n-1)

For the result to be from 1 to n, the input must be from 1 to n+k-1. This gives a bijection between non-decreasing sequences of numbers between 1 and n, to increasing sequences between 1 and n+k-1. The same bijection is used in the stars and bars argument for counting such sequences.
The code uses the python function random.sample, which takes k samples without replacement from the input list. Sorting it gives the increasing sequence.

This is impressive. Could you add an explanation of the method please?

Yup, busy now, will explain later.

I counted 90 bytes... (and you can also import* to  save 1 byte)

@Rod Thanks, I forgot about that.

87 bytes

@Danis That's a nice way to enumerate in 3.8+ (which postdates this challenge), I'll keep it in mind.

05AB1E, 13 bytes
+<L.r¹£{¹L<-Ä

Try it online!
Explanation
+<L            # range [1 ... n+k-1]
   .r          # scramble order
     ¹£        # take k numbers
       {       # sort
        ¹L<-   # subtract from their 0-based index
            Ä  # absolute value

Python, 87 bytes
from random import*
f=lambda n,k:k>random()*(n+k-1)and f(n,k-1)+[n]or k*[7]and f(n-1,k)

The probability that the maximum possible value n is included equals k/(n+k-1). To include it, put it at the end of the list, and decrement the needed numbers remaining k. To exclude it, decrement the upper bound n. Then, recurse until no more values are needed (k==0).
Python's random doesn't seem to have a built-in for a Bernoulli variable: 1 with some probability, and 0 otherwise. So, this checks if a random value between 0 and 1 generated by random falls below k/(n+k-1). Python 2 would the ratio as float division, so we instead multiply by the denominator: k>random()*(n+k-1).

Would numpy help here?

@Lembik Good thought, but it looks like you'd have to import numpy.random, which is too long.

JavaScript (Firefox 30+), 74 bytes
(n,k,i=0,j=k)=>[for(_ of Array(q=k+n-1))if(Math.random(++i)<k/q--)i-j+k--]

Explanation
xnor's excellent Python answer contains a very good summary of how/why the technique used here works. The first step is to create the range [1, 2, ..., n + k - 1]:
(n,k,i=0)=>[for(_ of Array(q=k+n-1))++i]

Next we need to take k random items from this range. To do this, we need to select each item with probability s / q, where s is the number of items still needed and q is the number of items left in the range. Since we're using an array comprehension, this is fairly easy:
(n,k,i=0)=>[for(_ of Array(q=k+n-1))if(Math.random(++i)<k/q--)k--&&i]

This gives us a uniformly distributed increasing sequence of numbers. This can be fixed by subtracting the number of items j that we have previously found:
(n,k,i=0,j=0)=>[for(_ of Array(q=k+n-1))if(Math.random(++i)<k/q--)k--&&i-j++]

Finally, by storing k in j, we can incorporate k-- into the expression and save a few bytes:
(n,k,i=0,j=k)=>[for(_ of Array(q=k+n-1))if(Math.random(++i)<k/q--)i-j+k--]

TI-BASIC, 53 Bytes
Prompt N,K
K→dim(L1
While K
If rand<K/(N+K-1
Then
N→L1(K
K-1→K
Else
N-1→N
End
End
L1

Follow's xnor's logic, with a small caveat.  We could theoretically shave a byte by doing something like this:
K>rand(N+K-1

But rand( is reserved to create a list of random numbers, so we wouldn't be able to do the desired implicit multiplication to save a byte.
This should run decently fast on an 84+ per the restriction but I'll check to make sure when I can.

PHP, 77 75 73 bytes
foreach(array_rand(range(2,$argv[1]+$k=$argv[2]),$k)as$v)echo$v+1-$i++,_;

Run like this:
php -r 'foreach(array_rand(range(2,$argv[1]+$k=$argv[2]),$k)as$v)echo$v+1-$i++,_;' -- 10 5 2>/dev/null;echo
> 1_4_6_9_9_

Explanation
foreach(                    # Iterate over...
  array_rand(               #   a (sorted) random number of items from...
    range(                  #     an array with items...
      2,                    #       from 2
      $argv[1]+$k=$argv[2]  #       to n + k (set arg 2 to $k)
    ),
    $k                      #     Take k number of items (their keys)
  )
  as $v
)
  echo $v +1 - $i++,"_";    # Print the value subtracted by the index.
                            # Need to add 1, because keys are 0-indexed.

Tweaks

Saved 2 bytes by removing end() call and set $argv[2] to $k instead to shorten access to arguments
Saved 2 bytes by removing the index from the foreach, since it's simply an incrementing number. Just increment $i each iteration instead

First JavaScript and now PHP. All the best scientific programming languages :) Thank you.

@Lembik, you're welcome. Mind you, it uses a basic PRNG. Do not use for cryptographic stuff. :)


text:
Do Matrix Multiplication!
In mathematics, matrix multiplication or the matrix product is a binary operation that produces a matrix from two matrices. The definition is motivated by linear equations and linear transformations on vectors, which have numerous applications in applied mathematics, physics, and engineering. In more detail, if A is an n × m matrix and B is an m × p matrix, their matrix product AB is an n × p matrix, in which the m entries across a row of A are multiplied with the m entries down a columns of B and summed to produce an entry of AB. When two linear transformations are represented by matrices, then the matrix product represents the composition of the two transformations.
Source: Wikipedia
In other words, to multiply two matrices, for example:
1 2 3   1 4
2 3 4 × 3 1 =
3 4 5   4 6

First, take row number 1 in the first matrix, column number 1 in the second matrix, and multiply 1 by 1, 2 by 3, and 3 by 4.
1 × 1 = 1
2 × 3 = 6
3 × 4 = 12

Now add them together to get your first item:
1 2 3   1 4   19
2 3 4 × 3 1 =
3 4 5   4 6

For the second number in the first column of the result, you will need to take row number 2 instead of row number 1 and do the same thing.
1 × 2 = 2
3 × 3 = 9
4 × 4 = 16
      = 27

After you do the entire first column, the result looks like this:
1 2 3   1 4   19
2 3 4 × 3 1 = 27
3 4 5   4 6   35

Now, do the same exact thing again, but take the second column instead of the first column, resulting in:
1 2 3   1 4   19 24
2 3 4 × 3 1 = 27 35
3 4 5   4 6   35 46

Your task
Given two matrices (max dimensions 200x200), containing numbers in the range -10000 to 10000, where the number of columns on the first one equals the number of rows on the second, multiply the first one by the second one. (Matrix multiplication is non-commutative.)
You may take input and give output as an array of arrays (or equivalent), a matrix (if your language has that format) or a multiline string.
You may not use any built-ins for matrix multiplication.
Test cases
1 2   1 2 3 4 5    13 16 19 22 25
3 4 × 6 7 8 9 10 = 27 34 41 48 55
5 6                41 52 63 74 85

2 3   3 5   15 13
3 4 × 3 1 = 21 19

5 3            11    27
1 3      1 3   7     15
9 3    × 2 4 = 15    39
1 -1000        -1999 -3997

Remember, this is code-golf, so the code with the fewest bytes wins.

Can we use built-in dot products? They operate on vectors, not matrices.

Is the input order fixed or can we take a and b in that order and output b × a?

@Dennis You can reverse the input, but no dot products

Challenges about doing X without Y are discouraged.

Can the input matrices contain floating point numbers? If so, I recommend adding a test case with some.

Python, 1 byte: @ It’s the matmul operator in python!

Jelly, 7 5 bytes
Z×þḅ1

Takes B and A as arguments and returns A × B.
Try it online!
How it works
Z×þḅ1  Main link. Left argument: B. Right argument: A

Z      Zip; transpose B's rows and columns.
 ×þ    Table multiplication; multiply all columns of B (rows of B's transpose) by
       all rows of A, element by element. Results are grouped by the rows of A.
   ḅ1  Unbase 1; compute the sum of all flat arrays in the result.

So wait, the built-in and the manual way to multiply matrices end up being the same number of bytes in Jelly?  That's confusing, but cool.

@Yodle The built-in is æ×, which is 2 bytes.

@EriktheOutgolfer That was in reference to revision 2, which used the æ. atom.

Python 2, 69 66 Bytes
This just follows the standard formula, but lambda-d for conciseness :) The ungolfed code is extremely straightforward!
lambda x,y:[[sum(map(int.__mul__,r,c))for c in zip(*y)]for r in x]

Thanks to Alexi Torhamo for saving 3 bytes! :)
Ungolfed code:
x = [[1,2],[3,4],[5,6]]
y = [[1,2,3,4,5],[6,7,8,9,10]]

output = []
for row in x:
    nrow = []
    for col in zip(*y):                             # zip(*[]) transposes a matrix
        nrow += [sum(a*b for a,b in zip(row,col))]  # multiplication for each pair summed
    output += [nrow]

print output

You could use sum(map(int.__mul__,r,c)) to save 3 bytes. (Won't work with floating point, but that wasn't required, either)

05AB1E, 13 bytes
vyU²øvyX*O})ˆ

Try it online!
Explanation
v               # for each row in the first matrix
 yU             # save the row in X
   ²øv          # for each row in the transposition of the second matrix
      yX*       # multiply the rows
         O      # sum the elements of the resulting row
          }     # end inner loop
           )    # wrap elements of the new row in a list
            ˆ   # push to global list
                # implicitly output global list

Can be 7 bytes now with the exact same approach: εUøεX*O

Haskell, 57 56 54 bytes
e=[]:e
z=zipWith
a!b=[sum.z(*)r<$>foldr(z(:))e b|r<-a]

Try it online!
Usage:
Prelude> [[1,2],[3,4],[5,6]] ! [[1,2,3,4,5],[6,7,8,9,10]]
[[13,16,19,22,25],[27,34,41,48,55],[41,52,63,74,85]]

foldr(zipWith(:))e with e=[]:e is a shorter form of transpose.

Haskell, 45 bytes
map.(foldr1(z(+)).).flip(z$map.(*))
z=zipWith

Try it online!
Takes arguments in reversed order.

J, 13 9 bytes
Saved 4 bytes thanks to miles!
[:+/*"#:~

This is a capped fork:
[: +/ *"#:~

Which is equivalent to:
[: +/ (*"#:)~
[: +/ (*"_ 1 0)~

Which performs the desired multiplication; these are then summed.
With a dot product built in, 5 bytes: +/ .*
Test cases
   f =: [: +/ *"#:~
   (3 3$1 2 3 2 3 4 3 4 5)f(3 2$1 4 3 1 4 6)
19 24
27 35
35 46
   (3 3$1 2 3 2 3 4 3 4 5);(3 2$1 4 3 1 4 6)
+-----+---+
|1 2 3|1 4|
|2 3 4|3 1|
|3 4 5|4 6|
+-----+---+
   (2 2$2 3 3 4)f(2 2$3 5 3 1)
15 13
21 19
   (2 2$2 3 3 4);(2 2$3 5 3 1)
+---+---+
|2 3|3 5|
|3 4|3 1|
+---+---+

I just stumbled upon [:+/*"#:~ for 9 bytes

@miles spectacular!

Mathematica, 20 bytes
Inner[1##&,##,Plus]&

Anonymous function. Takes two rank-2 lists of numbers as input, and returns a rank-2 list of numbers as output. For those curious, Inner is a function that does a matrix-multiplication-like application of two functions to two tensors.

I believe Inner[1##&,##]& is equivalent to Inner[1##&,##,Plus]&...? And so 1##&~Inner~##& would be even better.

Husk, 7 6 bytes
mMδṁ*T

Please note the argument order, try it online!
-1 byte thanks to @Zgarb!
Explanation
Basically just doing what the definition of matrix-multiplication sais:
mMδṁ*T  -- takes arguments in reverse order, eg: [[1],[0],[-1]] [[1,2,3],[4,5,6]]
     T  -- transpose the first argument: [[1,0,-1]] [[1,2,3],[4,5,6]]
m       -- map the following function (example element [1,0,-1])
 M      --   map the following function applied to [1,0,-1] (example element [1,2,3])
  δṁ    --     accumulate a sum of element-wise..
    *    --    ..multiplication: -2
          -- [[-2],[-2]]

oΣz can be δṁ

K (ngn/k), 6 bytes
+/'*\:

Try it online!
Because arraylang FTW.
How it works
+/'*\:    Dyadic train; x: m×n matrix; y: n×p matrix
   *\:    Multiply eachleft; multiply each row of x to whole of y
          each row of x (xr) = length-n vector
          each element of xr is multiplied to each row of y
          the result is m×n×p cube
+/'       Sum each; sum across the 2nd axis to get the m×p matrix

Jelly port is ×"€S€ which only ties with the existing solution.

J, 7 bytes
+/@:*"$

Try it online!
Port of the more well-known K idiom (+/*)\: (for each row of x1 and entirety of x2, first-axis multiply and sum). "$ is the shorthand for "1 _, which satisfies the "for each row of x1 and entirety of x2" part.

MATL, 12 11 bytes
7L&!*Xs6Be!

Matrices are input using ; as row separator.
Try it online!
Matrix multiplication without the builtin was part of my answer to Showcase of languages. However, when trying to reuse the original code for this answer I realized it had a bug (row vector output was incorrectly converted to a column vector). This is now corrected, both here and there. For an explanation of how the code works, see the referred post (length-11 snippet).

C#, 168 167 bytes
(A,B)=>{int n=A.Length,p=B[0].Length,i=0,j=0,k=0,s;var R=new int[n,p];while(i++<n)for(j=0;j<p;){s=0;for(k=0;k<A[0].Length;)s+=A[i][k]*B[k++][j];R[i,j++]=s;}return R;};

Thank you @Mukul Kumar for saving 1 byte, the while loop was actually shorter this time :P
Full program with test cases:
using System;
class Matrix
{
    static void Main()
    {
        Func<int[][], int[][], int[,]> a = null;

        a = (A,B)=>
        {
            int n=A.Length,p=B[0].Length,i=0,j=0,k=0,s;
            var R=new int[n,p];
            while(i++<n)
                for(j=0;j<p;)
                {
                    s=0;
                    for(k=0;k<A[0].Length;)
                        s+=A[i][k]*B[k++][j];
                    R[i,j++]=s;
                }
            return R;
        };

        int[,] t1 = a(new int[][] { new int[] { 1, 2 }, new int[] { 3, 4 }, new int[] { 5, 6 } },
            new int[][] { new int[] { 1, 2, 3, 4, 5 }, new int[] { 6, 7, 8, 9, 10 } } );
        int[,] t2 = a(new int[][] { new int[] { 2, 3 }, new int[] { 3, 4 } },
            new int[][] { new int[] { 3, 5 }, new int[] { 3, 1 } });
        int[,] t3 = a(new int[][] { new int[] { 5, 3 }, new int[] { 1, 3 }, new int[] { 9, 3 }, new int[] { 1, -1000 } },
            new int[][] { new int[] { 1, 3 }, new int[] { 2, 4 } });

        Console.WriteLine(IsCorrect(t1, new int[,] { { 13, 16, 19, 22, 25 }, { 27, 34, 41, 48, 55 }, { 41, 52, 63, 74, 85 } } ));
        Console.WriteLine(IsCorrect(t2, new int[,] { { 15, 13 }, { 21, 19 } } ));
        Console.WriteLine(IsCorrect(t3, new int[,] { { 11, 27 }, { 7, 15 }, { 15, 39 }, { -1999, -3997 } } ));

        Console.Read();
    }

    static bool IsCorrect(int[,] answer, int[,] valid)
    {
        if (answer.Length != valid.Length)
            return false;
        for (int i = 0; i < answer.GetLength(0); i++)
            for (int j = 0; j < answer.GetLength(1); j++)
                if (answer[i, j] != valid[i, j])
                    return false;
        return true;
    }
}

You can trim a few bytes by using while loops....

@MukulKumar Wait, I don't think so.  At most, they break even right?  for(;i<n;) -> while(i<n) are both 10 bytes.

for (;i <n;i++)  ->  while (i++<n) saves 1 byte

Not sure of the etiquette when I have a fairly different answer, but my alternative was definitely inspired by this.

R, 66 bytes
function(A,B)apply(B,2,function(i)apply(A,1,function(j)sum(j*i)))

Unnamed function taking two R-matrices as input and returns the product. It makes use of apply which is used to apply functions across margins of arrays. It works just as a double for loop in this case: for each column of B and for each row of A, return the sum of the (vectorized) products.
Compare to the pure for loop approach (101 bytes):
function(A,B){M=matrix(NA,m<-nrow(A),n<-ncol(B));for(i in 1:n)for(j in 1:m)M[j,i]=sum(A[j,]*B[,i]);M}

Not at my desktop at the moment, but couldn't you do something like outer(A,B,\*`)rather than the embeddedapply` calls?

@rturnbull I'm not sure how outer works in conjunction with matrices but it would produce a 4-D array in a this case.

Ah yes, that is a little problematic. Linearizing the matrices would likely take more bytes than your approach here

C++14, 173 168 156 146 bytes

-5 bytes for returning via reference parameter
-12 bytes for using foreach and C.back() instead counting on i
-10 bytes for dropping C.clear() and requiring C to be empty at start

As unnamed lambda:
[](auto A,auto B,auto&C){int j,k,s=B[0].size();for(auto a:A){C.emplace_back(s);for(j=-1;++j<s;)for(k=-1;++k<B.size();C.back()[j]+=a[k]*B[k][j]);}}

Requires input and output as vector<vector<int>> and output must be empty beforehand.
Ungolfed:
auto f=
[](auto A, auto B, auto&C){
 int j,k,s=B[0].size();
 for (auto a:A){
  C.emplace_back(s);
  for (j=-1;++j<s;)
   for (k=-1;++k<B.size();
    C.back()[j]+=a[k]*B[k][j]
   );
 }
}
;

Sample:
int main() {
 using M=std::vector<std::vector<int>>;
 M a = {
  {1,2,3},
  {2,3,4},
  {3,4,5},
 };
 M b = {
  {1,4},
  {3,1},
  {4,6},
 };
 M c;
 f(a,b,c);
 for (auto&r:c){
  for (auto&i:r) std::cout << i << ", ";
  std::cout << "\n";
 }
}

Why not use push_back() instead of emplace_back()?

132 bytes

JavaScript (ES6), 66 bytes
(a,b)=>a.map(c=>b[0].map((_,i)=>b.reduce((s,d,j)=>s+d[i]*c[j],0)))

C#, 131 bytes
(A,B)=>new List<List<int>>(A.Select(x=>new List<int>
    (B[0].Select((f,i)=>B.Select(r=>r[i])).Select(y=>x.Zip(y,(p,q)=>p*q).Sum()))));

I stole Yodle's solution with the assumption that I could write this more efficiently using LINQ (as opposed to for loops). Took a few attempts but crunched it down somewhat.
Here it is broken down somewhat:
a = (A, B) => new List<List<int>>(
            from x in A
            select new List<int>(
                from y in B.First().Select((f, i) => B.Select(r => r.ElementAt(i)))
                select x.Zip(y, (p, q) => p * q).Sum()));

The only real 'trick' here is the matrix transpose, B.First().Select((f, i) => B.Select(r => r.ElementAt(i))). Once we transpose the second matrix, we have two arrays A[i,x] and B[j,x]. Take the cartesian product (i*j) and Zip each of those x length arrays together.
Test code:
using System;
class Matrix
{
    static void Main()
    {
        Func<int[][], int[][], List<List<int>>> a = null;
        a = (A, B) => new List<List<int>>(A.Select(x => new List<int>(B[0].Select((f, i) => B.Select(r => r[i])).Select(y => x.Zip(y, (p, q) => p * q).Sum()))));

        List<List<int>> t1 = a(new int[][] { new int[] { 1, 2 }, new int[] { 3, 4 }, new int[] { 5, 6 } },
            new int[][] { new int[] { 1, 2, 3, 4, 5 }, new int[] { 6, 7, 8, 9, 10 } });
        List<List<int>> t2 = a(new int[][] { new int[] { 2, 3 }, new int[] { 3, 4 } },
            new int[][] { new int[] { 3, 5 }, new int[] { 3, 1 } });
        List<List<int>> t3 = a(new int[][] { new int[] { 5, 3 }, new int[] { 1, 3 }, new int[] { 9, 3 }, new int[] { 1, -1000 } },
            new int[][] { new int[] { 1, 3 }, new int[] { 2, 4 } });

        Console.WriteLine(IsCorrect(t1, new int[,] { { 13, 16, 19, 22, 25 }, { 27, 34, 41, 48, 55 }, { 41, 52, 63, 74, 85 } }));
        Console.WriteLine(IsCorrect(t2, new int[,] { { 15, 13 }, { 21, 19 } }));
        Console.WriteLine(IsCorrect(t3, new int[,] { { 11, 27 }, { 7, 15 }, { 15, 39 }, { -1999, -3997 } }));

        Console.Read();
    }

    static bool IsCorrect(List<List<int>> answer, int[,] valid)
    {
        if (answer.Count*answer[0].Count != valid.Length)
            return false;
        for (int i = 0; i < answer.Count; i++)
            for (int j = 0; j < answer[0].Count; j++)
                if (answer[i][j] != valid[i, j])
                    return false;
        return true;
    }

}

Nice :P I've never really used Linq all that much, so I'm not fully aware of all the capabilities of it so I tend to just use standard loops and stuff.  However, I think you have to include the using System.Linq; line in your byte count, not sure how much that effects it.

@Yodle yes I would have to include using System.Linq; I'm not sure if solutions here need to include boilerplate like using System and static void Main()

I've been answering for a bit now, and from what I've seen, basically your answer (whatever you're including in your byte count) has to work if you just pasted it into a program.  For C# specifically, if you're writing just a function then you don't need to include class definitions or the static void Main() stuff, but if your solution uses any library stuff like Console.WriteLine() then you have to do System.Console.WriteLine() or using System; since one may be shorter.

Haskell, 49 bytes
z=zipWith
m a=map(\x->foldr1(z(+))$z(map.(*))x a)

Try it online!
Input and output are lists of columns. Maps each column of the second matrix to that row, zipped with the columns of the first matrix and scaling each, summed as a vector.
I feel that there's gotta be a nice way to make this pointfree and save a handful of bytes, but I'm not seeing it yet.

ayr, 9 bytes
An array lang I'm currently working on. It's not complete, but it can solve this just fine.
+/&*\@;:=

Explanation
A = left matrix, B = right matrix

        =  Transpose B
    \      Table of A and =B
+/&*       Reduction via sum after multiplying
     @;:   After squishing (rank-2 matrix to rank-1 vector) both args

I'm probably going to add inner product eventually, so this solution will eventually be + .* or +/ .*, haven't decided which yet. I can't make use of the k idiom, as multiplication between a vector and matrix is currently unsupported, resulting in a rank error.

Uiua, 5 bytes
∺'/+×

Try it online!
Takes two matrices in reverse order, because ∺ distribute evaluates on the entirety of the first arg and each row of the second, and there is no mirror version of it. Other than that, this also works like the K idiom.
∺'/+×    input: matrix A(m*k), matrix B(n*m)
∺        map over the entirety of A(m*k) and each row of B(m):
 '  ×    multiply each row of A and each element of B and
  /+     sum each column

PHP, 110 bytes
function f($a,$b){foreach($a as$n=>$x)foreach($b as$m=>$y)foreach($y as$p=>$v)$z[$n][$p]+=$v*$x[$m];return$z;}

Three loops for the elven arrays. This is so straight forward ... but there´s not much to golf.

Actually, 14 bytes
Golfing suggestions welcome! Try it online!
┬@;l)∙`i♀*Σ`M╡

Ungolfing
         Implicit input A, then B.
┬        Transpose B's rows and columns. Call it B_T.
@        Swap A to TOS.
;l)      Get len(A) and move to BOS for later.
∙        Push the Cartesian product of A and B_T. Call it cart_prod.
`...`M   Map the following function over cart_prod. Variable xs.
  i        Flatten xs onto the stack, getting a row of A and column of B.
  ♀*       Multiply each element of A_row by each element of B_column.
  Σ        Sum the resulting list to get an element of A*B.
         The result of the map returns every element of A*B, but in one flat list.
╡        Push a list containing len(A) non-overlapping sublists of A*B.
         This separates A*B into rows.
         Implicit return.

Javascript, 128 bytes
m=(a,b)=>{$=[];q=0;for(x in b){c=[];j=0;for(y in a[0]){_=i=0;for(z in b[0]){_+=a[i][j]*b[q][i];i++}c.push(_);j++}$.push(c);q++}}

You get the result by just checking $ - it's kinda cheating, but hey, it saved a few bytes.

C, 618 bytes
M(char*a,char*b){char*P[2];P[0]=malloc(strlen(a));P[1]=malloc(strlen(b));for(int A=0;A<strlen(a);A++){P[0][A]=a[A];};for(int B=0;B<strlen(b);B++){P[1][B]=b[B];};int H[200][200],B[200][200];int O,N,m,J;for(int Y=0;Y<2;Y++){int y=0,z=0,r=0;char j[7];int p=strlen(P[Y]);for(int i=0;i<=p;i++){if(P[Y][i]==' '||P[Y][i]==','||i==p){(Y<1)?H[y][z]=atoi(j):(B[y][z]=atoi(j));memset(j,'\0',4);(P[Y][i]==' ')?z++:y++;z=(P[Y][i]==',')?0:z;r=0;}else{j[r]=P[Y][i];r++;};};(Y<1)?O=z+1,N=y:(m=y,J=z+1);};for(int U=0;U<N;U++){for(int F=0;F<J;F++){int T=0;for(int d=0;d<O;d++){T+=H[U][d]*B[d][F];};printf("%d ",T);T=0;};printf("\n");};}

A named function and by far the longest submission here, partly due to the fact that converting the character array inputs into C 2-dimensional integer arrays is taking up the most bytes, and also because I have not golfed in C in the longest time. I am still working on shortening this as much as I can, and any tips in doing so are much appreciated.
Now, with that out of the way, this takes input through the command line with the two matrices represented by two strings, with each one containing the rows separated by commas and each row represented by space separated integers. For example, the matrices:
   1 2 3     44 52
A= 4 5 6  B= 67 -79
   7 8 9     83 90

would be input as:
./a.out "1 2 3,4 5 6,7 8 9" "44 52,67 -79,83 90"
The resulting matrix is output to STDOUT as a multiline string. For example, the output for the above input would be:
 427 164
1009 353
1591 542

TIO 539 bytes

Building on @girobuz 319 bytes

Clojure, 60 bytes
#(for[a %](for[b(apply map vector %2)](apply +(map * a b))))

Many bytes spent on transposing the 2nd argument.

Ruby, 59 bytes
->m,n{m.map{|r|n.transpose.map{|c|r.zip(c).sum{|i,j|i*j}}}}

Try it online!

Raku, 55 bytes
{cross(with=>{sum @^x Z*@^y},@^a,[Z] @^b).rotor(@b[0])}

Try it online!

Julia 1.0, 49 bytes
% =axes
a\b=[sum(a[i,:].*b[:,j]) for i=a%1,j=b%2]

Try it online!
1 byte

Nibbles, 5.5 bytes (11 nibbles)
.$.`'_+!$_*

Attempt This Online!
.$           # map over the rows of matrix 1
  .          #   map over the rows of
   `'        #   transpose of
     _       #   matrix 2
      +      #     sum of
       !     #     zip together
        $_   #     both rows
          *  #       by multiplication

Nekomata, 4 bytes
ᵐ*ᵐ∑

Attempt This Online!
ᵐ*ᵐ∑
ᵐ       Map
 *      Multiply
  ᵐ     Map
   ∑    Sum

If a built-in for dot product is allowed, then it can be 2 bytes:
ᵐ∙

Attempt This Online!