问:
Tips for golfing in MATL
MATL is a golfing language created by Luis Mendo. MATL has proven to be highly competitive, often beating submissions in other golfing languages such as Pyth, CJam and Jelly.

What are some useful tips for golfing in MATL? (As always, one tip per answer, please!)

For the record, MATL can be tested online here.

Documentation can be found on Github

答:
Get familiar with MATL's truthy/falsy definitions

While true (T) and false (F) clearly represent truthy and falsy output, respectively, the widely agreed upon definition of truthy/falsy gives us a little bit more flexibility in MATL.

The definition states:

```<code>if (x)
    disp("x is truthy");
else
    disp("x is falsy");
end
</code>```

So we can write a quick MATL truthy/falsy test which will loop through all inputs and display whether they were considered to be truthy or falsy

```<code>` ? 'truthy' } 'falsey' ]DT
</code>```

Here is an online version.

What this means in MATL

What this actually translates to in MATL (and therefore in MATLAB and Octave) is that a condition is considered to be true if if it is non-empty and real components of all its values are non-zero. There are two parts to this that should be emphasized.

Non-zero: This means precisely that, not equal to zero (==). This includes positive numbers, negative numbers, non-null characters, etc. You can easily check by converting a given value to a logical value (g) or you can use ~~

```<code>F           % Falsy
T           % Truthy
0           % Falsy
1           % Truthy
2           % Truthy
-1          % Truthy
'a'         % Truthy
' '         % Truthy (ASCII 32)
char(0)     % Falsy  (ASCII 0)
</code>```

All values: Typically we think of scalars as being true or false, but in MATL, we can evaluate scalars, row vectors, column vectors, or even multi-dimensional matrices and they are considered to be truthy if and only if every single value is non-zero (as defined above), otherwise they are falsy. Here are a few examples to demonstrate

```<code>[1, 1, 1]           % Truthy
[1, 0, 0]           % Falsey
[1, 1, 1; 1, 1, 1]  % Truthy
[1, 0, 1; 1, 1, 1]  % Falsey
'Hello World'       % Truthy
</code>```

The one edge case, as mentioned above, is an empty array [], which is always considered to be falsy (example)

How can I use this to golf better?

If the challenge simply mentions that your output should be truthy or falsy, you can likely exploit the definition above to shave a few bytes off of your answer. To save confusion, it is recommended that you include a link to the online truthy/falsy test above in your answer to help explain how MATL truthy/falsy values work.

A couple of specific examples:

An answer ending in A. If the challenge requires a truthy or falsy output and you end your answer in all (A) to create a scalar, you can remove this last byte and your answer will remain correct (unless the output is [] since [] is false but []A is true).

Ensuring that an array contains only one unique value: Uses &= in place of un1=. If all values in an array are equal, a broadcasted element-wise equality comparison will yield an N x N matrix of all ones. If all values are not equal, this matrix will contain some 0 values and therefore be considered falsy.

Title: Tips for golfing in MATL

Body:
Get familiar with MATL's truthy/falsy definitions

While true (T) and false (F) clearly represent truthy and falsy output, respectively, the widely agreed upon definition of truthy/falsy gives us a little bit more flexibility in MATL.

The definition states:

if (x)
    disp("x is truthy");
else
    disp("x is falsy");
end

So we can write a quick MATL truthy/falsy test which will loop through all inputs and display whether they were considered to be truthy or falsy

` ? 'truthy' } 'falsey' ]DT

Here is an online version.

What this means in MATL

What this actually translates to in MATL (and therefore in MATLAB and Octave) is that a condition is considered to be true if if it is non-empty and real components of all its values are non-zero. There are two parts to this that should be emphasized.

Non-zero: This means precisely that, not equal to zero (==). This includes positive numbers, negative numbers, non-null characters, etc. You can easily check by converting a given value to a logical value (g) or you can use ~~

F           % Falsy
T           % Truthy
0           % Falsy
1           % Truthy
2           % Truthy
-1          % Truthy
'a'         % Truthy
' '         % Truthy (ASCII 32)
char(0)     % Falsy  (ASCII 0)

All values: Typically we think of scalars as being true or false, but in MATL, we can evaluate scalars, row vectors, column vectors, or even multi-dimensional matrices and they are considered to be truthy if and only if every single value is non-zero (as defined above), otherwise they are falsy. Here are a few examples to demonstrate

[1, 1, 1]           % Truthy
[1, 0, 0]           % Falsey
[1, 1, 1; 1, 1, 1]  % Truthy
[1, 0, 1; 1, 1, 1]  % Falsey
'Hello World'       % Truthy

The one edge case, as mentioned above, is an empty array [], which is always considered to be falsy (example)

How can I use this to golf better?

If the challenge simply mentions that your output should be truthy or falsy, you can likely exploit the definition above to shave a few bytes off of your answer. To save confusion, it is recommended that you include a link to the online truthy/falsy test above in your answer to help explain how MATL truthy/falsy values work.

A couple of specific examples:

An answer ending in A. If the challenge requires a truthy or falsy output and you end your answer in all (A) to create a scalar, you can remove this last byte and your answer will remain correct (unless the output is [] since [] is false but []A is true).

Ensuring that an array contains only one unique value: Uses &= in place of un1=. If all values in an array are equal, a broadcasted element-wise equality comparison will yield an N x N matrix of all ones. If all values are not equal, this matrix will contain some 0 values and therefore be considered falsy.


答:
Perl 6, 16 bytes

{({@_}…*)[$_]}
```

<p>Returns nested data structure.</p>

<h2>Example:</h2>

<pre class="lang-perl6 prettyprint-override"><code>say {({@_}…*)[$_]}( 4 );
# [[] [[]] [[] [[]]] [[] [[]] [[] [[]]]]]
</code>```

Explanation:

{   # lambda with implicit parameter ｢$_｣

  (

    # produce a lazy infinite sequence of all results

    {       # lambda with implicit parameter ｢@_｣
      @_    # array containing all previously seen values in the sequence
    }

    …       # keep repeating that block until:

    *       # Whatever ( never stop )

  )[ $_ ]   # use the outer block's argument to index into the sequence

}
```

ContentLicense: CC BY-SA 3.0

Title: Natural construction

Body:
The natural numbers including 0 are formally defined as sets, in the following way:

Number 0 is defined as the empty set, {}

For n ≥ 0, number n+1 is defined as n ∪ {n}.

As a consequence, n = {0, 1, ..., n-1}.

The first numbers, defined by this procedure, are:

0 = {}

1 = {{}}

2 = {{}, {{}}}

3 = {{}, {{}}, {{}, {{}}}}

Challenge

Given n, output its representation as a set.

Rules

The output can consistently use any bracket character such as {}, [], () or <>. Arbitrary characters (such as 01) are not allowed.

Instead of a comma as above, the separator can be any punctuation sign; or it may be inexistent.

Spaces (not newlines) may be included arbitrarily and inconsistently.

For example, number 2 with square brackets and semicolon as separator is [[]; [[]]], or equivalently [ [ ]; [ [ ] ] ], or even [  [ ] ;[  []]]

The order in which elements of a set are specified doesn't matter. So you can use any order in the representation. For example, these are some valid outputs for 3:

```<code>{{},{{}},{{},{{}}}}
{{{}},{{},{{}}},{}}
{{{}},{{{}},{}},{}}
</code>```

You can write a program or function. Output may be a string or, if using a function, you may return a nested list or array whose string representation conforms to the above.

Test cases

```<code>0  ->  {}
1  ->  {{}}
2  ->  {{},{{}}}
3  ->  {{},{{}},{{},{{}}}}
4  ->  {{},{{}},{{},{{}}},{{},{{}},{{},{{}}}}}
5  ->  {{},{{}},{{},{{}}},{{},{{}},{{},{{}}}},{{},{{}},{{},{{}}},{{},{{}},{{},{{}}}}}}
6  ->  {{},{{}},{{},{{}}},{{},{{}},{{},{{}}}},{{},{{}},{{},{{}}},{{},{{}},{{},{{}}}}},{{},{{}},{{},{{}}},{{},{{}},{{},{{}}}},{{},{{}},{{},{{}}},{{},{{}},{{},{{}}}}}}}
7  ->  {{},{{}},{{},{{}}},{{},{{}},{{},{{}}}},{{},{{}},{{},{{}}},{{},{{}},{{},{{}}}}},{{},{{}},{{},{{}}},{{},{{}},{{},{{}}}},{{},{{}},{{},{{}}},{{},{{}},{{},{{}}}}}},{{},{{}},{{},{{}}},{{},{{}},{{},{{}}}},{{},{{}},{{},{{}}},{{},{{}},{{},{{}}}}},{{},{{}},{{},{{}}},{{},{{}},{{},{{}}}},{{},{{}},{{},{{}}},{{},{{}},{{},{{}}}}}}}}
</code>```

Body:
Perl 6, 16 bytes

{({@_}…*)[$_]}

Returns nested data structure.

Example:

say {({@_}…*)[$_]}( 4 );
# [[] [[]] [[] [[]]] [[] [[]] [[] [[]]]]]

Explanation:

{   # lambda with implicit parameter ｢$_｣

  (

    # produce a lazy infinite sequence of all results

    {       # lambda with implicit parameter ｢@_｣
      @_    # array containing all previously seen values in the sequence
    }

    …       # keep repeating that block until:

    *       # Whatever ( never stop )

  )[ $_ ]   # use the outer block's argument to index into the sequence

}


问:
Least Common Multiple
The least common multiple of a set of positive integers A is the smallest postive integer B such that, for each k in A, there exists a positive integer n such that k*n = B.

Given at least two positive integers as input, output their least common multiple.

Rules

Builtins are allowed, but if your solution uses one, you are encouraged to include an alternate solution that does not use GCD/LCM builtins. However, the alternate solution will not count towards your score at all, so it is entirely optional.

All inputs and outputs will be within the natively-representable range for your language. If your language is natively capable of arbitrarily-large integers, then your solution must work with arbitrarily large inputs and outputs.

Test cases

```<code>[7, 2] -> 14
[8, 1] -> 8
[6, 4, 8] -> 24
[8, 2, 1, 10] -> 40
[9, 6, 2, 1, 5] -> 90
[5, 5, 7, 1, 1] -> 35
[4, 13, 8, 8, 11, 1] -> 1144
[7, 2, 2, 11, 11, 8, 5] -> 3080
[1, 6, 10, 3, 4, 10, 7] -> 420
[5, 2, 9, 10, 3, 4, 4, 4, 7] -> 1260
[9, 7, 10, 9, 7, 8, 5, 10, 1] -> 2520
</code>```

答:
C#, 50+18 = 68 bytes

50 bytes for method defintion, +18 bytes for LINQ import.

```<code>using System.Linq;int L(int[]n,int i=1)=>n.All(x=>1>i%x)?i:L(n,i+1);
</code>```

Pretty much the same as a lot of other answers. Counts up recursively until it finds the LCM. I was a bit surprised this didn't get a StackOverflowException, so I also have a non-recursive version which is actually just 1 byte longer.

```<code>using System.Linq;n=>{for(int i=1;;i++)if(n.All(x=>1>i%x))return i;};
</code>```

Ungolfed:

```<code>using System.Linq;            // Import LINQ
int L(int[] n, int i = 1) =>  // Function declaration
    n.All(x => 1 > i % x)     // Check if each x in n divides i
        ? i                   // And if so return i
        : L(n, i + 1)         // Otherwise increment i and recurse
;
</code>```

Title: Least Common Multiple

Body:
C#, 50+18 = 68 bytes

50 bytes for method defintion, +18 bytes for LINQ import.

using System.Linq;int L(int[]n,int i=1)=>n.All(x=>1>i%x)?i:L(n,i+1);

Pretty much the same as a lot of other answers. Counts up recursively until it finds the LCM. I was a bit surprised this didn't get a StackOverflowException, so I also have a non-recursive version which is actually just 1 byte longer.

using System.Linq;n=>{for(int i=1;;i++)if(n.All(x=>1>i%x))return i;};

Ungolfed:

using System.Linq;            // Import LINQ
int L(int[] n, int i = 1) =>  // Function declaration
    n.All(x => 1 > i % x)     // Check if each x in n divides i
        ? i                   // And if so return i
        : L(n, i + 1)         // Otherwise increment i and recurse
;


答:
Perl 6, 10 bytes

{[lcm] @_}
```

<p>basically the same as:</p>

<pre class="lang-perl6 prettyprint-override"><code>sub ( *@_ ) { @_.reduce: &infix:< lcm > }
</code>```

Title: Least Common Multiple

Body:
The least common multiple of a set of positive integers A is the smallest postive integer B such that, for each k in A, there exists a positive integer n such that k*n = B.

Given at least two positive integers as input, output their least common multiple.

Rules

Builtins are allowed, but if your solution uses one, you are encouraged to include an alternate solution that does not use GCD/LCM builtins. However, the alternate solution will not count towards your score at all, so it is entirely optional.

All inputs and outputs will be within the natively-representable range for your language. If your language is natively capable of arbitrarily-large integers, then your solution must work with arbitrarily large inputs and outputs.

Test cases

```<code>[7, 2] -> 14
[8, 1] -> 8
[6, 4, 8] -> 24
[8, 2, 1, 10] -> 40
[9, 6, 2, 1, 5] -> 90
[5, 5, 7, 1, 1] -> 35
[4, 13, 8, 8, 11, 1] -> 1144
[7, 2, 2, 11, 11, 8, 5] -> 3080
[1, 6, 10, 3, 4, 10, 7] -> 420
[5, 2, 9, 10, 3, 4, 4, 4, 7] -> 1260
[9, 7, 10, 9, 7, 8, 5, 10, 1] -> 2520
</code>```

Body:
Perl 6, 10 bytes

{[lcm] @_}

basically the same as:

sub ( *@_ ) { @_.reduce: &infix:< lcm > }


问:
Make your language unusable
Try to write some code in your language and make it not satisfying our criteria of being a programming language any more.

A language satisfies our criteria (simplified version for this challenge) of being a programming language if:

It can read user input representing tuples of positive integers in some way.

It can output at least two different possible results depending on the input.

It can take two positive integers and add them (and the result can affect the output).

It can take a positive integer and decide whether it is a prime (and the result can affect the output).

For the purpose of this challenge, any kind of output that isn't an allowed output method for a normal challenge is ignored. So it doesn't matter whether the program can also play a piece of music, or posting via HTTP, etc.

Update: You can also choose one or some of the allowed output methods, and ignore all the others. But you must use the same definition everywhere in the following criteria. And if your program can disable more than one output methods — that worths more upvotes.

Examples like making it not able to output, or disabling all the loop constructs so it won't be able to do primality test and making sure the user cannot re-enable them.

You should leave a place for inserting new code. By default, it is at the end of your code. If we consider putting the source code in that place in your answer and running the full code as a complete program the interpreter of a new language, that language should not satisfy the criteria.

But the inserted code must be executed in such a way like a language satisfying the criteria:

The inserted code must be grammatically the same as something (say it's a code block in the following criteria) that generally do satisfy the criteria, from the perspective of whoever wants to write a syntax highlighter. So it cannot be in a string, comment, etc.

The inserted code must be actually executed, in a way it is supposed to satisfy the criteria. So it cannot be in an unused function or sizeof in C, you cannot just execute only a non-functional part in the code, and you cannot put it after an infinite loop, etc.

You can't limit the number of possible grammatically correct programs generated this way. If there is already something like a length limit in the language you are using, it shouldn't satisfy the criteria even if this limit is removed.

You can't modify or "use up" the content of input / output, but you can prevent them from being accessed.

These criteria usually only applies to languages without explicit I/O:

Your code should redirect the user input (that contains informations of arbitrary length) to the inserted code, if a code block isn't usually able to get the user input directly / explicitly in the language you are using.

Your code should print the returned value of the inserted code, if a code block isn't usually able to output things directly / explicitly in the language you are using.

In case you print the returned value, and it is typed in the language you are using, the returned type should be able to have 2 different practically possible values. For example, you cannot use the type struct {} or struct {private:int x;} in C++.

This is popularity-contest. The highest voted valid answer (so nobody spotted an error or all errors are fixed) wins.

Clarifications

You shouldn't modify the code in the text form, but can change the syntax before the code is interpreted or compiled.

You can do other things while the code is running. But the reason that it doesn't satisfy the criteria should be within the inserted code itself. It can error because of the interference of another thread, but not just be killed by another thread.

All the specs basically means it should be grammatically likely satisfying the criteria if all the built-ins were not changed but not actually do. It's fine if you find any non-grammatical workarounds, such as passing the parameters to the code block correctly, but make them not able to be used in some way.

Again, the inserted code must be actually executed. Code after an infinite loop or crashing is considered "not actually executed", thus not valid. Those answers might be interesting, but there are already some other infinite loop or crashing questions on this site, and you may find a more appropriate one to answer. If not, consider asking a new question. Examples of those questions are:

Shortest infinite loop producing no output

Why isn't it ending?

Loop without 'looping'

Challenge: Write a piece of code that quits itself

Ridiculous Runtime Errors

Crash your favorite compiler

Leaderboard

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

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

Leaderboard

	Author	Language	Score

Sorted by Language

	Language	User	Score

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

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

```

答:
Go

I did it! I really finally did it! I've been stewing on this problem for months but I finally have a definitive solution that I challenge anyone to crack!

```<code>package main

import (
    . "runtime"
    . "os"
)

func main() {
    const (
        Chmod = iota
        Chtimes
        Create
        Exit
        File
        FindProcess
        Lchown
        Link
        Mkdir
        MkdirAll
        NewFile
        Open
        OpenFile
        Process
        Remove
        RemoveAll
        Rename
        Setenv
        StartProcess
        Symlink
        TempDir
        Truncate
        Unsetenv
    )
    Stdout.Close()
    Stdin.Close()
    Stderr.Close()
    defer func() {
        go func() {
            // User code here
        }()
    }()
    Goexit()
}
</code>```

My definitive reddit post on this problem for Go.

But now, I have a solution. By forcing the user's code to execute in a goroutine, and then terminating the main goroutine with runtime.Goexit, the user can no longer set the exit code. If they panic the program crashes, yes, but if they don't then it also crashes, per the documentation of Goexit:

Calling Goexit from the main goroutine terminates that goroutine without func main returning. Since func main has not returned, the program continues execution of other goroutines. If all other goroutines exit, the program crashes.

Title: Make your language unusable

Body:
Go

I did it! I really finally did it! I've been stewing on this problem for months but I finally have a definitive solution that I challenge anyone to crack!

package main

import (
    . "runtime"
    . "os"
)

func main() {
    const (
        Chmod = iota
        Chtimes
        Create
        Exit
        File
        FindProcess
        Lchown
        Link
        Mkdir
        MkdirAll
        NewFile
        Open
        OpenFile
        Process
        Remove
        RemoveAll
        Rename
        Setenv
        StartProcess
        Symlink
        TempDir
        Truncate
        Unsetenv
    )
    Stdout.Close()
    Stdin.Close()
    Stderr.Close()
    defer func() {
        go func() {
            // User code here
        }()
    }()
    Goexit()
}

My definitive reddit post on this problem for Go.

But now, I have a solution. By forcing the user's code to execute in a goroutine, and then terminating the main goroutine with runtime.Goexit, the user can no longer set the exit code. If they panic the program crashes, yes, but if they don't then it also crashes, per the documentation of Goexit:

Calling Goexit from the main goroutine terminates that goroutine without func main returning. Since func main has not returned, the program continues execution of other goroutines. If all other goroutines exit, the program crashes.


Title: Least Common Multiple

Body:
Mathematica, 3 bytes

LCM

Usage:

In[1]:= LCM[9, 7, 10, 9, 7, 8, 5, 10, 1]

Out[1]= 2520


答:
Cheddar, 17 bytes

```<code>n f->(|>n).map(f)
</code>```

Short recursion + Short range + Short iteration = A challenge where cheddar does very well

Non-competing, 11 bytes

```<code>n f->|>n=>f
</code>```

The => operator was added after this challenge was released making this answer non-competing.

This may look confusing but let me simplify it:

```<code>n f -> |> n => f
</code>```

basically n is the input and f is the function itself. |>n generates [0, n) and => maps that over f.

Title: Natural construction

Body:
Cheddar, 17 bytes

n f->(|>n).map(f)

Short recursion + Short range + Short iteration = A challenge where cheddar does very well

Non-competing, 11 bytes

n f->|>n=>f

The => operator was added after this challenge was released making this answer non-competing.

This may look confusing but let me simplify it:

n f -> |> n => f

basically n is the input and f is the function itself. |>n generates [0, n) and => maps that over f.


答:
Mathematica, 31 bytes

Straightforwardly implements the definition as a nested list. Uses an unnamed function that recursively calls itself using #0.

```<code>If[#<1,{},Join[t=#0[#-1],{t}]]&
</code>```

Title: Natural construction

Body:
Mathematica, 31 bytes

Straightforwardly implements the definition as a nested list. Uses an unnamed function that recursively calls itself using #0.

If[#<1,{},Join[t=#0[#-1],{t}]]&


答:
Actually, <s>12</s> 1 byte

Golfing suggestions are still welcome, though I'm not sure how to improve on the raw LCM built-in. Try it online!

```<code>▲
</code>```

A 12-byte version without the built-in. Golfing suggestions welcome. Try it online!

```<code>╗2`╜@♀%ΣY`╓N
</code>```

Ungolfing

```<code>          Implicit input array.
╗         Save array in register 0.
2`...`╓   Starting with f(0), find the first (two) x where f(x) returns a truthy value.
          These two values will be 0 and our LCM.
  ╜         Push array from register 0.
  @         Swap the top two values. Stack: x, array
  ♀%        Map % over x and array, returning (x % item) for each item in array.
  ΣY        If the sum of all the modulos equals 0, x is either 0 or our LCM.

N         Push the last (second) value of our results. This is our LCM.
          Implicit return.
</code>```

Title: Least Common Multiple

Body:
Actually, <s>12</s> 1 byte

Golfing suggestions are still welcome, though I'm not sure how to improve on the raw LCM built-in. Try it online!

▲

A 12-byte version without the built-in. Golfing suggestions welcome. Try it online!

╗2`╜@♀%ΣY`╓N

Ungolfing

          Implicit input array.
╗         Save array in register 0.
2`...`╓   Starting with f(0), find the first (two) x where f(x) returns a truthy value.
          These two values will be 0 and our LCM.
  ╜         Push array from register 0.
  @         Swap the top two values. Stack: x, array
  ♀%        Map % over x and array, returning (x % item) for each item in array.
  ΣY        If the sum of all the modulos equals 0, x is either 0 or our LCM.

N         Push the last (second) value of our results. This is our LCM.
          Implicit return.


答:
PHP, <s>42</s> 74 bytes

```<code>for(;($p=++$f*$argv[1])%$argv[2];);echo$p;
</code>```

straight forward:

loop $f from 1 upwards; if $f*$a divides through $b without a remainder, the LCM is found.

I totally had overread the at least ... here´s the code for any number of parameters:

```<code>for(;$i<$argc;)for($p=$argv[$i=1]*++$f;++$i<$argc&$p%$argv[$i]<1;);echo$p;
</code>```

Loop $f from 1 upwards while inner loop has not run to $argc.

Loop $i from 2 to $argc-1 while $f*$argv[1] divides through $argv[$i] without a remainder.

both loops broken: print $f*$argument 1.

Title: Least Common Multiple

Body:
PHP, <s>42</s> 74 bytes

for(;($p=++$f*$argv[1])%$argv[2];);echo$p;

straight forward:

loop $f from 1 upwards; if $f*$a divides through $b without a remainder, the LCM is found.

I totally had overread the at least ... here´s the code for any number of parameters:

for(;$i<$argc;)for($p=$argv[$i=1]*++$f;++$i<$argc&$p%$argv[$i]<1;);echo$p;

Loop $f from 1 upwards while inner loop has not run to $argc.

Loop $i from 2 to $argc-1 while $f*$argv[1] divides through $argv[$i] without a remainder.

both loops broken: print $f*$argument 1.


问:
Interpret loose ranges

Interpret loose ranges

ListSharp is an interpreted programming language that has many features, one of those features is a 1 index based range creator that works like this:

You define a range as (INT) TO (INT) or just (INT) where both or the single int can go from min to max int32 value

Then you can use those ranges to extract elements of an array without fearing to overstep it's boundaries

therefore:

1 TO 5 generates: {1,2,3,4,5}

3 generates: {3}

Ranges can be added up using the AND operator

1 TO 5 AND 3 TO 6 generates: {1,2,3,4,5,3,4,5,6}

remember this works with negative numbers as well

3 TO -3 generates: {3,2,1,0,-1,-2,-3}

The challenge is the following:

Input

A character array and the previously defined range clause as a string

Output

The elements at the 1 index based locations of the range (non existing/negative indexes translate to an empty character)

How to win

As a code-golf challenge you are supposed to create the program with the shortest byte count to win

It has been pointed out empty characters do not exist, therefore you should be ignoring them (I only showed them here to make it easier to understand yet it confused people)

Test cases:

```<code>input array is:
{'H','e','l','l','o',' ','W','o','r','l','d'}

range clause:
"1 TO 3" => "Hel"
"5" => "o"
"-10 TO 10" => "Hello Worl"
"0 AND 2 AND 4" => "el"
"8 TO 3" => "oW oll"
"-300 AND 300" => ""
"1 TO 3 AND 3 TO 1" => "HelleH"
"-20 TO 0 AND 1 AND 4" => "Hl"
</code>```

答:
Perl - 110 bytes

Calling the script in the command line with the string as the first argument, and the range as the second.

```<code>for(split AND,pop@ARGV){$_>0?print+(split//,"@ARGV")[$_-1]:0for(/(.+)TO(.+)/?($1>$2?reverse$2..$1:$1..$2):$_)}
</code>```

De-obfuscated :

```<code>for $subrange (split 'AND', $ARGV[1]) {
    for $index ($subrange =~ /(.+)TO(.+)/
        ? ($1 > $2 ? reverse $2..$1 : $1..$2) # All indices of that range
        : $subrange) # Otherwise, an index only
    {
        if ($index > 0) {
            # Here, 'split' returns an array of all characters
            print((split //, $ARGV[0])[$index - 1]);
        }
    }
}
</code>```

Title: Interpret loose ranges

Body:
Perl - 110 bytes

Calling the script in the command line with the string as the first argument, and the range as the second.

for(split AND,pop@ARGV){$_>0?print+(split//,"@ARGV")[$_-1]:0for(/(.+)TO(.+)/?($1>$2?reverse$2..$1:$1..$2):$_)}

De-obfuscated :

for $subrange (split 'AND', $ARGV[1]) {
    for $index ($subrange =~ /(.+)TO(.+)/
        ? ($1 > $2 ? reverse $2..$1 : $1..$2) # All indices of that range
        : $subrange) # Otherwise, an index only
    {
        if ($index > 0) {
            # Here, 'split' returns an array of all characters
            print((split //, $ARGV[0])[$index - 1]);
        }
    }
}


问:
Triangular Square Numbers
Square numbers are those that take the form of \$n^2\$ where \$n\$ is an integer. These are also called perfect squares, because when you take their square root you get an integer.

The first 10 square numbers are: (OEIS)

0, 1, 4, 9, 16, 25, 36, 49, 64, 81

Triangular numbers are numbers that can form an equilateral triangle. The n-th triangle number is equal to the sum of all natural numbers from 1 to n.

The first 10 triangular numbers are: (OEIS)

0, 1, 3, 6, 10, 15, 21, 28, 36, 45

Square triangular numbers are numbers that are both square and triangular.

The first 10 square triangular numbers are: (OEIS)

0, 1, 36, 1225, 41616, 1413721, 48024900, 1631432881, 55420693056, 1882672131025, 63955431761796

There is an infinite number of square numbers, triangle numbers, and square triangular numbers.

Write a program or named function that given an input (parameter or stdin) number \$n\$, calculates the \$n\$th square triangular number and outputs/returns it, where n is a positive nonzero number. (For \$n=1\$ return 0)

For the program/function to be a valid submission it should be able to return at least all square triangle numbers smaller than \$2^{31}-1\$.

Bonus

-4 bytes for being able to output all square triangular numbers less than 2^63-1

-4 bytes for being able to theoretically output square triangular numbers of any size.

<s>+8 byte penalty for solutions that take nonpolynomial time.</s>

Bonuses stack.

This is code-golf challenge, so the answer with the fewest bytes wins.

答:
PHP, <s>65</s> <s>59</s> 56-4=52 bytes

```<code>while($argv[1]--)while((0|$r=sqrt($s+=$f++))-$r);echo$s;
</code>```

repeat until square root of $s is ∈ℤ: add $f to sum $s, increment $f;

repeat $argv[1] times.

output sum.

ContentLicense: CC BY-SA 4.0

Title: Triangular Square Numbers

Body:
PHP, <s>65</s> <s>59</s> 56-4=52 bytes

while($argv[1]--)while((0|$r=sqrt($s+=$f++))-$r);echo$s;

repeat until square root of $s is ∈ℤ: add $f to sum $s, increment $f;

repeat $argv[1] times.

output sum.


问:
Find the occurrences of a character in an input string

Challenge

Write a program that, given a string x which is 10 characters long and a character y, outputs the number of times character y occurs in string x.

The shortest program in bytes to do so wins.

Example

```<code>Input: tttggloyoi, t
Output: 3
</code>```

```<code>Input: onomatopoe, o
Output: 4
</code>```

答:
Jelly, 1 byte

```<code>ċ
</code>```

TryItOnline

The obvious implementation would be 3 bytes: s1ċ, which splits a string or list (left argument) into slices of length 1 with s1 and counts occurrences of the character (right argument) with ċ.

However, since the character will only ever be of length 1, we could, instead, inspect all non-empty contiguous slices of a string with Ẇ; the character will only ever match those slices that are of length 1.

...and since a string is an array of characters, the function can just be ċ.

Body:
Jelly, 1 byte

ċ

TryItOnline

The obvious implementation would be 3 bytes: s1ċ, which splits a string or list (left argument) into slices of length 1 with s1 and counts occurrences of the character (right argument) with ċ.

However, since the character will only ever be of length 1, we could, instead, inspect all non-empty contiguous slices of a string with Ẇ; the character will only ever match those slices that are of length 1.

...and since a string is an array of characters, the function can just be ċ.


问:
Now I know my ABCs, won't you come and golf with me?
Write a program or function that outputs this exact text, case-insensitive:

```<code>A, B, C, D, E, F, G,
H, I, J, K, L, M, N, O, P,
Q, R, S,
T, U, V,
W, X, Y, Z.
</code>```

(Based on the alphabet song that many American kids learn to help memorize the alphabet, though edited for more compressibility.)

The output must look exactly the same as the above (again, case-insensitive), but may contain trailing spaces on each line and/or trailing newlines. Notice the period at the end.

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

答:
///, 62 bytes

```<code>/c/, /AcBcCcDcEcFcG,
HcIcJcKcLcMcNcOcP,
QcRcS,
TcUcV,
WcXcYcZ.
</code>```

Try it online!

Not much to golf here, but I reduced it from 77 bytes to 62 just by replacing ,  with c.

Body:
///, 62 bytes

/c/, /AcBcCcDcEcFcG,
HcIcJcKcLcMcNcOcP,
QcRcS,
TcUcV,
WcXcYcZ.

Try it online!

Not much to golf here, but I reduced it from 77 bytes to 62 just by replacing ,  with c.


答:
C, 68 bytes

This was a fun challenge with C

main(o,k){o==1?k=0:0;k<9e9&&k>=0&&main(34*o-k+2,o,printf("%d,",k));}

Watch it run here: https://ideone.com/0ulGmM

Title: Triangular Square Numbers

Body:
Square numbers are those that take the form of \$n^2\$ where \$n\$ is an integer. These are also called perfect squares, because when you take their square root you get an integer.

The first 10 square numbers are: (OEIS)

0, 1, 4, 9, 16, 25, 36, 49, 64, 81

Triangular numbers are numbers that can form an equilateral triangle. The n-th triangle number is equal to the sum of all natural numbers from 1 to n.

The first 10 triangular numbers are: (OEIS)

0, 1, 3, 6, 10, 15, 21, 28, 36, 45

Square triangular numbers are numbers that are both square and triangular.

The first 10 square triangular numbers are: (OEIS)

0, 1, 36, 1225, 41616, 1413721, 48024900, 1631432881, 55420693056, 1882672131025, 63955431761796

There is an infinite number of square numbers, triangle numbers, and square triangular numbers.

Write a program or named function that given an input (parameter or stdin) number \$n\$, calculates the \$n\$th square triangular number and outputs/returns it, where n is a positive nonzero number. (For \$n=1\$ return 0)

For the program/function to be a valid submission it should be able to return at least all square triangle numbers smaller than \$2^{31}-1\$.

Bonus

-4 bytes for being able to output all square triangular numbers less than 2^63-1

-4 bytes for being able to theoretically output square triangular numbers of any size.

<s>+8 byte penalty for solutions that take nonpolynomial time.</s>

Bonuses stack.

This is code-golf challenge, so the answer with the fewest bytes wins.


问:
Priority to the right
Your task is to regulate traffic on a crossroads. There are 4 roads coming from north, east, south and west.

The input is a string representing the upcoming traffic on each road. For example, NNNWS indicates there is a total of 5 cars: three at the north, one at the west and one at the south. The order of characters has no importance here, NNNWS is equivalent to WNNSN.

You must output the order in which the cars should go, using the priority to the right rule: cars coming from the south must let cars coming from east go first, east gives way to north, north gives way to west and west gives way to south.

For example, with the input NNNWS, the south car should go first, then the west car, then the 3 north cars. The output should thus be SWNNN.

There are some indecidable cases, for example NS or NNWSE : you should then output the string stuck.

Test cases

```<code>N => N
NW => WN
NWS => SWN
SNW => SWN
SSSSS => SSSSS
ENNNNES => NNNNEES
NS => stuck
NNWSE => stuck
</code>```

答:
Perl, 65 bytes

Includes +2 for -lp

Give input on STDIN. Assumes the empty string is not a valid input

```<code>#!/usr/bin/perl -lp
s%.%'+(y/NESW/ESWN/*s/N(.*)W/W$1N/,/N/^/S/)'x4%gere+0or$_=stuck
</code>```

If you don't mind the absence of a newline after stuck you can drop the l option

Title: Priority to the right

Body:
Perl, 65 bytes

Includes +2 for -lp

Give input on STDIN. Assumes the empty string is not a valid input

#!/usr/bin/perl -lp
s%.%'+(y/NESW/ESWN/*s/N(.*)W/W$1N/,/N/^/S/)'x4%gere+0or$_=stuck

If you don't mind the absence of a newline after stuck you can drop the l option


答:
Python 2, 146 bytes

lambda s,a:[a[i]for x in[map(int,c.split('TO'))for c in s.split('AND')]for i in range(x[0]-1,x[-1]-2*(x[-1]<x[0]),1-2*(x[-1]<x[0]))if 0<=i<len(a)]
```

All tests are at ideone

Splits the clause, s, on "AND", splits each of the resulting sub-clauses on "TO", converts the resulting strings to int using map. The results will each have either 1 or 2 items (1 if no "TO" was present in the sub-clause).

Constructs 0-based ranges for each of these using the step parameter of range as 1 or -1 by inspection of the values at indexes 0 and -1 (a list with one entry has that entry at both indexes).

Runs through these ranges and constructs a list of the output, if the indexes provided are in-range (if 0<=i<len(a)).

Title: Interpret loose ranges

Body:
Interpret loose ranges

ListSharp is an interpreted programming language that has many features, one of those features is a 1 index based range creator that works like this:

You define a range as (INT) TO (INT) or just (INT) where both or the single int can go from min to max int32 value

Then you can use those ranges to extract elements of an array without fearing to overstep it's boundaries

therefore:

1 TO 5 generates: {1,2,3,4,5}

3 generates: {3}

Ranges can be added up using the AND operator

1 TO 5 AND 3 TO 6 generates: {1,2,3,4,5,3,4,5,6}

remember this works with negative numbers as well

3 TO -3 generates: {3,2,1,0,-1,-2,-3}

The challenge is the following:

Input

A character array and the previously defined range clause as a string

Output

The elements at the 1 index based locations of the range (non existing/negative indexes translate to an empty character)

How to win

As a code-golf challenge you are supposed to create the program with the shortest byte count to win

It has been pointed out empty characters do not exist, therefore you should be ignoring them (I only showed them here to make it easier to understand yet it confused people)

Test cases:

```<code>input array is:
{'H','e','l','l','o',' ','W','o','r','l','d'}

range clause:
"1 TO 3" => "Hel"
"5" => "o"
"-10 TO 10" => "Hello Worl"
"0 AND 2 AND 4" => "el"
"8 TO 3" => "oW oll"
"-300 AND 300" => ""
"1 TO 3 AND 3 TO 1" => "HelleH"
"-20 TO 0 AND 1 AND 4" => "Hl"
</code>```

Body:
Python 2, 146 bytes

lambda s,a:[a[i]for x in[map(int,c.split('TO'))for c in s.split('AND')]for i in range(x[0]-1,x[-1]-2*(x[-1]<x[0]),1-2*(x[-1]<x[0]))if 0<=i<len(a)]

All tests are at ideone

Splits the clause, s, on "AND", splits each of the resulting sub-clauses on "TO", converts the resulting strings to int using map. The results will each have either 1 or 2 items (1 if no "TO" was present in the sub-clause).

Constructs 0-based ranges for each of these using the step parameter of range as 1 or -1 by inspection of the values at indexes 0 and -1 (a list with one entry has that entry at both indexes).

Runs through these ranges and constructs a list of the output, if the indexes provided are in-range (if 0<=i<len(a)).


问:
Help the architects visualize the skyline
As part of a city planning project, you've gotten the assignment of creating a program or function that will display the city skyline, given some input from the architects. The project is only in the startup phase, so a very rough sketch is sufficient. The easiest approach is of course to simply draw the skyline in ASCII-art.

All buildings will be by the river, thus they are all aligned. The architects will give the height of each building as input, and your code should display the skyline.

The input from the architects will either be an integer or a half-integer. If the number is an integer, the building will have a flat roof, while a half-integer will result in a pitched roof. A zero will just be flat ground. The walls of a building are 3 characters apart, while a zero will be a single character wide. Adjacent buildings share walls.

For details and clarifications regarding the output, please have a look at the examples below:

```<code>N = 3
 ___
|   |
|   |
|___|

N = 3.5
  _
 / \
|   |
|   |
|___|

N = 6
 ___
|   |
|   |
|   |
|   |
|   |
|___|

n = 0
_
</code>```

Example input: 3 3.5 0 2

```<code>      _
 ___ / \
|   |   |  ___
|   |   | |   |
|___|___|_|___|
</code>```

Example input: 0 0 2.5 3 0 4 1

```<code>             ___
    _  ___  |   |
   / \|   | |   |
  |   |   | |   |___
__|___|___|_|___|___|
</code>```

Louisville, 0 2 1 3.5 0 4 2 4 2 4 6 1 6 0 5 1

```<code>                                    ___     ___
                                   |   |   |   |  ___
           _    ___     ___     ___|   |   |   | |   |
          / \  |   |   |   |   |   |   |   |   | |   |
  ___    |   | |   |___|   |___|   |   |   |   | |   |
 |   |___|   | |   |   |   |   |   |   |___|   | |   |___
_|___|___|___|_|___|___|___|___|___|___|___|___|_|___|___|
</code>```

The ASCII-characters used are: newline, space, and /\_| (code points 10, 32, 47, 92, 95, 124).

Rules:

It's optional to make a program that only take integers as input, by multiplying all numbers by two. So, instead of taking 3 3.5 2, your program may take 6 7 4. If the second input format is chosen, an input of 6 should result in a 3 story building, 7 should be a 3 story building with pitched roofs etc.

The output should be exactly as described above, but trailing spaces and newlines are OK.

The exact format of the input is optional. Whatever is best in your language.

The result must be displayed on the screen, so that the architects can have a look at it.

You can assume there will be at least one integer given, and that only valid input will be given.

This is codegolf, so the shortest code in bytes win.

答:
PHP, <s>307</s> <s>297</s> 293 bytes

```<code><?$r=str_pad("",$p=((max($argv)+1)>>1)*$w=4*$argc,str_pad("\n",$w," ",0));for(;++$i<$argc&&$r[$p++]=_;$m=$n)if($n=$argv[$i]){$q=$p+=!$m;eval($x='$r[$q-1]=$r[$q]=$r[$q+1]=_;');for($h=$n>>1;$h--;$q-=$w)$r[$q-2]=$r[$q+2]="|";$n&1?($r[$q-1]="/")&($r[$q-$w]=_)&$r[$q+1]="\\":eval($x);$p+=3;}echo$r;
</code>```

Takes arguments*2 from command line. save to file, run with php <filename> <parameters>.

breakdown

```<code>// initialize result
$r=str_pad("",              // nested str_pad is 3 bytes shorter than a loop
    $p=                     // cursor=(max height-1)*(max width)=(start of last line)
    ((max($argv)+1)>>1)     // max height-1
    *
    $w=4*$argc              // we need at least 4*($argc-1)-1, +1 for newline
    ,
    // one line
    str_pad("\n",$w," ",0)  // (`str_pad("",$w-1)."\n"` is one byte shorter,
);                          // but requires `$w+1`)

// draw skyline
for(;
    ++$i<$argc              // loop through arguments
    &&$r[$p++]=_                // 0. draw empty ground and go one forward
    ;
    $m=$n                       // 7. remember value
)
    if($n=$argv[$i])            // if there is a house
    {
        $q=                         // 2. copy $p to $q
        $p+=!$m;                    // 1. go one forward if there was no house before this
        // offset all further positions by -2 (overwrite empty ground, share walls)
        eval($x=                    // 3. draw floor
        '$r[$q-1]=$r[$q]=$r[$q+1]=_;'
        );
        for($h=$n>>1;$h--;$q-=$w)   // 4. draw walls
            $r[$q-2]=$r[$q+2]="|";
        $n&1                        // 5. draw roof
            ?($r[$q-1]="/")&($r[$q-$w]=_)&$r[$q+1]="\\"
            :eval($x)               // (eval saved 7 bytes)
        ;                           // (ternary saved 6 bytes over `if`)
        $p+=3;                      // 6. go three forward (5-2)
    }

// output
echo$r;
</code>```

Body:
PHP, <s>307</s> <s>297</s> 293 bytes

<?$r=str_pad("",$p=((max($argv)+1)>>1)*$w=4*$argc,str_pad("\n",$w," ",0));for(;++$i<$argc&&$r[$p++]=_;$m=$n)if($n=$argv[$i]){$q=$p+=!$m;eval($x='$r[$q-1]=$r[$q]=$r[$q+1]=_;');for($h=$n>>1;$h--;$q-=$w)$r[$q-2]=$r[$q+2]="|";$n&1?($r[$q-1]="/")&($r[$q-$w]=_)&$r[$q+1]="\\":eval($x);$p+=3;}echo$r;

Takes arguments*2 from command line. save to file, run with php <filename> <parameters>.

breakdown

// initialize result
$r=str_pad("",              // nested str_pad is 3 bytes shorter than a loop
    $p=                     // cursor=(max height-1)*(max width)=(start of last line)
    ((max($argv)+1)>>1)     // max height-1
    *
    $w=4*$argc              // we need at least 4*($argc-1)-1, +1 for newline
    ,
    // one line
    str_pad("\n",$w," ",0)  // (`str_pad("",$w-1)."\n"` is one byte shorter,
);                          // but requires `$w+1`)

// draw skyline
for(;
    ++$i<$argc              // loop through arguments
    &&$r[$p++]=_                // 0. draw empty ground and go one forward
    ;
    $m=$n                       // 7. remember value
)
    if($n=$argv[$i])            // if there is a house
    {
        $q=                         // 2. copy $p to $q
        $p+=!$m;                    // 1. go one forward if there was no house before this
        // offset all further positions by -2 (overwrite empty ground, share walls)
        eval($x=                    // 3. draw floor
        '$r[$q-1]=$r[$q]=$r[$q+1]=_;'
        );
        for($h=$n>>1;$h--;$q-=$w)   // 4. draw walls
            $r[$q-2]=$r[$q+2]="|";
        $n&1                        // 5. draw roof
            ?($r[$q-1]="/")&($r[$q-$w]=_)&$r[$q+1]="\\"
            :eval($x)               // (eval saved 7 bytes)
        ;                           // (ternary saved 6 bytes over `if`)
        $p+=3;                      // 6. go three forward (5-2)
    }

// output
echo$r;


问:
The Woz Monitor

 Challenge

I've recently gotten into 8-bit computers and are fascinated with the workings of them and others alike; thus the objective of this code golf, is to replicate a portion of the Woz Monitor, designed by Steve Wozniak for the Apple I.

You are to store an array of 22 hexadecimal values with a width of two bytes, (min value $10, max value $FF), and then take in n-amount of inputs. (Normally two; languages like Brainfuck might have a hard time).

The inputs will refer to where in the array to start printing from, and where to stop; an input with defined behaviour will have their starting value less or equal to the ending value. Your program must then be capable of printing every hexadecimal value between, and including, the hexadecimals inputted.

An example of this:

```<code>Array
00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F 10 11 12 13 14 15

Values
FF F4 B6 D7 40 00 00 A4 F0 00 FF 0D 9C 21 65 C4 02 28 90 E7 D6 A5
</code>```

```<code>input first num:
04
input second num:
14
40 00 00 A4 F0 00 FF 0D 9C 21 65 C4 02 28 90 E7 D6
</code>```

Now the interesting part of this exercise, is that you can use whatever you want to check the bounds of the users input. Person inputs hello and your program has undefined behaviour? It quits without notice? They are both valid.

The only rules are:

1. You must include the values of the 22 hexadecimal values as part of your program before it starts, (can't ask the user for inputs).

2. The output of the hexadecimal values must follow the exact format:
    00 FF 00 FF 00 Trailing spaces, tabs or lines are OK. Characters are not.

3. The program doesn't have to ask for the inputs with a message. Leave the "message" blank if you wish. The user must input the hex-bounds however.

4. As with the values of the 22 hexadecimals are up to you to decide, you must make a program that actually fetches the values from storage, opposed to mimicking a program by simply printing values. (such as a list of $00's).

5. n-amount of inputs, refers to the amount of inputs required for your language of choice to recognise a hexadecimal of two byte-width. eg. (Brainfuck will require two inputs per hex, making it four for the two).

Feel free to comment if you need clarification.

This is code golf, so the shortest answer in the number of bytes is the winner.

 Leaderboard

Here is a leaderboard generating snippet courtesy of Martin Ender.

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

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

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

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

function answersUrl(e){return"http://api.stackexchange.com/2.2/questions/95080/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function getAnswers(){$.ajax({url:answersUrl(page++),method:"get",dataType:"jsonp",crossDomain:true,success:function(e){answers.push.apply(answers,e.items);if(e.has_more)getAnswers();else process()}})}function shouldHaveHeading(e){var t=false;var n=e.body_markdown.split("\n");try{t|=/^#/.test(e.body_markdown);t|=["-","="].indexOf(n[1][0])>-1;t&=LANGUAGE_REG.test(e.body_markdown)}catch(r){}return t}function shouldHaveScore(e){var t=false;try{t|=SIZE_REG.test(e.body_markdown.split("\n")[0])}catch(n){}return t}function getAuthorName(e){return e.owner.display_name}function process(){answers=answers.filter(shouldHaveScore).filter(shouldHaveHeading);answers.sort(function(e,t){var n=+(e.body_markdown.split("\n")[0].match(SIZE_REG)||[Infinity])[0],r=+(t.body_markdown.split("\n")[0].match(SIZE_REG)||[Infinity])[0];return n-r});var e={};var t=0,c=0,p=-1;answers.forEach(function(n){var r=n.body_markdown.split("\n")[0];var i=$("#answer-template").html();var s=r.match(NUMBER_REG)[0];var o=(r.match(SIZE_REG)||[0])[0];var u=r.match(LANGUAGE_REG)[1];var a=getAuthorName(n);t++;c=p==o?c:t;i=i.replace("{{PLACE}}",c+".").replace("{{NAME}}",a).replace("{{LANGUAGE}}",u).replace("{{SIZE}}",o).replace("{{LINK}}",n.share_link);i=$(i);p=o;$("#answers").append(i);e[u]=e[u]||{lang:u,user:a,size:o,link:n.share_link}});var n=[];for(var r in e)if(e.hasOwnProperty(r))n.push(e[r]);n.sort(function(e,t){if(e.lang>t.lang)return 1;if(e.lang<t.lang)return-1;return 0});for(var i=0;i<n.length;++i){var s=$("#language-template").html();var r=n[i];s=s.replace("{{LANGUAGE}}",r.lang).replace("{{NAME}}",r.user).replace("{{SIZE}}",r.size).replace("{{LINK}}",r.link);s=$(s);$("#languages").append(s)}}var QUESTION_ID=49042;var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";var answers=[],page=1;getAnswers();var SIZE_REG=/\d+(?=[^\d&]*(?:<(?:s>[^&]*<\/s>|[^&]+>)[^\d&]*)*$)/;var NUMBER_REG=/\d+/;var LANGUAGE_REG=/^#*\s*([^,]+)/```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}</code>```

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

Leaderboard

	AuthorLanguageSize

Winners by Language

LanguageUserScore

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

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

答:
Jelly, <s>24</s> 21 bytes

```<code>w@€ØHḅ⁴
ɠÇµɠÇr@b⁴ịØHK
</code>```

Chosen values: [00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 1F 10 11 12 13 14 15]

TryItOnline

If the second input is less than the first it outputs the reversed sequence.

Out of bounds behaviour is undefined (e.g. "foo", "14" returns 38 values, most of which are not even in the array and many of which are not length 2)

How?

```<code>w@€ØHḅ⁴ - Link 1, parse a string as a 1-based hex value e.g. "14"
w@€      - first index (1-based) of each character in
   ØH    - hex digits: "0123456789ABCDEF"                   [2,5]
     ḅ⁴ - convert from base 16                                 37

ɠÇµɠÇr@b⁴ịØHK - Main link
ɠ  ɠ          - read a line from stdin               e.g. "04"  "14"
 Ç  Ç         - call the last link (1) as a monad          21    37
  µ           - monadic chain separation
     r@       - inclusive range, with reversed arguments  [   21,   22,...,   36,   37]
       b⁴     - convert to base 16                        [[1,5],[1,6],...,[2,4],[2,5]]
         ị    - index into
          ØH  - hex digits: "0123456789ABCDEF"            [ "04", "05",..., "13", "14"]
            K - join with spaces
</code>```

Title: The Woz Monitor

Body:
Jelly, <s>24</s> 21 bytes

w@€ØHḅ⁴
ɠÇµɠÇr@b⁴ịØHK

Chosen values: [00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 1F 10 11 12 13 14 15]

TryItOnline

If the second input is less than the first it outputs the reversed sequence.

Out of bounds behaviour is undefined (e.g. "foo", "14" returns 38 values, most of which are not even in the array and many of which are not length 2)

How?

w@€ØHḅ⁴ - Link 1, parse a string as a 1-based hex value e.g. "14"
w@€      - first index (1-based) of each character in
   ØH    - hex digits: "0123456789ABCDEF"                   [2,5]
     ḅ⁴ - convert from base 16                                 37

ɠÇµɠÇr@b⁴ịØHK - Main link
ɠ  ɠ          - read a line from stdin               e.g. "04"  "14"
 Ç  Ç         - call the last link (1) as a monad          21    37
  µ           - monadic chain separation
     r@       - inclusive range, with reversed arguments  [   21,   22,...,   36,   37]
       b⁴     - convert to base 16                        [[1,5],[1,6],...,[2,4],[2,5]]
         ị    - index into
          ØH  - hex digits: "0123456789ABCDEF"            [ "04", "05",..., "13", "14"]
            K - join with spaces


答:
JavaScript (ES6), <s>107 152</s> 137 bytes

p=prompt,f=(a=+p(),b=+p(),[x,y,...s]='FFF4B6D7402011A4F0D0FF3D9C2165C4A22890E7D6A5')=>a?f(a-1,b-1,s):x+y+' '+(b?f(a,b-1,s):'');alert(f())
```

<p><div class="snippet" data-lang="js" data-hide="true" data-console="false" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var
   p=prompt,f=(a=+p(),b=+p(),[x,y,...s]='FFF4B6D7402011A4F0D0FF3D9C2165C4A22890E7D6A5')=>a?f(a-1,b-1,s):x+y+' '+(b?f(a,b-1,s):'');alert(f())
;

//input 0x04 then 0x14 will print 40 to D6
//input 0x00 then 0x00 will print FF
//input 0x13 then 0x17 will print E7 D6 A5 NaN NaN</code>```

Chosen values:

FF F4 B6 D7 40 20 11 A4 F0 D0 FF 3D 9C 21 65 C4 A2 28 90 E7 D6 A5
```

<p>Inputs:  </p>

<ul>
<li>Input format is <code>0x14</code></li>
<li>If any input is negative or the 1st input is greater than the 2nd : <code>InternalError: too much recursion</code></li>
<li>Will print <code>NaN</code> for out of bounds.</li>
</ul>

<hr/>

<p>Previous solutions:<br>
152 bytes:</p>

<pre class="lang-js prettyprint-override"><code>i=parseInt,p=prompt,f=(a=i(p()),b=i(p()),[x,y,...s]='FFF4B6D7402011A4F0D0FF3D9C2165C4A22890E7D6A5')=>a?f(a-1,b-1,s):x+y+' '+(b?f(a,b-1,s):'');alert(f())
</code>```

107 bytes, invalid solution (inputs missing):

f=(a,b,[x,y,...s]='FFF4B6D7402011A4F0D0FF3D9C2165C4A22890E7D6A5')=>a?f(a-1,b-1,s):x+y+' '+(b?f(a,b-1,s):'')
```

Title: The Woz Monitor

Body:
 Challenge

I've recently gotten into 8-bit computers and are fascinated with the workings of them and others alike; thus the objective of this code golf, is to replicate a portion of the Woz Monitor, designed by Steve Wozniak for the Apple I.

You are to store an array of 22 hexadecimal values with a width of two bytes, (min value $10, max value $FF), and then take in n-amount of inputs. (Normally two; languages like Brainfuck might have a hard time).

The inputs will refer to where in the array to start printing from, and where to stop; an input with defined behaviour will have their starting value less or equal to the ending value. Your program must then be capable of printing every hexadecimal value between, and including, the hexadecimals inputted.

An example of this:

```<code>Array
00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F 10 11 12 13 14 15

Values
FF F4 B6 D7 40 00 00 A4 F0 00 FF 0D 9C 21 65 C4 02 28 90 E7 D6 A5
</code>```

```<code>input first num:
04
input second num:
14
40 00 00 A4 F0 00 FF 0D 9C 21 65 C4 02 28 90 E7 D6
</code>```

Now the interesting part of this exercise, is that you can use whatever you want to check the bounds of the users input. Person inputs hello and your program has undefined behaviour? It quits without notice? They are both valid.

The only rules are:

1. You must include the values of the 22 hexadecimal values as part of your program before it starts, (can't ask the user for inputs).

2. The output of the hexadecimal values must follow the exact format:
    00 FF 00 FF 00 Trailing spaces, tabs or lines are OK. Characters are not.

3. The program doesn't have to ask for the inputs with a message. Leave the "message" blank if you wish. The user must input the hex-bounds however.

4. As with the values of the 22 hexadecimals are up to you to decide, you must make a program that actually fetches the values from storage, opposed to mimicking a program by simply printing values. (such as a list of $00's).

5. n-amount of inputs, refers to the amount of inputs required for your language of choice to recognise a hexadecimal of two byte-width. eg. (Brainfuck will require two inputs per hex, making it four for the two).

Feel free to comment if you need clarification.

This is code golf, so the shortest answer in the number of bytes is the winner.

 Leaderboard

Here is a leaderboard generating snippet courtesy of Martin Ender.

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

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

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

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

function answersUrl(e){return"http://api.stackexchange.com/2.2/questions/95080/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function getAnswers(){$.ajax({url:answersUrl(page++),method:"get",dataType:"jsonp",crossDomain:true,success:function(e){answers.push.apply(answers,e.items);if(e.has_more)getAnswers();else process()}})}function shouldHaveHeading(e){var t=false;var n=e.body_markdown.split("\n");try{t|=/^#/.test(e.body_markdown);t|=["-","="].indexOf(n[1][0])>-1;t&=LANGUAGE_REG.test(e.body_markdown)}catch(r){}return t}function shouldHaveScore(e){var t=false;try{t|=SIZE_REG.test(e.body_markdown.split("\n")[0])}catch(n){}return t}function getAuthorName(e){return e.owner.display_name}function process(){answers=answers.filter(shouldHaveScore).filter(shouldHaveHeading);answers.sort(function(e,t){var n=+(e.body_markdown.split("\n")[0].match(SIZE_REG)||[Infinity])[0],r=+(t.body_markdown.split("\n")[0].match(SIZE_REG)||[Infinity])[0];return n-r});var e={};var t=0,c=0,p=-1;answers.forEach(function(n){var r=n.body_markdown.split("\n")[0];var i=$("#answer-template").html();var s=r.match(NUMBER_REG)[0];var o=(r.match(SIZE_REG)||[0])[0];var u=r.match(LANGUAGE_REG)[1];var a=getAuthorName(n);t++;c=p==o?c:t;i=i.replace("{{PLACE}}",c+".").replace("{{NAME}}",a).replace("{{LANGUAGE}}",u).replace("{{SIZE}}",o).replace("{{LINK}}",n.share_link);i=$(i);p=o;$("#answers").append(i);e[u]=e[u]||{lang:u,user:a,size:o,link:n.share_link}});var n=[];for(var r in e)if(e.hasOwnProperty(r))n.push(e[r]);n.sort(function(e,t){if(e.lang>t.lang)return 1;if(e.lang<t.lang)return-1;return 0});for(var i=0;i<n.length;++i){var s=$("#language-template").html();var r=n[i];s=s.replace("{{LANGUAGE}}",r.lang).replace("{{NAME}}",r.user).replace("{{SIZE}}",r.size).replace("{{LINK}}",r.link);s=$(s);$("#languages").append(s)}}var QUESTION_ID=49042;var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";var answers=[],page=1;getAnswers();var SIZE_REG=/\d+(?=[^\d&]*(?:<(?:s>[^&]*<\/s>|[^&]+>)[^\d&]*)*$)/;var NUMBER_REG=/\d+/;var LANGUAGE_REG=/^#*\s*([^,]+)/```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}</code>```

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

Leaderboard

	AuthorLanguageSize

Winners by Language

LanguageUserScore

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

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

Body:
JavaScript (ES6), <s>107 152</s> 137 bytes

p=prompt,f=(a=+p(),b=+p(),[x,y,...s]='FFF4B6D7402011A4F0D0FF3D9C2165C4A22890E7D6A5')=>a?f(a-1,b-1,s):x+y+' '+(b?f(a,b-1,s):'');alert(f())

var
   p=prompt,f=(a=+p(),b=+p(),[x,y,...s]='FFF4B6D7402011A4F0D0FF3D9C2165C4A22890E7D6A5')=>a?f(a-1,b-1,s):x+y+' '+(b?f(a,b-1,s):'');alert(f())
;

//input 0x04 then 0x14 will print 40 to D6
//input 0x00 then 0x00 will print FF
//input 0x13 then 0x17 will print E7 D6 A5 NaN NaN

Chosen values:

FF F4 B6 D7 40 20 11 A4 F0 D0 FF 3D 9C 21 65 C4 A2 28 90 E7 D6 A5

Inputs:

Input format is 0x14

If any input is negative or the 1st input is greater than the 2nd : InternalError: too much recursion

Will print NaN for out of bounds.

Previous solutions:

152 bytes:

i=parseInt,p=prompt,f=(a=i(p()),b=i(p()),[x,y,...s]='FFF4B6D7402011A4F0D0FF3D9C2165C4A22890E7D6A5')=>a?f(a-1,b-1,s):x+y+' '+(b?f(a,b-1,s):'');alert(f())

107 bytes, invalid solution (inputs missing):

f=(a,b,[x,y,...s]='FFF4B6D7402011A4F0D0FF3D9C2165C4A22890E7D6A5')=>a?f(a-1,b-1,s):x+y+' '+(b?f(a,b-1,s):'')


答:
JavaScript (ES6), <s>118</s> <s>115</s> <s>112</s> <s>102</s> <s>82</s> 81 bytes

Saved 1 byte thanks to ETHproductions

Chosen values:

```<code>00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f 10 11 12 13 14 15
-----------------------------------------------------------------
10 10 11 14 10 10 15 15 11 14 10 10 15 15 11 14 10 10 15 15 10 11
</code>```

Prompts for the lower bound, then for the upper bound (e.g. 0x04 / 0x0f).

An invalid lower bound will be interpreted as 0x00 (minimum value).

An invalid upper bound will be interpreted as 0x15 (maximum value).

Outputs nothing if the lower bound is greater than the upper bound.

alert((1/7+'789').replace(/./g,(v,i)=>ib?'':(v|10)+' ',p=prompt,b=p(a=p())))```
</div>
</div>
</p>
<h3>Previous version (97 bytes)</h3>
<p>Generating a pseudo-random list of 'true' hexadecimal values:</p>
<pre class="lang-js prettyprint-override"><code>alert((1/7+'789').replace(/./g,(v,i)=>i<a|i>b?'':(v*7|16).toString(16)+' ',p=prompt,a=p(),b=p()))
</code>```

Sequence:

```<code>10 10 17 1c 1e 38 33 31 17 1c 1e 38 33 31 17 1c 1e 38 33 31 38 3f
</code>```

Title: The Woz Monitor

Body:
JavaScript (ES6), <s>118</s> <s>115</s> <s>112</s> <s>102</s> <s>82</s> 81 bytes

Saved 1 byte thanks to ETHproductions

Chosen values:

00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f 10 11 12 13 14 15
-----------------------------------------------------------------
10 10 11 14 10 10 15 15 11 14 10 10 15 15 11 14 10 10 15 15 10 11

Prompts for the lower bound, then for the upper bound (e.g. 0x04 / 0x0f).

An invalid lower bound will be interpreted as 0x00 (minimum value).

An invalid upper bound will be interpreted as 0x15 (maximum value).

Outputs nothing if the lower bound is greater than the upper bound.

alert((1/7+'789').replace(/./g,(v,i)=>i<a|i>b?'':(v|10)+' ',p=prompt,b=p(a=p())))

Previous version (97 bytes)

Generating a pseudo-random list of 'true' hexadecimal values:

alert((1/7+'789').replace(/./g,(v,i)=>i<a|i>b?'':(v*7|16).toString(16)+' ',p=prompt,a=p(),b=p()))

Sequence:

10 10 17 1c 1e 38 33 31 17 1c 1e 38 33 31 17 1c 1e 38 33 31 38 3f


问:
Multiple-Key Sorting
Given a list of indices and zero or more lists of integers, output the lists of integers, sorted in ascending order, with the key priority from the first input.

Example

Let the keys input be [1, 0, 2], and the lists input be [[5, 3, 4], [6, 2, 1], [5, 2, 1]]. Those lists need to be sorted by their second element, then first element, then third element, in ascending order:

First, we sort by the values at index 1: [[6, 2, 1], [5, 2, 1], [5, 3, 4]]

Next, we break any ties from the first sort using the values at index 0: [[5, 2, 1], [6, 2, 1], [5, 3, 4]]

Finally, we break any remaining ties with the vlues at index 2 (this doesn't actually change anything, because there are no ties remaining).

Details

Sorting is stable: if two elements compare equal with respect to the given sort keys, they must remain in the same relative order in the output. For example, if A and B are equal under the given sort keys, and the input was [..., A, ..., B, ...], A must be placed before B in the output.

A sort key will never reference a non-existant element in one of the input lists.

No sort key will be repeated. Thus, [1, 2, 1] is not a valid list of sort keys.

Any elements not referenced by the sort keys do not factor into the sorting order. Only the initial relative order and the values of the elements referenced by the sort keys determine the output order.

You may choose whether the sort keys are zero-indexed or one-indexed.

There will be no negative values in the sort keys. If you choose to use one-indexing, there will be no zeroes in the sort keys either.

Integer values will not exceed your language's natively-representable range. If your chosen language is natively capable of arbitrary-precision integers (like Python), then any integer value can be present in the input, subject to memory constraints.

Reference Implementation (Python 2)

#!/usr/bin/env python

keys = input()
lists = input()

print sorted(lists, key=lambda l:[l[x] for x in keys])
```
<p>Try it online</p>
<h2>Test Cases</h2>
<p>Format: <code>keys lists -> output</code>. All sort keys are zero-indexed.</p>
```[1, 0, 2] [[5, 3, 4], [6, 2, 1], [5, 2, 1]] -> [[5, 2, 1], [6, 2, 1], [5, 3, 4]]
[1, 2] [[5, 3, 4], [6, 2, 1], [5, 2, 1]] -> [[6, 2, 1], [5, 2, 1], [5, 3, 4]]
[0, 1] [[1, 2], [2, 1]] -> [[1, 2], [2, 1]]
[1, 0] [[1, 2], [2, 1]] -> [[2, 1], [1, 2]]
[0] [[4], [10, 11, -88], [-2, 7]] -> [[-2, 7], [4], [10, 11, -88]]
[2] [[-1, -5, 8, -1, -4, -10, -5, 4, 4, 6, -8, 4, 2], [-7, 6, 2, -8, -7, 7, -3, 3, 0, -6, 1], [-9, 8, -5, -1, -7, -8, -5, -6, 5, -6, 6]] -> [[-9, 8, -5, -1, -7, -8, -5, -6, 5, -6, 6], [-7, 6, 2, -8, -7, 7, -3, 3, 0, -6, 1], [-1, -5, 8, -1, -4, -10, -5, 4, 4, 6, -8, 4, 2]]
[2, 1] [[9, 2, -2, -10, -6], [3, -4, -2]] -> [[3, -4, -2], [9, 2, -2, -10, -6]]
[2, 4, 8] [[5, -3, 4, -6, -1, -2, -2, -4, 5], [-2, -3, 6, -4, -1, -4, -4, -5, 8, 9, 9, -3, 3, -9, -3], [2, 0, 10, -10, -1, 2, -1, 5, -1, 10, -5], [-7, -8, -6, 7, 3, 8, 6, -7, -2, 0, -6, -4, 4, -3, 2, -3]] -> [[-7, -8, -6, 7, 3, 8, 6, -7, -2, 0, -6, -4, 4, -3, 2, -3], [5, -3, 4, -6, -1, -2, -2, -4, 5], [-2, -3, 6, -4, -1, -4, -4, -5, 8, 9, 9, -3, 3, -9, -3], [2, 0, 10, -10, -1, 2, -1, 5, -1, 10, -5]]
[1, 2, 3, 4, 5] [[-7, 3, -8, 3, 5, -1, 6, -6, 9, 8], [-9, -1, -7, -9, -10, -2, -8, -10, -10, -3], [5, 3, -6, -5, -4, -4, -8, 2], [9, -4, 1, -1, -3, -2], [-6, -10, 4, -10, 6, 6, -1, 3, 0, 0], [1, -2, -7, -6, -7, -7, -1, 0, -4, 3, 3], [7, -1, -7, 2, -2, 9, 7, 5, -6, -8], [1, -5, -3, -10, -7, 9, -8, -5, -1], [-9, 4, -1, -1, 2, 4]] -> [[-6, -10, 4, -10, 6, 6, -1, 3, 0, 0], [1, -5, -3, -10, -7, 9, -8, -5, -1], [9, -4, 1, -1, -3, -2], [1, -2, -7, -6, -7, -7, -1, 0, -4, 3, 3], [-9, -1, -7, -9, -10, -2, -8, -10, -10, -3], [7, -1, -7, 2, -2, 9, 7, 5, -6, -8], [-7, 3, -8, 3, 5, -1, 6, -6, 9, 8], [5, 3, -6, -5, -4, -4, -8, 2], [-9, 4, -1, -1, 2, 4]]
[8, 7, 3, 2, 4, 9, 1] [[8, -5, 1, -6, -1, -4, 6, 10, 10, 6, 9, 5], [4, -8, 6, -10, -2, -3, 2, -6, 9, 5, 4, 10, 2, 3], [10, -1, 3, 0, -4, 1, -5, -4, -1, -7, 9, -9, -1, -5, 7, 8, 9, 6, -3], [0, -9, -7, -2, 2, -5, 7, 4, 6, -4, 1, 8, -7, 10], [5, 6, -9, 0, -1, 5, 4, 7, 5, 10, 2, 5, 7, -9]] -> [[10, -1, 3, 0, -4, 1, -5, -4, -1, -7, 9, -9, -1, -5, 7, 8, 9, 6, -3], [5, 6, -9, 0, -1, 5, 4, 7, 5, 10, 2, 5, 7, -9], [0, -9, -7, -2, 2, -5, 7, 4, 6, -4, 1, 8, -7, 10], [4, -8, 6, -10, -2, -3, 2, -6, 9, 5, 4, 10, 2, 3], [8, -5, 1, -6, -1, -4, 6, 10, 10, 6, 9, 5]]
```

答:
PHP, 139 Bytes

use the new spaceship operator and usort

```<code><?$a=$_GET[a];function c($x,$y,$i=0){$k=$_GET[k];return$x[$k[$i]]-$y[$k[$i]]?:($k[++$i]?c($x,$y,$i):0);}usort($a,c);echo json_encode($a);
</code>```

Instead of $x[$k[$i]]<=>$y[$k[$i]] you can use $x[$k[$i]]-$y[$k[$i]] under a PHP Version greater 7 - 2 Bytes

version with create an own index 197 Bytes like in a real library

```<code><?$m=min(array_map(min,$a=$_GET[a]));foreach($a as$p=>$v){$k="";foreach($s=$_GET[s]as$f){$k.=str_pad($v[$f]-$m,5,0,0);}$k.=str_pad($p,5,0,0);$r[$k]=$v;}ksort($r);echo json_encode(array_values($r));
</code>```

Title: Multiple-Key Sorting

Body:
PHP, 139 Bytes

use the new spaceship operator and usort

<?$a=$_GET[a];function c($x,$y,$i=0){$k=$_GET[k];return$x[$k[$i]]-$y[$k[$i]]?:($k[++$i]?c($x,$y,$i):0);}usort($a,c);echo json_encode($a);

Instead of $x[$k[$i]]<=>$y[$k[$i]] you can use $x[$k[$i]]-$y[$k[$i]] under a PHP Version greater 7 - 2 Bytes

version with create an own index 197 Bytes like in a real library

<?$m=min(array_map(min,$a=$_GET[a]));foreach($a as$p=>$v){$k="";foreach($s=$_GET[s]as$f){$k.=str_pad($v[$f]-$m,5,0,0);}$k.=str_pad($p,5,0,0);$r[$k]=$v;}ksort($r);echo json_encode(array_values($r));


答:
C, <s>176</s> <s>175</s> 161 bytes

1 byte save thanks to @JonathanAllan

Massive help thanks to @Downvoter for saving me 14 bytes!

```<code>int main(){int a[44]={0};char s[2];scanf("%s",s);int b=(int)strtol(s,0,16);scanf("%s",s);int c=(int)strtol(s,0,16);while(b<=c){printf("%d%d ",a[b],a[b+1]);b++;}}
</code>```

Try it online!

Chosen values: 00 for everything.

Un-golfed answer:

```<code>int main() {
    int a[44] = {0};
    char s[2];
    scanf("%s", s);
    int b = (int) strtol(s, 0, 16);
    scanf("%s", s);
    int c = (int) strtol(s, 0, 16);
    while (b <= c) {
        printf("%d%d ", a[b], a[b+1]);
        b++;
    }
}
</code>```

The trick to this, is taking in two inputs and attempting to convert them to hexadecimal strings and then cast to integers. Since there is no error-checking or anything likewise, undefined behaviour is simply throwing errors and breaking the program.
The user needs to enter two inputs, however my Eclipse CDT compiler seems to let me input them both on the same line with a space between.

They must be in the correct order, as requesting a bigger value before a smaller value will not run the while-loop at all.

The thing is, there is also no buffer-overflow protection, so I can simply request something absurd such as a range from $0 to $FFFF, and I will get everything in my computers memory from the beginning of the allocation of memory for the a[44] array, all the way to 65536 values later.

Title: The Woz Monitor

Body:
C, <s>176</s> <s>175</s> 161 bytes

1 byte save thanks to @JonathanAllan

Massive help thanks to @Downvoter for saving me 14 bytes!

int main(){int a[44]={0};char s[2];scanf("%s",s);int b=(int)strtol(s,0,16);scanf("%s",s);int c=(int)strtol(s,0,16);while(b<=c){printf("%d%d ",a[b],a[b+1]);b++;}}

Try it online!

Chosen values: 00 for everything.

Un-golfed answer:

int main() {
    int a[44] = {0};
    char s[2];
    scanf("%s", s);
    int b = (int) strtol(s, 0, 16);
    scanf("%s", s);
    int c = (int) strtol(s, 0, 16);
    while (b <= c) {
        printf("%d%d ", a[b], a[b+1]);
        b++;
    }
}

The trick to this, is taking in two inputs and attempting to convert them to hexadecimal strings and then cast to integers. Since there is no error-checking or anything likewise, undefined behaviour is simply throwing errors and breaking the program.
The user needs to enter two inputs, however my Eclipse CDT compiler seems to let me input them both on the same line with a space between.

They must be in the correct order, as requesting a bigger value before a smaller value will not run the while-loop at all.

The thing is, there is also no buffer-overflow protection, so I can simply request something absurd such as a range from $0 to $FFFF, and I will get everything in my computers memory from the beginning of the allocation of memory for the a[44] array, all the way to 65536 values later.


答:
Python, <s>88</s> <s>87</s> 86 bytes

1 byte save thanks to @JonathanAllan

1 byte save again to @JonathanAllan

Also changed the base of the code, much nicer now.

```<code>a,b=[int(x,16)for x in raw_input().split()];l=[0]*22
while a<=b:print"%02x"%l[a],;a+=1
</code>```

Chosen values: 00 for everything.

Same idea as my C answer. This time however, the code takes a single input from the user, requiring a space between both values, split them, cast them to hex values, and print every hex in the l array including and between the two inputted values. Since Python has a magnificent error-catching system, no buffer overflows are present and the code is therefore much more secure. The program is safe from undefined behaviour in a sense that it will not execute when a higher value is submitted before a lower value.

This should work on both Python 2.x and 3.x; Please correct me if I am wrong, as I don't have access to both interpreters due to my system not supporting both of them.

Title: The Woz Monitor

Body:
Python, <s>88</s> <s>87</s> 86 bytes

1 byte save thanks to @JonathanAllan

1 byte save again to @JonathanAllan

Also changed the base of the code, much nicer now.

a,b=[int(x,16)for x in raw_input().split()];l=[0]*22
while a<=b:print"%02x"%l[a],;a+=1

Chosen values: 00 for everything.

Same idea as my C answer. This time however, the code takes a single input from the user, requiring a space between both values, split them, cast them to hex values, and print every hex in the l array including and between the two inputted values. Since Python has a magnificent error-catching system, no buffer overflows are present and the code is therefore much more secure. The program is safe from undefined behaviour in a sense that it will not execute when a higher value is submitted before a lower value.

This should work on both Python 2.x and 3.x; Please correct me if I am wrong, as I don't have access to both interpreters due to my system not supporting both of them.


答:
Racket 173 bytes

```<code>(λ()(let((l(list 7 9 3 3 4))(s 65))(for((i 5))(define e(+ s(list-ref l i)))(for((j(range s e)))
(printf"~a~a "(integer->char j)(if(= j 90)"."",")))(printf"~n")(set! s e))))
</code>```

Ungolfed:

```<code>(define f
  (λ()
    (let ((l (list 7 9 3 3 4))
          (s 65))
      (for ((i 5))
        (define e (+ s (list-ref l i)))
        (for ((j (range s e)))
          (printf "~a~a " (integer->char j) (if(= j 90) "." ",")))
        (printf "~n")
        (set! s e)
        ))))
</code>```

Testing:

```<code>(f)
</code>```

Output:

```<code>A, B, C, D, E, F, G,
H, I, J, K, L, M, N, O, P,
Q, R, S,
T, U, V,
W, X, Y, Z.
</code>```

Title: Now I know my ABCs, won't you come and golf with me?

Body:
Write a program or function that outputs this exact text, case-insensitive:

```<code>A, B, C, D, E, F, G,
H, I, J, K, L, M, N, O, P,
Q, R, S,
T, U, V,
W, X, Y, Z.
</code>```

(Based on the alphabet song that many American kids learn to help memorize the alphabet, though edited for more compressibility.)

The output must look exactly the same as the above (again, case-insensitive), but may contain trailing spaces on each line and/or trailing newlines. Notice the period at the end.

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

Body:
Racket 173 bytes

(λ()(let((l(list 7 9 3 3 4))(s 65))(for((i 5))(define e(+ s(list-ref l i)))(for((j(range s e)))
(printf"~a~a "(integer->char j)(if(= j 90)"."",")))(printf"~n")(set! s e))))

Ungolfed:

(define f
  (λ()
    (let ((l (list 7 9 3 3 4))
          (s 65))
      (for ((i 5))
        (define e (+ s (list-ref l i)))
        (for ((j (range s e)))
          (printf "~a~a " (integer->char j) (if(= j 90) "." ",")))
        (printf "~n")
        (set! s e)
        ))))

Testing:

(f)

Output:

A, B, C, D, E, F, G,
H, I, J, K, L, M, N, O, P,
Q, R, S,
T, U, V,
W, X, Y, Z.


Title: The Woz Monitor

Body:
PHP, <s>106 105 104</s> 96+2 bytes

eval($s='for($a=a;$a++<c;)$$a=hexdec($argv[++$i]);while($b<=$c)printf("%02X ",ord($s[$b++]));');

or

eval($s='for($a=a;$a++<c;)$$a=hexdec($argv[++$i]);');while($b<=$c)printf("%02X ",ord($s[$b++]));

Run with php -nr '<code>' <lowindex> <highindex>; escape the single quotes in the code.

... or test it online.

dechex interpretes input as hexadecimal strings as far as characters are hex digits,

0 if the input starts with something else.

prints nothing if first value is larger than second.

chosen values:

00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f 10 11 12 13 14 15
-----------------------------------------------------------------
66 6F 72 28 24 61 3D 61 3B 24 61 2B 2B 3C 63 3B 29 24 24 61 3D 68

(first 22 ascii codes of the executed code)

or

for($a=a;$a++<c;)eval($s='$$a=hexdec($argv[++$i]);');while($b<=$c)printf("%02X ",ord($s[$b++]));

with these values:

00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f 10 11 12 13 14 15
-----------------------------------------------------------------
24 24 61 3D 68 65 78 64 65 63 28 24 61 72 67 76 5B 2B 2B 24 69 5D


答:
Haskell, 60 bytes

putStr$(['A'..'Y']>>= \x->x:", "++['\n'|elem x"GPSV"])++"Z."
```
<p>Try it on Ideone.</p>
<pre class="lang-haskell prettyprint-override"><code>putStr$(['A'..'Y']>>= \x->x:", "++['\n'|elem x"GPSV"])++"Z."
        ['A'..'Y']                                          --String "ABC...XY"
                      \x->x:", "++['\n'|elem x"GPSV"]       --function to append ", " and a "\n" when needed
       (          >>=                                )      --map function over the string and concat
                                                      ++"Z."--append "Z."
putStr$                                                     --print
</code>```

Body:
Haskell, 60 bytes

putStr$(['A'..'Y']>>= \x->x:", "++['\n'|elem x"GPSV"])++"Z."

Try it on Ideone.

putStr$(['A'..'Y']>>= \x->x:", "++['\n'|elem x"GPSV"])++"Z."
        ['A'..'Y']                                          --String "ABC...XY"
                      \x->x:", "++['\n'|elem x"GPSV"]       --function to append ", " and a "\n" when needed
       (          >>=                                )      --map function over the string and concat
                                                      ++"Z."--append "Z."
putStr$                                                     --print


答:
CJam, 31 bytes

```<code>'[,65>", "*7933Ab{3*/(\:+}%N*'.
</code>```

Explanation:

```<code>'[,65>                             push uppercase alphabet
      ", "*                        ", " between all letters
           7933Ab                  push [7 9 3 3]
                 {3*/(\:+}%        slices of lengths 21, 27, 9, 9
                           N*'.    join slices with newlines, add final "."
</code>```

Try it online

Body:
CJam, 31 bytes

'[,65>", "*7933Ab{3*/(\:+}%N*'.

Explanation:

'[,65>                             push uppercase alphabet
      ", "*                        ", " between all letters
           7933Ab                  push [7 9 3 3]
                 {3*/(\:+}%        slices of lengths 21, 27, 9, 9
                           N*'.    join slices with newlines, add final "."

Try it online


答:
Perl, 79 45 41 bytes

"min value $10" - the example has minimum of $00- is that a typo?

Here's a rather boring perl answer in 41 bytes (Was 46 and then I kept seeing spaces, parens I could elide). Takes input in two lines.

```<code>printf'%02X ',$_ for(4..26)[hex<>..hex<>]
</code>```

The data is a list 04..1A

Before I was being too clever with pack & unpack. Its input bytes are entered at once smushed together, eg "020E' will print the 2nd-14th entries

```<code>printf'%02X ',$_ for sub{(4..26)[shift..shift]}->(unpack'CC',pack'H4',<>)
</code>```

Might try golfing it more using all 0's, substr, and printf'%*vX' ... nope that is making my answer longer. 48 characters (using a string of ascii '7', hex 37 as the data)

```<code>printf'%*vX',' ',substr 7x22,$s=hex<>,1+hex<>-$s
</code>```

Title: The Woz Monitor

Body:
Perl, 79 45 41 bytes

"min value $10" - the example has minimum of $00- is that a typo?

Here's a rather boring perl answer in 41 bytes (Was 46 and then I kept seeing spaces, parens I could elide). Takes input in two lines.

printf'%02X ',$_ for(4..26)[hex<>..hex<>]

The data is a list 04..1A

Before I was being too clever with pack & unpack. Its input bytes are entered at once smushed together, eg "020E' will print the 2nd-14th entries

printf'%02X ',$_ for sub{(4..26)[shift..shift]}->(unpack'CC',pack'H4',<>)

Might try golfing it more using all 0's, substr, and printf'%*vX' ... nope that is making my answer longer. 48 characters (using a string of ascii '7', hex 37 as the data)

printf'%*vX',' ',substr 7x22,$s=hex<>,1+hex<>-$s


答:
R, <s>83</s> 71 bytes

a=rbind(LETTERS[-26],","," ");a[3,7+3*c(0,3:5)]="\n";cat(a,"Z.",sep="")
```

Try it online!

Makes a matrix of 3 rows (one with the letters, one with the commas and the other with either a space or a newline).

Edit: Thanks Billywob!

Body:
R, <s>83</s> 71 bytes

a=rbind(LETTERS[-26],","," ");a[3,7+3*c(0,3:5)]="\n";cat(a,"Z.",sep="")

Try it online!

Makes a matrix of 3 rows (one with the letters, one with the commas and the other with either a space or a newline).

Edit: Thanks Billywob!


答:
Ruby, <s>56</s> 54 bytes

```<code>$><<(?A..?Y).map{|c|c+('GPSV'[c]?",
":", ")}.join+"Z."
</code>```

The first line ends with a literal newline.

Edit: saved two bytes by replacing 'A'..'Y' with ?A..?Y.

Body:
Ruby, <s>56</s> 54 bytes

$><<(?A..?Y).map{|c|c+('GPSV'[c]?",
":", ")}.join+"Z."

The first line ends with a literal newline.

Edit: saved two bytes by replacing 'A'..'Y' with ?A..?Y.


问:
So sayeth the Shepherd
I'm tired, but I can't seem to fall asleep. Help me count sheep.

Given an input N (positive integer), make N sheep jump over an ascii fence, like the sample below. Only one frame should be displayed at once:

```<code>o |-|
──|-|──  0
</code>```

```<code> o|-|
──|-|──  0
</code>```

```<code>   o
  |-|
──|-|──  0
</code>```

```<code>  |-|o
──|-|──  0
</code>```

```<code>  |-| o
──|-|──  0
</code>```

```<code>o |-|
──|-|──  1
</code>```

```<code> o|-|
──|-|──  1
</code>```

```<code>   o
  |-|
──|-|──  1
</code>```

Count should be kept at the lower right side of the 'ground'. Trailing and leading whitespace and newlines are allowed. If your language of choice has difficulty clearing the screen for each frame you can add sufficient newlines to clear the screen - please state how many lines you add for this in your answer. The program should terminate when the N'th sheep is on the fifth floortile.

I need to get up early tomorrow, so shortest code in bytes wins. Please submit a function or complete program. Standard loopholes apply.

答:
JavaScript (ES6), <s>120</s> 124 bytes

f=(n,m=`   2
43|-|10
──|-|── `,s=0)=>n?alert(m.replace(s%5,'o').replace(/\d/g,' ')+' '+(n-1),(++s%5?f(n,m,s):f(n-1,m,0))):''
```
<p>The last frame computed is showing first.
Thanks to this the jump number is <code>n-1</code><br />
In <code>alert</code>, charaters have different width so it looks like it's broken.</p>
<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>f=(n,m=`   2
43|-|10
──|-|── `,s=0)=>n?alert(m.replace(s%5,'o').replace(/\d/g,' ')+' '+(n-1),(++s%5?f(n,m,s):f(n-1,m,0))):''
;

f(2);//You'll get 10 alert popup</code>```

Previous answer:

120 bytes, the jump number is wrong because it starts at 1 instead of 0

f=(n,m=`   2
43|-|10
──|-|── `,s=0)=>n?alert(m.replace(s%5,'o').replace(/\d/g,' ')+' '+n,(++s%5?f(n,m,s):f(n-1,m,0))):''
```

Title: So sayeth the Shepherd

Body:
JavaScript (ES6), <s>120</s> 124 bytes

f=(n,m=`   2
43|-|10
──|-|── `,s=0)=>n?alert(m.replace(s%5,'o').replace(/\d/g,' ')+' '+(n-1),(++s%5?f(n,m,s):f(n-1,m,0))):''

The last frame computed is showing first.
Thanks to this the jump number is n-1

In alert, charaters have different width so it looks like it's broken.

f=(n,m=`   2
43|-|10
──|-|── `,s=0)=>n?alert(m.replace(s%5,'o').replace(/\d/g,' ')+' '+(n-1),(++s%5?f(n,m,s):f(n-1,m,0))):''
;

f(2);//You'll get 10 alert popup

Previous answer:

120 bytes, the jump number is wrong because it starts at 1 instead of 0

f=(n,m=`   2
43|-|10
──|-|── `,s=0)=>n?alert(m.replace(s%5,'o').replace(/\d/g,' ')+' '+n,(++s%5?f(n,m,s):f(n-1,m,0))):''


答:
JavaScript (ES6), <s>144</s> 142 bytes

Clears the output and waits 300ms between each frame:

```<code>n=>(F=j=>((c=console).clear(),c.log(`   2
01|-|34
──|-|── `.replace(/\d/g,i=>(j-i)%5?' ':'o')+(j/5|0)),++j<n*5&&setTimeout(`F(${j})`,300)))(0)
</code>```

You can test it here (make sure to open the console).

Title: So sayeth the Shepherd

Body:
I'm tired, but I can't seem to fall asleep. Help me count sheep.

Given an input N (positive integer), make N sheep jump over an ascii fence, like the sample below. Only one frame should be displayed at once:

```<code>o |-|
──|-|──  0
</code>```

```<code> o|-|
──|-|──  0
</code>```

```<code>   o
  |-|
──|-|──  0
</code>```

```<code>  |-|o
──|-|──  0
</code>```

```<code>  |-| o
──|-|──  0
</code>```

```<code>o |-|
──|-|──  1
</code>```

```<code> o|-|
──|-|──  1
</code>```

```<code>   o
  |-|
──|-|──  1
</code>```

Count should be kept at the lower right side of the 'ground'. Trailing and leading whitespace and newlines are allowed. If your language of choice has difficulty clearing the screen for each frame you can add sufficient newlines to clear the screen - please state how many lines you add for this in your answer. The program should terminate when the N'th sheep is on the fifth floortile.

I need to get up early tomorrow, so shortest code in bytes wins. Please submit a function or complete program. Standard loopholes apply.

Body:
JavaScript (ES6), <s>144</s> 142 bytes

Clears the output and waits 300ms between each frame:

n=>(F=j=>((c=console).clear(),c.log(`   2
01|-|34
──|-|── `.replace(/\d/g,i=>(j-i)%5?' ':'o')+(j/5|0)),++j<n*5&&setTimeout(`F(${j})`,300)))(0)

You can test it here (make sure to open the console).


答:
05AB1E, <s>66</s> <s>60</s> 59 bytes

```<code>FNU5Fð4×N<i¨'oJ},N<iðë'o}ðNÉis}"|-|  "JN1›iR},…──|Â'-sððXJ,
</code>```

Uses CP-1252 encoding.

Explanantion

Iteration refers to the inner iteration (0 -> 4) of the sheeps journey.

Main loops

```<code>F      # For N in range [0 .. input)
 NU    # Save N in variable X
 5F    # For N in range [0 .. 5)
</code>```

Generate top row

```<code>ð4×         # push 4 spaces
N<i    }    # if we're on the 2nd iteration
   ¨'oJ     # replace the last space with an "o"
,           # print row
</code>```

Generate middle row

```<code>N<iðë'o}     # push a space if we're on the 2nd iteration, else push "o"
ð            # push a space
NÉis}        # if we're on an odd numbered iteration, swap the stacks top 2 chars
"|-|  "      # push this string
J            # join the stack to one string
N1›iR}       # if we're on the any of the last 3 iterations, reverse the string
,            # print row
</code>```

Generate bottom row

```<code>…──|  # push the string "──|"
Â     # push a reversed copy
'-s   # push "-" between the 2 strings on the stack
ðð    # push 2 spaces
X     # push the N we saved in the main loop (current sheep number)
J,    # join and print row
</code>```

Title: So sayeth the Shepherd

Body:
05AB1E, <s>66</s> <s>60</s> 59 bytes

FNU5Fð4×N<i¨'oJ},N<iðë'o}ðNÉis}"|-|  "JN1›iR},…──|Â'-sððXJ,

Uses CP-1252 encoding.

Explanantion

Iteration refers to the inner iteration (0 -> 4) of the sheeps journey.

Main loops

F      # For N in range [0 .. input)
 NU    # Save N in variable X
 5F    # For N in range [0 .. 5)

Generate top row

ð4×         # push 4 spaces
N<i    }    # if we're on the 2nd iteration
   ¨'oJ     # replace the last space with an "o"
,           # print row

Generate middle row

N<iðë'o}     # push a space if we're on the 2nd iteration, else push "o"
ð            # push a space
NÉis}        # if we're on an odd numbered iteration, swap the stacks top 2 chars
"|-|  "      # push this string
J            # join the stack to one string
N1›iR}       # if we're on the any of the last 3 iterations, reverse the string
,            # print row

Generate bottom row

…──|  # push the string "──|"
Â     # push a reversed copy
'-s   # push "-" between the 2 strings on the stack
ðð    # push 2 spaces
X     # push the N we saved in the main loop (current sheep number)
J,    # join and print row


答:
MATL, <s>60</s> <s>56</s> 53 bytes

```<code>:"@qXJx[HKCbO]"7Z"'  |-|  'v'o'@('--|-|--  '  JVhXxXD
</code>```

The animation with the above code runs very fast. The following version includes a pause to make the animation slower and thus easier to see (not required by the challenge), at the cost of 4 more bytes:

```<code>:"@qXJx[HKCbO]"7Z"'  |-|  'v'o'@('--|-|--  '  JVhXxXD.2Y.
</code>```

Try it at MATL Online! The interpreter is a beta; refresh the page if it doesn't work.

Or see a recording from the offline compiler:

Explanation

```<code>:"              % Input N implicitly. Repeat N times
  @q            %   Push iteration index minus 1, that is, from 0 to N-1. This
                %   are the numbers of sheep
  XJx           %   Copy into clipboard J and delete
  [HKCbO]       %   Push array [2 4 7 -2 0]
  "             %   For each value in that array. This loops generates the 5
                %   frames for each number of sheep
    7Z"         %     Push string of 7 spaces
    '  |-|  '   %     Push this string
    v           %     Concatenate vertically. This gives a 2x7 char array
                %     with the upper part of the frame, except the 'o',
                %     which will be now placed in a varying position
    'o'         %     Push string 'o'
    @           %     Push loop variable, that is, 2, 4, 7, -2 or 0
    (           %     Write 'o' into that position of the 2x7 char array.
                %     The position is interpreated linearly, that is, a single
                %     number is used as index into the 2D array in column-major
                %     order (down, then across). So index 2 is lower-left corner,
                %     index 4 is to the right of that etc. Indexing is
                %     semi-modular (modular for non-positive values). So 0 is
                %     the lower-right corner, and -2 is to the left of that
    '--|-|--  ' %     Push this string
    JV          %     Push current number of sheep converted to string
    h           %     Concatenate horizontally
    Xx          %     Clear screen
    XD          %     Display all stack contents
    .2Y.        %     Pause for 0.2 seconds (optional)
                %   End implicitly
                % End implicitly
</code>```

Title: So sayeth the Shepherd

Body:
MATL, <s>60</s> <s>56</s> 53 bytes

:"@qXJx[HKCbO]"7Z"'  |-|  'v'o'@('--|-|--  '  JVhXxXD

The animation with the above code runs very fast. The following version includes a pause to make the animation slower and thus easier to see (not required by the challenge), at the cost of 4 more bytes:

:"@qXJx[HKCbO]"7Z"'  |-|  'v'o'@('--|-|--  '  JVhXxXD.2Y.

Try it at MATL Online! The interpreter is a beta; refresh the page if it doesn't work.

Or see a recording from the offline compiler:

Explanation

:"              % Input N implicitly. Repeat N times
  @q            %   Push iteration index minus 1, that is, from 0 to N-1. This
                %   are the numbers of sheep
  XJx           %   Copy into clipboard J and delete
  [HKCbO]       %   Push array [2 4 7 -2 0]
  "             %   For each value in that array. This loops generates the 5
                %   frames for each number of sheep
    7Z"         %     Push string of 7 spaces
    '  |-|  '   %     Push this string
    v           %     Concatenate vertically. This gives a 2x7 char array
                %     with the upper part of the frame, except the 'o',
                %     which will be now placed in a varying position
    'o'         %     Push string 'o'
    @           %     Push loop variable, that is, 2, 4, 7, -2 or 0
    (           %     Write 'o' into that position of the 2x7 char array.
                %     The position is interpreated linearly, that is, a single
                %     number is used as index into the 2D array in column-major
                %     order (down, then across). So index 2 is lower-left corner,
                %     index 4 is to the right of that etc. Indexing is
                %     semi-modular (modular for non-positive values). So 0 is
                %     the lower-right corner, and -2 is to the left of that
    '--|-|--  ' %     Push this string
    JV          %     Push current number of sheep converted to string
    h           %     Concatenate horizontally
    Xx          %     Clear screen
    XD          %     Display all stack contents
    .2Y.        %     Pause for 0.2 seconds (optional)
                %   End implicitly
                % End implicitly