答:
Jelly, 22 bytes

```<code>4ṗạµ×2,5,10,20S€+⁵iƓịḤ
</code>```

Try it online! or verify all test cases.

How it works

```<code>4ṗạµ×2,5,10,20S€+⁵iƓịḤ  Main link. No arguments

4                       Set the left argument and initial return value to 4.
 ṗ                      Take the Cartesian power of [1, 2, 3, 4] and 4, i.e.,
                        generate all 4-tuples of integers between 1 and 4.
  ạ                     Take the absolute difference of all integers in the
                        4-tuples and the integer 4. This maps [1, 2, 3, 4] to
                        [3, 2, 1, 0] and places [0, 0, 0, 0] at index 0.
   µ                    Begin a new, monadic chain. Argument: A (list of 4-tuples)
     2,5,10,20          Yield [2, 5, 10, 20].
    ×                   Perform vectorized multiplication with each 4-tuple in A.
              S€        Sum each resulting 4-tuple.
                +⁵      Add 10 to each sum.
                   Ɠ    Read an integer from STDIN.
                  i     Find its first index in the array of sums (0 if not found).
                     Ḥ  Unhalve; yield the list A, with all integers doubled.
                    ị   Retrieve the 4-tuple at the proper index.
</code>```

Body:
Jelly, 22 bytes

4ṗạµ×2,5,10,20S€+⁵iƓịḤ

Try it online! or verify all test cases.

How it works

4ṗạµ×2,5,10,20S€+⁵iƓịḤ  Main link. No arguments

4                       Set the left argument and initial return value to 4.
 ṗ                      Take the Cartesian power of [1, 2, 3, 4] and 4, i.e.,
                        generate all 4-tuples of integers between 1 and 4.
  ạ                     Take the absolute difference of all integers in the
                        4-tuples and the integer 4. This maps [1, 2, 3, 4] to
                        [3, 2, 1, 0] and places [0, 0, 0, 0] at index 0.
   µ                    Begin a new, monadic chain. Argument: A (list of 4-tuples)
     2,5,10,20          Yield [2, 5, 10, 20].
    ×                   Perform vectorized multiplication with each 4-tuple in A.
              S€        Sum each resulting 4-tuple.
                +⁵      Add 10 to each sum.
                   Ɠ    Read an integer from STDIN.
                  i     Find its first index in the array of sums (0 if not found).
                     Ḥ  Unhalve; yield the list A, with all integers doubled.
                    ị   Retrieve the 4-tuple at the proper index.


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

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

The Rules

Each submission must be a full program.

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

The program must not write anything to STDERR.

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

Note that there must be an interpreter so the submission can be tested. It is allowed (and even encouraged) to write this interpreter yourself for a previously unimplemented language.

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

This is not about finding the language with the shortest "Hello, World!" program. This is about finding the shortest "Hello, World!" program in every language. Therefore, I will not mark any answer as "accepted".

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

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

For inspiration, check the Hello World Collection.

The Catalogue

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

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

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

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

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

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

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

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

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

/* Configuration */

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

/* App */

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

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

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

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

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

getAnswers();

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

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

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

function process() {
  var valid = [];

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

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

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

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

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

    var lang = a.language;
    lang = jQuery(''+lang+'').text();

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

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

  langs.sort(function (a, b) {
    if (a.lang_raw.toLowerCase() > b.lang_raw.toLowerCase()) return 1;
    if (a.lang_raw.toLowerCase() < b.lang_raw.toLowerCase()) return -1;
    return 0;
  });

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

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

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

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

table thead {
  font-weight: bold;
}

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

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

Shortest Solution by Language

Language	User	Score

Leaderboard

	Author	Language	Size

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

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

```

答:
scratchblocks2, 33 bytes

```<code>when gf clicked
say[Hello, World!
</code>```

ContentLicense: CC BY-SA 4.0

Title: "Hello, World!"

Body:
scratchblocks2, 33 bytes

when gf clicked
say[Hello, World!

ContentLicense: CC BY-SA 3.0


问:
Recursion bracketed; or Dyck words generation
We already have challenges to check if a string of brackets is fully matched and to count the number of balanced strings. It remains for us to generate these strings, but it will not be so easy…

A Dyck word is a string, of length 2n, consisting of n opening and n closing parentheses (( and )) fully matched (that is to say: for all prefixes of the string, the number of opening parentheses is greater than or equal to the number of closing ones).

It is interesting to note that the number of different Dyck words of length 2n is equal to the (n + 1)-th Catalan number.

It’s pretty straightforward to write a program that generates these words with a recursive function. But the goal here is to do the same thing without.

Challenge

Write a full program or function that takes a positive integer, n, using stdin or an acceptable alternative, and outputs all the different Dyck words of length 2n. The words can appear in any order and each must be separated from each other by a line break. Moreover, your program should not use recursive functions (see details below).

Rules

The output of your program should only contain Dyck words of length 2n, separated by line breaks. Each word must appear only once.

Your program must work at minimum for inputs 0 to 15.

You may not write recursive functions, neither direct (a function that calls itself) nor indirect (e.g. a function f that calls another function g that calls function f). That being said, you can still use the standard functions of your language without worry of how they work internally.

Similarly, your program should not call itself.

You may not use non-standard librairies.

Your program may not read or write files.

Your program must be able to run in a reasonable time for 0 ≤ n ≤ 15 (hence, naively generate all arrangements is probably not a good idea). Let’s say less than 20 minutes with a memory limit of 4 GB (my reference implementation in C manages n = 15 in less than 5 seconds).

All standard loopholes are forbidden.

As usual in code-golf, the shortest code in bytes wins. But if you have found an interesting way to achieve this challenge in your language, please do not hesitate.

Test I/O

For this input:

```<code>3
</code>```

The output could be (any other order is correct too):

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

答:
Haskell, <s>111</s> 105 bytes

```<code>import Data.Function
id=<<fix(\h a z->id=<<[('(':)<$>h(a-1)z|a>0]++[(')':)<$>h a(z-1)|a<z]++[[""]|a+z<1])
</code>```

Usage example: id=<<fix(\h a z->id=<<[('(':)<$>h(a-1)z|a>0]++[(')':)<$>h a(z-1)|a<z]++[[""]|a+z<1]) $ 3 -> ["((()))","(()())","(())()","()(())","()()()"].

The Dyck word building algorithm used here expressed in a classic recursive way looks like

```<code>dyck a z =                    -- take two numbers, `a` (the number of `(` to use)
                              -- and `z` (the number of `)` to use)
                 [[""]|a+z<1] -- base case if both numbers are 0, the result
                              -- is an empty word
    [('(':)<$>dyck(a-1)z|a>0] -- if there are `(` left, prepend one to every result
                              -- from a recursive call with one `(` less
   [(')':)<$>dyck a(z-1)|a<z] -- same for `)` if there are more than `(`.
id=<<  ...  ++  ...  ++       -- combine those results in to a flat list
</code>```

As recursion is not allowed, we pass the function to call as a third parameter h (and use a lambda instead of a named function):

```<code>\h a z ->   ....  h(a-1)z  ....  h a(z-1)
</code>```

and let the fixpoint combinator fix create this function for us:

```<code>fix(\h a z ...)
</code>```

finally, the leftmost id=<< duplicates the input parameter: (id=<<) f n is f n n, so when the whole function is called, the parameter n is used as a and z.

For input 15 it takes about 3min within ghci (25s when compiled) and a few MB on my 5 year old laptop.

Body:
Haskell, <s>111</s> 105 bytes

import Data.Function
id=<<fix(\h a z->id=<<[('(':)<$>h(a-1)z|a>0]++[(')':)<$>h a(z-1)|a<z]++[[""]|a+z<1])

Usage example: id=<<fix(\h a z->id=<<[('(':)<$>h(a-1)z|a>0]++[(')':)<$>h a(z-1)|a<z]++[[""]|a+z<1]) $ 3 -> ["((()))","(()())","(())()","()(())","()()()"].

The Dyck word building algorithm used here expressed in a classic recursive way looks like

dyck a z =                    -- take two numbers, `a` (the number of `(` to use)
                              -- and `z` (the number of `)` to use)
                 [[""]|a+z<1] -- base case if both numbers are 0, the result
                              -- is an empty word
    [('(':)<$>dyck(a-1)z|a>0] -- if there are `(` left, prepend one to every result
                              -- from a recursive call with one `(` less
   [(')':)<$>dyck a(z-1)|a<z] -- same for `)` if there are more than `(`.
id=<<  ...  ++  ...  ++       -- combine those results in to a flat list

As recursion is not allowed, we pass the function to call as a third parameter h (and use a lambda instead of a named function):

\h a z ->   ....  h(a-1)z  ....  h a(z-1)

and let the fixpoint combinator fix create this function for us:

fix(\h a z ...)

finally, the leftmost id=<< duplicates the input parameter: (id=<<) f n is f n n, so when the whole function is called, the parameter n is used as a and z.

For input 15 it takes about 3min within ghci (25s when compiled) and a few MB on my 5 year old laptop.


问:
Golf bit weaving
Note: the first half of this challenge comes from Martin Ender's previous challenge, Visualize Bit Weaving.

The esoteric programming language evil has an interesting operation on byte values which it calls "weaving".

It is essentially a permutation of the eight bits of the byte (it doesn't matter which end we start counting from, as the pattern is symmetric):

Bit 0 is moved to bit 2

Bit 1 is moved to bit 0

Bit 2 is moved to bit 4

Bit 3 is moved to bit 1

Bit 4 is moved to bit 6

Bit 5 is moved to bit 3

Bit 6 is moved to bit 7

Bit 7 is moved to bit 5

For convenience, here are three other representations of the permutation. As a cycle:

```<code>(02467531)
</code>```

As a mapping:

```<code>57361402 -> 76543210 -> 64725031
</code>```

And as a list of pairs of the mapping:

```<code>[[0,2], [1,0], [2,4], [3,1], [4,6], [5,3], [6,7], [7,5]]
</code>```

After 8 weavings, the byte is essentially reset.

For example, weaving the number 10011101 (which is 157 in base 10) will produce 01110110 (which is 118 in base 10).

Input

There are only 256 valid inputs, namely all the integers between 0 and 255 inclusive. That may be taken in any base, but it must be consistent and you must specify it if the base you choose is not base ten.

You may not zero-pad your inputs.

Output

You should output the result of the bit weaving, in any base, which must also be consistent and specified if not base ten.

You may zero-pad your outputs.

Related: Visualize Bit Weaving

答:
Evil, 3 characters

```<code>rew
</code>```

Try it online!

Input is in base 256, (e.g. ASCII), e.g. to enter the digit 63, enter ASCII 63 which is ?.

Explanation:

```<code>r          #Read a character
 e         #Weave it
  w        #Display it
</code>```

This so feels like cheating.

Title: Golf bit weaving

Body:
Evil, 3 characters

rew

Try it online!

Input is in base 256, (e.g. ASCII), e.g. to enter the digit 63, enter ASCII 63 which is ?.

Explanation:

r          #Read a character
 e         #Weave it
  w        #Display it

This so feels like cheating.


问:
Choose from an existing set of weights to make a target sum
When doing weightlifting, I want to make a specific weight by attaching several plates to a bar.

I have the following plates:

6 plates of 1 kg each

6 plates of 2.5 kg each

6 plates of 5 kg each

6 plates of 10 kg each

The bar itself weighs 10 kg.

It's only allowed to attach the plates in pairs - they are attached at each end of the bar, and the arrangement at the two ends must be completely symmetrical (e.g. attaching two 5-kg plates at one end, and one 10-kg plate at the other end is forbidden for reasons of safety).

Make a program or a function that tells me how many plates of each kind I have to use in order to get a given total weight. The input is an integer greater than 11; the output is a list/array/string of 4 numbers. If it's impossible to combine existing plates to get the target weight, output a zero/empty array, an invalid string, throw an exception or some such.

If there are several solutions, the code must output only one (don't make the user choose - he is too busy with other things).

Test cases:

```<code>12 -> [2 0 0 0] - 2 plates of 1 kg plus the bar of 10 kg
13 -> [0 0 0 0] - a special-case output that means "impossible"
20 -> [0 0 2 0] - 2 plates of 5 kg + bar
20 -> [0 4 0 0] - a different acceptable solution for the above
21 -> [6 2 0 0] - 6 plates of 1 kg + 2 plates of 2.5 kg + bar
28 -> [0 0 0 0] - impossible
45 -> [0 2 6 0] - a solution for a random number in range
112 -> [2 4 6 6] - a solution for a random number in range
121 -> [6 6 6 6] - maximal weight for which a solution is possible
</code>```

If your code outputs the numbers in the opposite order (from the heavy plate to the light one), please specify this explicitly to avoid confusion.

答:
Python 3, 112 bytes

```<code>lambda n:[i for i in[[i//4**j%4*2for j in range(4)]for i in range(256)]if i[0]+2.5*i[1]+5*i[2]+10*i[3]+10==n][0]
</code>```

An anonymous function that takes input, via argument, of the target mass and returns the number of each plate as a list. If no solution exists, an error is thrown. This is pure brute force.

How it works

```<code>lambda n                                   Anonymous function with input target mass n
...for i in range(256)                     Loop for all possible arrangement indices i
[i//4**j%4*2for j in range(4)]             Create a base-4 representation of the index i,
                                           and multiply each digit by 2 to map from
                                           (0,1,2,3) to (0,2,4,6)
[...]                                      Package all possible arrangements in a list
...for i in...                             Loop for all possible arrangements i
i...if i[0]+2.5*i[1]+5*i[2]+10*i[3]+10==n  Return i if it gives the target mass
[...]                                      Package all solutions in a list
:...[0]                                    Return the first list element. This removes any
                                           multiple solutions, and throws an error if there
                                           being no solutions results in an empty list
</code>```

Try it on Ideone

Body:
Python 3, 112 bytes

lambda n:[i for i in[[i//4**j%4*2for j in range(4)]for i in range(256)]if i[0]+2.5*i[1]+5*i[2]+10*i[3]+10==n][0]

An anonymous function that takes input, via argument, of the target mass and returns the number of each plate as a list. If no solution exists, an error is thrown. This is pure brute force.

How it works

lambda n                                   Anonymous function with input target mass n
...for i in range(256)                     Loop for all possible arrangement indices i
[i//4**j%4*2for j in range(4)]             Create a base-4 representation of the index i,
                                           and multiply each digit by 2 to map from
                                           (0,1,2,3) to (0,2,4,6)
[...]                                      Package all possible arrangements in a list
...for i in...                             Loop for all possible arrangements i
i...if i[0]+2.5*i[1]+5*i[2]+10*i[3]+10==n  Return i if it gives the target mass
[...]                                      Package all solutions in a list
:...[0]                                    Return the first list element. This removes any
                                           multiple solutions, and throws an error if there
                                           being no solutions results in an empty list

Try it on Ideone


问:
Difference of the square of the sum
Find the difference between the square of the sums and sum of the squares.

This is the mathematical representation:

\$\left(\sum n\right)^2-\sum n^2\$

Your program/method should take two inputs, these are your lower and upper limits of the range, and are inclusive.
Limits will be whole integers above 0.

Your program/method should return the answer.

You may use whichever base you would like to, but please state in your answer which base you have used.

Test case (Base 10)

```<code>5,9      970
91,123   12087152
1,10     2640
</code>```

This is usual code-golf, so the shorter the answer the better.

答:
GeoGebra, 91 bytes

```<code>a(x)=(x²+x)/2
b(x)=x³/3+x²/2+x/6
c(x,y)=(a(y)-a(x))²
d(x,y)=b(y)-b(x)
c(x-1,y)-d(x-1,y)
</code>```

Defines a function (probably e(x,y)) that computes the desired difference.

a(x) calculates the sum of natural numbers between 0 and x.

b(x) calculates the sum of the squares of the natural numbers between 0 and x.

c(x,y) first computes the sum of the natural numbers between x and y, then squares that sum.

d(x,y) calculates the sum of squares between b(x) and b(y).

The last line defines a multi-variable function that finishes the calculation. The function is automatically assigned a name, saving a few bytes.

Title: Difference of the square of the sum

Body:
GeoGebra, 91 bytes

a(x)=(x²+x)/2
b(x)=x³/3+x²/2+x/6
c(x,y)=(a(y)-a(x))²
d(x,y)=b(y)-b(x)
c(x-1,y)-d(x-1,y)

Defines a function (probably e(x,y)) that computes the desired difference.

a(x) calculates the sum of natural numbers between 0 and x.

b(x) calculates the sum of the squares of the natural numbers between 0 and x.

c(x,y) first computes the sum of the natural numbers between x and y, then squares that sum.

d(x,y) calculates the sum of squares between b(x) and b(y).

The last line defines a multi-variable function that finishes the calculation. The function is automatically assigned a name, saving a few bytes.


答:
Pyth, 19 characters

```<code>s[@z1.it%2tzP%2z@z6
</code>```

Input and output are base 2.

Far from a Pyth expert, but since no one else has answered with it yet I gave it a shot.

Explanation:

```<code>s[                # combine the 3 parts to a collection and then join them
  @z1             # bit 1 goes to bit 0
  .i              # interleave the next two collections
    t%2tz         # bits 3,5,7; t is used before z to offset the index by 1
    P%2z          # bits 0,2,4
  @z6             # bit 6 goes to bit 7
</code>```

Title: Golf bit weaving

Body:
Note: the first half of this challenge comes from Martin Ender's previous challenge, Visualize Bit Weaving.

The esoteric programming language evil has an interesting operation on byte values which it calls "weaving".

It is essentially a permutation of the eight bits of the byte (it doesn't matter which end we start counting from, as the pattern is symmetric):

Bit 0 is moved to bit 2

Bit 1 is moved to bit 0

Bit 2 is moved to bit 4

Bit 3 is moved to bit 1

Bit 4 is moved to bit 6

Bit 5 is moved to bit 3

Bit 6 is moved to bit 7

Bit 7 is moved to bit 5

For convenience, here are three other representations of the permutation. As a cycle:

```<code>(02467531)
</code>```

As a mapping:

```<code>57361402 -> 76543210 -> 64725031
</code>```

And as a list of pairs of the mapping:

```<code>[[0,2], [1,0], [2,4], [3,1], [4,6], [5,3], [6,7], [7,5]]
</code>```

After 8 weavings, the byte is essentially reset.

For example, weaving the number 10011101 (which is 157 in base 10) will produce 01110110 (which is 118 in base 10).

Input

There are only 256 valid inputs, namely all the integers between 0 and 255 inclusive. That may be taken in any base, but it must be consistent and you must specify it if the base you choose is not base ten.

You may not zero-pad your inputs.

Output

You should output the result of the bit weaving, in any base, which must also be consistent and specified if not base ten.

You may zero-pad your outputs.

Related: Visualize Bit Weaving

Body:
Pyth, 19 characters

s[@z1.it%2tzP%2z@z6

Input and output are base 2.

Far from a Pyth expert, but since no one else has answered with it yet I gave it a shot.

Explanation:

s[                # combine the 3 parts to a collection and then join them
  @z1             # bit 1 goes to bit 0
  .i              # interleave the next two collections
    t%2tz         # bits 3,5,7; t is used before z to offset the index by 1
    P%2z          # bits 0,2,4
  @z6             # bit 6 goes to bit 7


答:
R - 33 bytes

```<code>x=scan():scan();sum(x)^2-sum(x^2)
</code>```

pass your lower limit to the first scan then your upper limit to the second scan

Title: Difference of the square of the sum

Body:
Find the difference between the square of the sums and sum of the squares.

This is the mathematical representation:

\$\left(\sum n\right)^2-\sum n^2\$

Your program/method should take two inputs, these are your lower and upper limits of the range, and are inclusive.
Limits will be whole integers above 0.

Your program/method should return the answer.

You may use whichever base you would like to, but please state in your answer which base you have used.

Test case (Base 10)

```<code>5,9      970
91,123   12087152
1,10     2640
</code>```

This is usual code-golf, so the shorter the answer the better.

Body:
R - 33 bytes

x=scan():scan();sum(x)^2-sum(x^2)

pass your lower limit to the first scan then your upper limit to the second scan


Title: Choose from an existing set of weights to make a target sum

Body:
When doing weightlifting, I want to make a specific weight by attaching several plates to a bar.

I have the following plates:

6 plates of 1 kg each

6 plates of 2.5 kg each

6 plates of 5 kg each

6 plates of 10 kg each

The bar itself weighs 10 kg.

It's only allowed to attach the plates in pairs - they are attached at each end of the bar, and the arrangement at the two ends must be completely symmetrical (e.g. attaching two 5-kg plates at one end, and one 10-kg plate at the other end is forbidden for reasons of safety).

Make a program or a function that tells me how many plates of each kind I have to use in order to get a given total weight. The input is an integer greater than 11; the output is a list/array/string of 4 numbers. If it's impossible to combine existing plates to get the target weight, output a zero/empty array, an invalid string, throw an exception or some such.

If there are several solutions, the code must output only one (don't make the user choose - he is too busy with other things).

Test cases:

```<code>12 -> [2 0 0 0] - 2 plates of 1 kg plus the bar of 10 kg
13 -> [0 0 0 0] - a special-case output that means "impossible"
20 -> [0 0 2 0] - 2 plates of 5 kg + bar
20 -> [0 4 0 0] - a different acceptable solution for the above
21 -> [6 2 0 0] - 6 plates of 1 kg + 2 plates of 2.5 kg + bar
28 -> [0 0 0 0] - impossible
45 -> [0 2 6 0] - a solution for a random number in range
112 -> [2 4 6 6] - a solution for a random number in range
121 -> [6 6 6 6] - maximal weight for which a solution is possible
</code>```

If your code outputs the numbers in the opposite order (from the heavy plate to the light one), please specify this explicitly to avoid confusion.

Body:
Brachylog, 50 bytes

,L##l4,L:{.~e[0:3]}a:[2:5:10:20]*+:10+?,L:{:2*.}a.

Returns false when not possible.


问:
Is string X a subsequence of string Y?
Given strings X and Y, determine whether X is a subsequence of Y. The empty string is regarded as a subsequence of every string. (E.g., '' and 'anna' are subsequences of 'banana'.)

Input

X, a possibly-empty case-sensitive alphanumeric string

Y, a possibly-empty case-sensitive alphanumeric string

Output

True or False (or equivalents), correctly indicating whether X is a subsequence of Y.

I/O examples

```<code>X      Y        output

''     'z00'    True
'z00'  'z00'    True
'z00'  '00z0'   False
'aa'   'anna'   True
'anna' 'banana' True
'Anna' 'banana' False
</code>```

Criteria

The shortest program wins, as determined by the number of bytes of source code.

Example programs

Several programs that could be adapted are in this related posting.

答:
C, 23:

```<code>while(*y)*x-*y++?0:x++;
</code>```

result in *x

http://ideone.com/BpITZ

Title: Is string X a subsequence of string Y?

Body:
C, 23:

while(*y)*x-*y++?0:x++;

result in *x

http://ideone.com/BpITZ


问:
Digital River (Shortest And Fastest Solution)
This is my first question, so I hope it goes well.

Background:

It's not the rivers that you might be thinking about. The question revolves around the concept of digital rivers. A digital river is a sequence of numbers where the number following n is n plus the sum of its digits.

Explanation:

12345 is followed by 12360 since 1+2+3+4+5=15 and so 12345 + 15 gives
12360. similarly 145 is followed by 155. If the first number of a digital river is M we will call it river M.

For e.g: River 480 is the sequence beginning {480,492,507,519....}, and river 483 is the sequence beginning {483,498,519,....}. Normal streams and rivers can meet, and the same is true for digital rivers. This happens when two digital rivers share some of the same values.

Example:

River 480 meets river 483 at 519. River 480 meets river 507 at 507 and never meets river 481. Every digital river will eventually meet river 1, river 3 or river 9.

Write a program that can determine for a given integer n the value where river n first meets one of these three rivers.

Input

The input may contain multiple test cases. Each test case occupies a separate line and contains an integer n (1 <= n <= 16384). A test case with value of 0 for n terminates the input and this test case must not be processed.

Output

For each test case in the input first output the test case number (starting from 1) as shown in the sample output. Then on a separate line output the line "first meets river x at y". Here y is the lowest value where river n first meets river x (x = 1 or 3 or 9). If river n meets river x at y for more than one value of x, output the lowest value. Print a blank line between two consecutive test cases.

Test case

Input:

```<code>86
12345
0
</code>```

Output:

```<code>Case #1

first meets river 1 at 101

Case #2

first meets river 3 at 12423
</code>```

Scoring:

The fastest algorithm wins. In case of tie. The one with shorter code will win.

Thanks to mbomb007 for pointing out my error.

p.s: I want to have the fastest solution rather than the smallest one.
I also have a solution of mine which is slow. For that look here.

Note:

I will be using this for code testing. And performance checking.

答:
C

Very simple, it just looks that long because I unrolled all the 3 rivers. It first generates the 3 rivers up to RIVER_LENGTH (which I hope is big enough), and then for each step on N it does a binary search on all three streams to see if it is in any of them. This works because the streams are already sorted, so we can do the contains check in log(n) time.

```<code>#include <stdio.h>

#define RIVER_LENGTH 10000

int main() {
    int num_cases;
    scanf("%d", &num_cases);
    int cases[num_cases];
    int N;
    int s1[RIVER_LENGTH] = {1};
    int s3[RIVER_LENGTH] = {3};
    int s9[RIVER_LENGTH] = {9};
    int i;
    int temp;

    for (i = 1; i < RIVER_LENGTH; i++) {
        s1[i] = temp = s1[i-1];
        while (temp) {
            s1[i] += temp % 10;
            temp /= 10;
        }
    }

    for (i = 1; i < RIVER_LENGTH; i++) {
        s3[i] = temp = s3[i-1];
        while (temp) {
            s3[i] += temp % 10;
            temp /= 10;
        }
    }

    for (i = 1; i < RIVER_LENGTH; i++) {
        s9[i] = temp = s9[i-1];
        while (temp) {
            s9[i] += temp % 10;
            temp /= 10;
        }
    }

    int start;
    int end;
    int pivot;

    for (i=1; i <= num_cases; i++) {
        scanf("%d", &cases[i]);
    }

    for (i=1; i <= num_cases; i++) {
        printf("Case #%d\n\n", i);
        N = cases[i];

        while (1) {

            temp = N;
            while (temp) {
                N += temp % 10;
                temp /= 10;
            }

            start = 0;
            end = RIVER_LENGTH;
            pivot = 1;

            while (end != start && pivot != RIVER_LENGTH - 1) {
                pivot = start + ((end - start) >> 1);
                if (s1[pivot] == N) {
                    printf("first meets river 1 at %d\n\n", N);
                    goto case_done;
                } else if (N < s1[pivot]){
                    end = pivot;
                } else {
                    start = pivot+1;
                }
            }

            start = 0;
            end = RIVER_LENGTH;
            pivot = 1;

            while (end != start && pivot != RIVER_LENGTH - 1) {
                pivot = start + ((end - start) >> 1);
                if (s3[pivot] == N) {
                    printf("first meets river 3 at %d\n\n", N);
                    goto case_done;
                } else if (N < s3[pivot]){
                    end = pivot;
                } else {
                    start = pivot+1;
                }
            }

            start = 0;
            end = RIVER_LENGTH;
            pivot = 1;

            while (end != start && pivot != RIVER_LENGTH - 1) {
                pivot = start + ((end - start) >> 1);
                if (s9[pivot] == N) {
                    printf("first meets river 9 at %d\n\n", N);
                    goto case_done;
                } else if (N < s9[pivot]){
                    end = pivot;
                } else {
                    start = pivot+1;
                }
            }
        }

        case_done:;

    }
}
</code>```

It takes a number for the number of cases first, instead of using 0 to delimit the end of the inputs, because you know, C. This is just for convenience and doesn't really affect anything, so I hope its okay.

Body:
C

Very simple, it just looks that long because I unrolled all the 3 rivers. It first generates the 3 rivers up to RIVER_LENGTH (which I hope is big enough), and then for each step on N it does a binary search on all three streams to see if it is in any of them. This works because the streams are already sorted, so we can do the contains check in log(n) time.

#include <stdio.h>

#define RIVER_LENGTH 10000

int main() {
    int num_cases;
    scanf("%d", &num_cases);
    int cases[num_cases];
    int N;
    int s1[RIVER_LENGTH] = {1};
    int s3[RIVER_LENGTH] = {3};
    int s9[RIVER_LENGTH] = {9};
    int i;
    int temp;

    for (i = 1; i < RIVER_LENGTH; i++) {
        s1[i] = temp = s1[i-1];
        while (temp) {
            s1[i] += temp % 10;
            temp /= 10;
        }
    }

    for (i = 1; i < RIVER_LENGTH; i++) {
        s3[i] = temp = s3[i-1];
        while (temp) {
            s3[i] += temp % 10;
            temp /= 10;
        }
    }

    for (i = 1; i < RIVER_LENGTH; i++) {
        s9[i] = temp = s9[i-1];
        while (temp) {
            s9[i] += temp % 10;
            temp /= 10;
        }
    }

    int start;
    int end;
    int pivot;

    for (i=1; i <= num_cases; i++) {
        scanf("%d", &cases[i]);
    }

    for (i=1; i <= num_cases; i++) {
        printf("Case #%d\n\n", i);
        N = cases[i];

        while (1) {

            temp = N;
            while (temp) {
                N += temp % 10;
                temp /= 10;
            }

            start = 0;
            end = RIVER_LENGTH;
            pivot = 1;

            while (end != start && pivot != RIVER_LENGTH - 1) {
                pivot = start + ((end - start) >> 1);
                if (s1[pivot] == N) {
                    printf("first meets river 1 at %d\n\n", N);
                    goto case_done;
                } else if (N < s1[pivot]){
                    end = pivot;
                } else {
                    start = pivot+1;
                }
            }

            start = 0;
            end = RIVER_LENGTH;
            pivot = 1;

            while (end != start && pivot != RIVER_LENGTH - 1) {
                pivot = start + ((end - start) >> 1);
                if (s3[pivot] == N) {
                    printf("first meets river 3 at %d\n\n", N);
                    goto case_done;
                } else if (N < s3[pivot]){
                    end = pivot;
                } else {
                    start = pivot+1;
                }
            }

            start = 0;
            end = RIVER_LENGTH;
            pivot = 1;

            while (end != start && pivot != RIVER_LENGTH - 1) {
                pivot = start + ((end - start) >> 1);
                if (s9[pivot] == N) {
                    printf("first meets river 9 at %d\n\n", N);
                    goto case_done;
                } else if (N < s9[pivot]){
                    end = pivot;
                } else {
                    start = pivot+1;
                }
            }
        }

        case_done:;

    }
}

It takes a number for the number of cases first, instead of using 0 to delimit the end of the inputs, because you know, C. This is just for convenience and doesn't really affect anything, so I hope its okay.


答:
C, 320 <s>294</s> bytes

Compile with -std=c99

```<code>#include<stdio.h>
int s(int i){for(int j=i;j;j/=10)i+=j%10;return i;}int main(){int c=0,i;while(scanf("%d",&i)){c++;if(!i)continue;int j,o[]={1,3,9},p[]={1,3,9};Q:for(j=0;j<3;j++){if(o[j]==i)goto D;else if(o[j]<i){o[j]=s(o[j]);goto Q;}}i=s(i);goto Q;D:printf("Case #%d\n\nfirst meets river %d at %d\n\n",c,p[j],o[j]);}}
</code>```

Ungolfed:

```<code>#include <stdio.h>

int s(int i)
{
    for(int j = i; j; j /= 10)
        i += j % 10;
    return i;
}

int main()
{
    int c = 0, i;
    while(scanf("%d", &i))
    {
        c++;
        if(!i)
            continue;
        int j,o[]={1,3,9},p[]={1,3,9};
        Q: for(j = 0; j < 3; j++)
        {
            if(o[j] == i)
                goto D;
            else if(o[j] < i)
            {
                o[j] = s(o[j]);
                goto Q;
            }
        }
        i = s(i);
        goto Q;
        D: printf("Case #%d\n\nfirst meets river %d at %d\n\n", c, p[j], o[j]);
    }
}
</code>```

Try it out!

Essentially, the "target" rivers are increased until they're greater than the river we're testing against, and afterwards the test river is increased. This is repeated until the test river is equal to some other river.

<s>I'm not reading parameters from the command line in this program, and I'm not sure if you're supposed to.</s> Now you can pass parameters to STDIN. You can terminate by passing a non-numeric input.

Also darn, beaten by half an hour.

Title: Digital River (Shortest And Fastest Solution)

Body:
This is my first question, so I hope it goes well.

Background:

It's not the rivers that you might be thinking about. The question revolves around the concept of digital rivers. A digital river is a sequence of numbers where the number following n is n plus the sum of its digits.

Explanation:

12345 is followed by 12360 since 1+2+3+4+5=15 and so 12345 + 15 gives
12360. similarly 145 is followed by 155. If the first number of a digital river is M we will call it river M.

For e.g: River 480 is the sequence beginning {480,492,507,519....}, and river 483 is the sequence beginning {483,498,519,....}. Normal streams and rivers can meet, and the same is true for digital rivers. This happens when two digital rivers share some of the same values.

Example:

River 480 meets river 483 at 519. River 480 meets river 507 at 507 and never meets river 481. Every digital river will eventually meet river 1, river 3 or river 9.

Write a program that can determine for a given integer n the value where river n first meets one of these three rivers.

Input

The input may contain multiple test cases. Each test case occupies a separate line and contains an integer n (1 <= n <= 16384). A test case with value of 0 for n terminates the input and this test case must not be processed.

Output

For each test case in the input first output the test case number (starting from 1) as shown in the sample output. Then on a separate line output the line "first meets river x at y". Here y is the lowest value where river n first meets river x (x = 1 or 3 or 9). If river n meets river x at y for more than one value of x, output the lowest value. Print a blank line between two consecutive test cases.

Test case

Input:

```<code>86
12345
0
</code>```

Output:

```<code>Case #1

first meets river 1 at 101

Case #2

first meets river 3 at 12423
</code>```

Scoring:

The fastest algorithm wins. In case of tie. The one with shorter code will win.

Thanks to mbomb007 for pointing out my error.

p.s: I want to have the fastest solution rather than the smallest one.
I also have a solution of mine which is slow. For that look here.

Note:

I will be using this for code testing. And performance checking.

Body:
C, 320 <s>294</s> bytes

Compile with -std=c99

#include<stdio.h>
int s(int i){for(int j=i;j;j/=10)i+=j%10;return i;}int main(){int c=0,i;while(scanf("%d",&i)){c++;if(!i)continue;int j,o[]={1,3,9},p[]={1,3,9};Q:for(j=0;j<3;j++){if(o[j]==i)goto D;else if(o[j]<i){o[j]=s(o[j]);goto Q;}}i=s(i);goto Q;D:printf("Case #%d\n\nfirst meets river %d at %d\n\n",c,p[j],o[j]);}}

Ungolfed:

#include <stdio.h>

int s(int i)
{
    for(int j = i; j; j /= 10)
        i += j % 10;
    return i;
}

int main()
{
    int c = 0, i;
    while(scanf("%d", &i))
    {
        c++;
        if(!i)
            continue;
        int j,o[]={1,3,9},p[]={1,3,9};
        Q: for(j = 0; j < 3; j++)
        {
            if(o[j] == i)
                goto D;
            else if(o[j] < i)
            {
                o[j] = s(o[j]);
                goto Q;
            }
        }
        i = s(i);
        goto Q;
        D: printf("Case #%d\n\nfirst meets river %d at %d\n\n", c, p[j], o[j]);
    }
}

Try it out!

Essentially, the "target" rivers are increased until they're greater than the river we're testing against, and afterwards the test river is increased. This is repeated until the test river is equal to some other river.

<s>I'm not reading parameters from the command line in this program, and I'm not sure if you're supposed to.</s> Now you can pass parameters to STDIN. You can terminate by passing a non-numeric input.

Also darn, beaten by half an hour.


答:
Retina, 39 bytes

```<code>+`^(?!.{8})
0
(.)(.)
$2$1
\B(.)(.)
$2$1
</code>```

Input and output in base 2, output is left-padded.

Try it online!

Explanation

```<code>+`^(?!.{8})
0
</code>```

This just left-pads the input with zeros. The + indicates that this stage is repeated until the string stops changing. It matches the beginning of the string as long as there are less than 8 characters in it, and inserts a 0 in that position.

Now for the actual permutation. The straight-forward solution is this:

```<code>(.)(.)(.)(.)(.)(.)(.)(.)
$2$4$1$6$3$8$5$7
</code>```

However that's painfully long and redundant. I found a different formulation of the permutation that is much easier to implement in Retina (X represents a swap of adjacent bits):

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

Now that's much easier to implement:

```<code>(.)(.)
$2$1
</code>```

This simply matches two characters and swaps them. Since matches don't overlap, this swaps all four pairs.

```<code>\B(.)(.)
$2$1
</code>```

Now we want to do the same thing again, but we want to skip the first character. The easiest way to do so is to require that the match doesn't start at a word boundary with \B.

Title: Golf bit weaving

Body:
Retina, 39 bytes

+`^(?!.{8})
0
(.)(.)
$2$1
\B(.)(.)
$2$1

Input and output in base 2, output is left-padded.

Try it online!

Explanation

+`^(?!.{8})
0

This just left-pads the input with zeros. The + indicates that this stage is repeated until the string stops changing. It matches the beginning of the string as long as there are less than 8 characters in it, and inserts a 0 in that position.

Now for the actual permutation. The straight-forward solution is this:

(.)(.)(.)(.)(.)(.)(.)(.)
$2$4$1$6$3$8$5$7

However that's painfully long and redundant. I found a different formulation of the permutation that is much easier to implement in Retina (X represents a swap of adjacent bits):

1 2 3 4 5 6 7 8
 X   X   X   X
2 1 4 3 6 5 8 7
   X   X   X
2 4 1 6 3 8 5 7

Now that's much easier to implement:

(.)(.)
$2$1

This simply matches two characters and swaps them. Since matches don't overlap, this swaps all four pairs.

\B(.)(.)
$2$1

Now we want to do the same thing again, but we want to skip the first character. The easiest way to do so is to require that the match doesn't start at a word boundary with \B.


答:
x86 machine code, 20 bytes

In hex:

```<code>89C22455C1E002D0E0D1E880E2AAC0EA0211D0C3
</code>```

It's a procedure taking input and returning result via AL register

Disassembly

```<code>89 c2                   mov    edx,eax
24 55                   and    al,0x55  ;Clear odd bits
c1 e0 02                shl    eax,0x2  ;Shift left, bit 6 goes to AH...
d0 e0                   shl    al,1     ;...and doesn't affected by this shift
d1 e8                   shr    eax,1    ;Shift bits to their's target positions
80 e2 aa                and    dl,0xaa  ;Clear even bits
c0 ea 02                shr    dl,0x2   ;Shift right, bit 1 goes to CF
11 d0                   adc    eax,edx  ;EAX=EAX+EDX+CF
c3                      ret
</code>```

Title: Golf bit weaving

Body:
x86 machine code, 20 bytes

In hex:

89C22455C1E002D0E0D1E880E2AAC0EA0211D0C3

It's a procedure taking input and returning result via AL register

Disassembly

89 c2                   mov    edx,eax
24 55                   and    al,0x55  ;Clear odd bits
c1 e0 02                shl    eax,0x2  ;Shift left, bit 6 goes to AH...
d0 e0                   shl    al,1     ;...and doesn't affected by this shift
d1 e8                   shr    eax,1    ;Shift bits to their's target positions
80 e2 aa                and    dl,0xaa  ;Clear even bits
c0 ea 02                shr    dl,0x2   ;Shift right, bit 1 goes to CF
11 d0                   adc    eax,edx  ;EAX=EAX+EDX+CF
c3                      ret


问:
Autonest an array
Everybody loves nested lists! However, sometimes it's hard to make a nested list. You have to decide if you want to nest it deeper, or if you need to nest it shallower. So for your challenge, you must "Autonest" a list. To autonest a list, compare every pair of items in the list.

If the second item is smaller, separate the two elements by inserting closing and opening brackets between them, like this:

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

For example, {2, 1} becomes {2}, {1}, and {3, 2, 1} becomes {3}, {2}, {1}

If the second item is the same, then change nothing. For example, {1, 1, 1} stays the same, and {2, 1, 1, 1} would become {2}, {1, 1, 1}.

If the second item is larger, then nest every following item one level deeper. For example, {1, 2} would become {1, {2}} and {1, 2, 3} would become {1, {2, {3}}}

The Challenge

You must write a program or function that takes in a list of numbers, and returns the same list after being autonested. Take this input in your languages native list format (or the closest alternative) or as a string. You do not have to use curly braces like I did in my examples. You can use whichever type of brackets are most natural in your language, as long as this is consistent. You can safely assume the list will only contain integers. You can also assume the list will have at least 2 numbers in it. Here is some sample IO:

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

Standard loopholes apply, and the shortest answer in bytes wins!

答:
MATL, <s>48</s> 43 bytes

```<code>YY_XKx"@K<?93]44@K-?91]@XKV]v93Gd0>sQY"h4L)
</code>```

This uses square brackets in input and output. The output has commas without spaces as separators.

Note that the output would not be interpreted as a nested list in MATL. It would in other languages, and it satisfies the output specification in the challenge.

Try it online!

Explanation

```<code>YY_XKx   % Push -inf. Copy to clipboard K (represents previous input entry). Delete
"        % Take numerical array implicitly. For each entry:
  @K<    %   Is current entry less than the previous one?
  ?93]   %   If so, push 93 (ASCII for ']')
  44     %   Push 44 (ASCII for comma)
  @K-    %   Is current entry different from the previous one?
  ?91]   %   If so, push 91 (ASCII for '[')
  @XKV   %   Push current entry, copy into clipboard K, convert to string
]        % End for each
v        % Concat vertically all stack contents, converting to char
93       % Push 93 (ASCII for ']') (to be repeated the appropriate number of times)
Gd0>sQ   % Determine how many times the input increases, plus 1
Y"       % Repeat 93 that many times
h        % Concat horizontally with previous string. Gives a row array, i.e. string
4L)      % Remove first char, which is an unwanted comma. Display implicitly
</code>```

Title: Autonest an array

Body:
MATL, <s>48</s> 43 bytes

YY_XKx"@K<?93]44@K-?91]@XKV]v93Gd0>sQY"h4L)

This uses square brackets in input and output. The output has commas without spaces as separators.

Note that the output would not be interpreted as a nested list in MATL. It would in other languages, and it satisfies the output specification in the challenge.

Try it online!

Explanation

YY_XKx   % Push -inf. Copy to clipboard K (represents previous input entry). Delete
"        % Take numerical array implicitly. For each entry:
  @K<    %   Is current entry less than the previous one?
  ?93]   %   If so, push 93 (ASCII for ']')
  44     %   Push 44 (ASCII for comma)
  @K-    %   Is current entry different from the previous one?
  ?91]   %   If so, push 91 (ASCII for '[')
  @XKV   %   Push current entry, copy into clipboard K, convert to string
]        % End for each
v        % Concat vertically all stack contents, converting to char
93       % Push 93 (ASCII for ']') (to be repeated the appropriate number of times)
Gd0>sQ   % Determine how many times the input increases, plus 1
Y"       % Repeat 93 that many times
h        % Concat horizontally with previous string. Gives a row array, i.e. string
4L)      % Remove first char, which is an unwanted comma. Display implicitly


答:
C (unsafe macro), 39 bytes

#define w(v)v*4&84|v*2&128|v/2&1|v/4&42
```

<h1>C (function), 41 bytes</h1>

<pre class="lang-c prettyprint-override"><code>w(v){return v*4&84|v*2&128|v/2&1|v/4&42;}
</code>```

C (full program), 59 bytes

main(v){scanf("%d",&v);return v*4&84|v*2&128|v/2&1|v/4&42;}
```

<p>(returns via exit code, so invoke with <code>echo "157" | ./weave;echo $?</code>)</p>

<h1>C (standards-compliant full program), 86 bytes</h1>

<pre class="lang-c prettyprint-override"><code>#include<stdio.h>
int main(){int v;scanf("%d",&v);return v*4&84|v*2&128|v/2&1|v/4&42;}
</code>```

C (standards-compliant full program with no compiler warnings), 95 bytes

#include<stdio.h>
int main(){int v;scanf("%d",&v);return (v*4&84)|(v*2&128)|(v/2&1)|(v/4&42);}
```

<h1>C (standards-compliant full program with no compiler warnings which can read from arguments or stdin and includes error/range checking), 262 bytes</h1>

<pre class="lang-c prettyprint-override"><code>#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
int main(int v,char**p){v=v<2?isatty(0)&&puts("Value?"),scanf("%d",&v)?v:-1:strtol(p[1],p,10);exit(*p==p[1]||v&255^v?fprintf(stderr,"Invalid value\n"):!printf("%d\n",(v*4&84)|(v*2&128)|(v/2&1)|(v/4&42)));}
</code>```

Breakdown

Pretty much the same as a lot of existing answers: bit-shift all the bits into place by using <<2 (*4), <<1 (*2), >>1 (/2) and >>2 (/4), then | it all together.

The rest is nothing but different flavours of boiler-plate.

Title: Golf bit weaving

Body:
C (unsafe macro), 39 bytes

#define w(v)v*4&84|v*2&128|v/2&1|v/4&42

C (function), 41 bytes

w(v){return v*4&84|v*2&128|v/2&1|v/4&42;}

C (full program), 59 bytes

main(v){scanf("%d",&v);return v*4&84|v*2&128|v/2&1|v/4&42;}

(returns via exit code, so invoke with echo "157" | ./weave;echo $?)

C (standards-compliant full program), 86 bytes

#include<stdio.h>
int main(){int v;scanf("%d",&v);return v*4&84|v*2&128|v/2&1|v/4&42;}

C (standards-compliant full program with no compiler warnings), 95 bytes

#include<stdio.h>
int main(){int v;scanf("%d",&v);return (v*4&84)|(v*2&128)|(v/2&1)|(v/4&42);}

C (standards-compliant full program with no compiler warnings which can read from arguments or stdin and includes error/range checking), 262 bytes

#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
int main(int v,char**p){v=v<2?isatty(0)&&puts("Value?"),scanf("%d",&v)?v:-1:strtol(p[1],p,10);exit(*p==p[1]||v&255^v?fprintf(stderr,"Invalid value\n"):!printf("%d\n",(v*4&84)|(v*2&128)|(v/2&1)|(v/4&42)));}

Breakdown

Pretty much the same as a lot of existing answers: bit-shift all the bits into place by using <<2 (*4), <<1 (*2), >>1 (/2) and >>2 (/4), then | it all together.

The rest is nothing but different flavours of boiler-plate.


答:
V, 17 bytes

```<code>8é0$7hd|òxplò2|@q
</code>```

Try it online!

This takes input and output in binary. Most of the byte count comes from padding it with 0's. If padding the input was allowed, we could just do:

```<code>òxplò2|@q
</code>```

Thanks to Martin's solution for the method of swapping characters, e.g:

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

Explanation:

```<code>8é0                 "Insert 8 '0' characters
   $                "Move to the end of the current line
    7h              "Move 7 characters back
      d|            "Delete until the first character
        ò   ò       "Recursively:
         xp         "Swap 2 characters
           l        "And move to the right
             2|     "Move to the second column
               @q   "And repeat our last recursive command.
</code>```

Title: Golf bit weaving

Body:
V, 17 bytes

8é0$7hd|òxplò2|@q

Try it online!

This takes input and output in binary. Most of the byte count comes from padding it with 0's. If padding the input was allowed, we could just do:

òxplò2|@q

Thanks to Martin's solution for the method of swapping characters, e.g:

1 2 3 4 5 6 7 8
 X   X   X   X
2 1 4 3 6 5 8 7
   X   X   X
2 4 1 6 3 8 5 7

Explanation:

8é0                 "Insert 8 '0' characters
   $                "Move to the end of the current line
    7h              "Move 7 characters back
      d|            "Delete until the first character
        ò   ò       "Recursively:
         xp         "Swap 2 characters
           l        "And move to the right
             2|     "Move to the second column
               @q   "And repeat our last recursive command.


问:
Integer square root of integer
Problem:

In your choice of language, write the shortest function that returns the floor of the square root of an unsigned 64-bit integer.

Test cases:

Your function must work correctly for all inputs, but here are a few which help illustrate the idea:

```<code>               INPUT ⟶ OUTPUT

                   0 ⟶  0
                   1 ⟶  1
                   2 ⟶  1
                   3 ⟶  1
                   4 ⟶  2
                   8 ⟶  2
                   9 ⟶  3
                  15 ⟶  3
                  16 ⟶  4
               65535 ⟶ 255
               65536 ⟶ 256
18446744073709551615 ⟶ 4294967295
</code>```

Rules:

You can name your function anything you like. (Unnamed, anonymous, or lambda functions are fine, as long as they are somehow callable.)

Character count is what matters most in this challenge, but runtime is also important. I'm sure you could scan upwards iteratively for the answer in O(√n) time with a very small character count, but O(log(n)) time would really be better (that is, assuming an input value of n, not a bit-length of n).

You will probably want to implement the function using purely integer and/or boolean artithmetic. However, if you really want to use floating-point calculations, then that is fine so long as you call no library functions. So, simply saying return (n>0)?(uint32_t)sqrtl(n):-1; in C is off limits even though it would produce the correct result. If you're using floating-point arithmetic, you may use *, /, +, -, and exponentiation (e.g., ** or ^ if it's a built-in operator in your language of choice, but only exponentiation of powers not less than 1). This restriction is to prevent "cheating" by calling sqrt() or a variant or raising a value to the ½ power.

If you're using floating-point operations (see #3), you aren't required that the return type be integer; only that that the return value is an integer, e.g., floor(sqrt(n)), and be able to hold any unsigned 32-bit value.

If you're using C/C++, you may assume the existence of unsigned 64-bit and 32-bit integer types, e.g., uint64_t and uint32_t as defined in stdint.h. Otherwise, just make sure your integer type is capable of holding any 64-bit unsigned integer.

If your langauge does not support 64-bit integers (for example, Brainfuck apparently only has 8-bit integer support), then do your best with that and state the limitation in your answer title. That said, if you can figure out how to encode a 64-bit integer and correctly obtain the square root of it using 8-bit primitive arithmetic, then more power to you!

Have fun and get creative!

答:
dc, 50 bytes

```<code>dc -e"?dsist[lt2/dstd*li<B]dsBx[lt1+dstd*li!<A]dsAxlt1-f"
</code>```

Spaced out and explained:

```<code>               # The idea here is to start with the input and reduce it quickly until it is
               # less than what we want, then increment it until it's just right
?              # Take input from stdin
d si st        # Duplicate input, store in `i' and in `t'
[              # Begin macro definition (when I write in dc, "macro"=="function")
 lt            # Load t, our test term
 2/            # Divide t by two
 d st          # Store a copy of this new term in `t'
 d*            # Duplicate and multiply (square)
 li<B          # Load i; if i<(t^2), execute B
] d sB x       # Duplicate, store function as `B', and execute
               # Loop ends when t^2 is less than i
[              # Begin macro definition
 lt            # Load t, our test term
 1+            # Increment
 d st          # Store a copy of this new term in `t'
 d*            # Duplicate and multiply (square)
 li!<A         # Load i; if i>=(t^2), execute A
] d sA x       # Duplicate, store function as `A', and execute
               # Loop ends when t^2 == i+1
lt 1- f        # Load t, decrement, and dump stack
</code>```

Title: Integer square root of integer

Body:
dc, 50 bytes

dc -e"?dsist[lt2/dstd*li<B]dsBx[lt1+dstd*li!<A]dsAxlt1-f"

Spaced out and explained:

               # The idea here is to start with the input and reduce it quickly until it is
               # less than what we want, then increment it until it's just right
?              # Take input from stdin
d si st        # Duplicate input, store in `i' and in `t'
[              # Begin macro definition (when I write in dc, "macro"=="function")
 lt            # Load t, our test term
 2/            # Divide t by two
 d st          # Store a copy of this new term in `t'
 d*            # Duplicate and multiply (square)
 li<B          # Load i; if i<(t^2), execute B
] d sB x       # Duplicate, store function as `B', and execute
               # Loop ends when t^2 is less than i
[              # Begin macro definition
 lt            # Load t, our test term
 1+            # Increment
 d st          # Store a copy of this new term in `t'
 d*            # Duplicate and multiply (square)
 li!<A         # Load i; if i>=(t^2), execute A
] d sA x       # Duplicate, store function as `A', and execute
               # Loop ends when t^2 == i+1
lt 1- f        # Load t, decrement, and dump stack


问:
Visualise Bit Weaving
The esoteric programming language evil has an interesting operation on byte values which it calls "weaving". It is essentially a permutation of the eight bits of the byte (it doesn't matter which end we start counting from, as the pattern is symmetric):

Bit 0 is moved to bit 2

Bit 1 is moved to bit 0

Bit 2 is moved to bit 4

Bit 3 is moved to bit 1

Bit 4 is moved to bit 6

Bit 5 is moved to bit 3

Bit 6 is moved to bit 7

Bit 7 is moved to bit 5

For convenience, here are two other representations of the permutation. As a cycle:

```<code>(02467531)
</code>```

And as a list of pairs of the mapping:

```<code>[[0,2], [1,0], [2,4], [3,1], [4,6], [5,3], [6,7], [7,5]]
</code>```

Your task is to visualise this permutation, using the box-drawing characters ─, │, ┌, ┐, └, ┘, ┼ (Unicode code points: U+2500, U+2502, U+250C, U+2510, U+2514, U+2518, U+253C). This visualisation should satisfy the following constraints:

The first and last line are exactly:

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

Between those, you can use as many lines as you want of up to 15 characters each to fit your box drawing characters (you will need at least 4 lines). The lines should start vertically beneath one of the digits on the first row and end vertically above the corresponding digit on the last row. The eight lines must be connected, and may only cross via ┼ (which is always a crossing, never two turning lines which are touching). The exact paths of the lines are up to you (and finding a particularly golfable layout is the core of this challenge). One valid output would be:

```<code>0 1 2 3 4 5 6 7
│ │ └─┼┐│ │ └┐│
└─┼─┐ ││└─┼─┐││
┌─┘ │ ││  │ │││
│ ┌─┼─┘│  │ │││
│ │ │ ┌┼──┘ │││
│ │ │ │└┐ ┌─┼┼┘
│ │ │ │ │ │ │└┐
0 1 2 3 4 5 6 7
</code>```

However, any other layout that correctly connects the right digits is fine too. Please show your chosen output in your answer.

You may write a program or function and will not take any input. Output the diagram either to STDOUT (or closest alternative) or as a function return value in the form of a string or a list of strings (each representing one line).

Standard code-golf rules apply, so the shortest code (in bytes) wins.

答:
Bash + GNU sed, 140 bytes

sed 'h
s/$/nxxxacnb b b bnyyycanc xxxcnc b b b cnc yyyc/
:
s/x/ac /
s/y/ca /
s/a/└┐/
s/b/┌┼┘/
t
y/cn/│\n/
G'<<<'0 1 2 3 4 5 6 7'
```

<p>Output:</p>

```0 1 2 3 4 5 6 7
└┐│ └┐│ └┐│ └┐│
┌┼┘ ┌┼┘ ┌┼┘ ┌┼┘
│└┐ │└┐ │└┐ │└┐
│ └┐│ └┐│ └┐│ │
│ ┌┼┘ ┌┼┘ ┌┼┘ │
│ │└┐ │└┐ │└┐ │
0 1 2 3 4 5 6 7
```

<p>Using @TimmyD's output: 142 bytes</p>

<pre class="lang-bash prettyprint-override"><code>sed 'h
s/$/npbcccnsurdddnbeeepnp bbbbbbp/
:
s/b/qt/
s/c/quot/
s/d/psor/
s/e/suor/
t
y/nopqrstu/\n─│┌┐└┘┼/
G'<<<'0 1 2 3 4 5 6 7'
</code>```

Output:

```<code>0 1 2 3 4 5 6 7
│┌┘┌┼─┘┌┼─┘┌┼─┘
└┼┐│└─┐│└─┐│└─┐
┌┘└┼─┐└┼─┐└┼─┐│
│ ┌┘┌┘┌┘┌┘┌┘┌┘│
0 1 2 3 4 5 6 7
</code>```

Title: Visualise Bit Weaving

Body:
Bash + GNU sed, 140 bytes

sed 'h
s/$/nxxxacnb b b bnyyycanc xxxcnc b b b cnc yyyc/
:
s/x/ac /
s/y/ca /
s/a/└┐/
s/b/┌┼┘/
t
y/cn/│\n/
G'<<<'0 1 2 3 4 5 6 7'

Output:

0 1 2 3 4 5 6 7
└┐│ └┐│ └┐│ └┐│
┌┼┘ ┌┼┘ ┌┼┘ ┌┼┘
│└┐ │└┐ │└┐ │└┐
│ └┐│ └┐│ └┐│ │
│ ┌┼┘ ┌┼┘ ┌┼┘ │
│ │└┐ │└┐ │└┐ │
0 1 2 3 4 5 6 7

Using @TimmyD's output: 142 bytes

sed 'h
s/$/npbcccnsurdddnbeeepnp bbbbbbp/
:
s/b/qt/
s/c/quot/
s/d/psor/
s/e/suor/
t
y/nopqrstu/\n─│┌┐└┘┼/
G'<<<'0 1 2 3 4 5 6 7'

Output:

0 1 2 3 4 5 6 7
│┌┘┌┼─┘┌┼─┘┌┼─┘
└┼┐│└─┐│└─┐│└─┐
┌┘└┼─┐└┼─┐└┼─┐│
│ ┌┘┌┘┌┘┌┘┌┘┌┘│
0 1 2 3 4 5 6 7


问:
Print a Lego piece
This challenge is a simple ascii-art one. Given two inputs, describing the height and width of a Lego piece, you have print an ASCII art representation of it.

Here is how the Lego pieces are supposed to look:

```<code>(4, 2)

___________
| o o o o |
| o o o o |
-----------

(8, 2)

___________________
| o o o o o o o o |
| o o o o o o o o |
-------------------

(4, 4)

___________
| o o o o |
| o o o o |
| o o o o |
| o o o o |
-----------

(3, 2)

_________
| o o o |
| o o o |
---------

(1, 1)

o
</code>```

If you can't tell from the test-cases, the top and bottom are width*2+3 underscores and dashes, and each row has pipes for the sides, o's for the little things, and everything is separated by spaces.

The only exception for this is (1, 1), which is just a single o.

You will never get 0 for any of the dimensions.

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

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

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

```

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

Anonymous function, returns a multiline string. Try it online!

-3 bytes thanks to borrowing a trick from @El'endiaStarman

```<code>->w,h{w*h<2??o:?_*(x=2*w+3)+$/+(?|+' o'*w+" |
")*h+?-*x}
</code>```

Title: Print a Lego piece

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

Anonymous function, returns a multiline string. Try it online!

-3 bytes thanks to borrowing a trick from @El'endiaStarman

->w,h{w*h<2??o:?_*(x=2*w+3)+$/+(?|+' o'*w+" |
")*h+?-*x}


答:
Minkolang 0.15, <s>58</s> <s>57</s> 56 bytes

Yes, that's right. I golfed off <s>one</s> two stinkin' little bytes...

```<code>nn$d*1-5&"o"O.rd2*3+$z1$([" o"]" ||"2Rlkr$Dlz["-_"0G]$O.
</code>```

Try it here!

Explanation

```<code>nn                Take two numbers from input (stack is now [w h])

                  C special case C
  $d              Duplicate stack
    *1-           Multiply and subtract 1
       5&         Jump 5 spaces if truthy
         "o"O.    Top of stack was 1*1-1=0, so output "o" and stop.

                     C precalculates width of top and bottom lines for later use C
         r           Reverse stack (now [h w])
          d          Duplicate top of stack
           2*3+      Multiply top of stack by 2 and add 3
               $z    Pop this and store in register (z = 2*w+3)

                                       C generates the row C
                 1$(                   Open while loop prepopulated with top of stack
                    [" o"]             w times, push "o "
                          " ||"        Push "|| "
                               2R      Rotate twice to the right
                                 l     Push newline (10)
                                  k    Break out of while loop

                                           C duplicates the row h times C
                                   r       Reverse stack
                                    $D     Duplicate whole stack h times
                                      l    Push newline

                     C this is for the top and bottom lines C
        z[           Open for loop that repeats z times
          "-_"       Push "_-"
              0G     Relocate top of stack to bottom of stack
                ]    Close for loop

                 $O.    Output whole stack as characters and stop.
</code>```

Okay, that's two significant rewrites of the explanation for two bytes saved. I don't think I can or will golf anything more out of this one. :P

Title: Print a Lego piece

Body:
This challenge is a simple ascii-art one. Given two inputs, describing the height and width of a Lego piece, you have print an ASCII art representation of it.

Here is how the Lego pieces are supposed to look:

```<code>(4, 2)

___________
| o o o o |
| o o o o |
-----------

(8, 2)

___________________
| o o o o o o o o |
| o o o o o o o o |
-------------------

(4, 4)

___________
| o o o o |
| o o o o |
| o o o o |
| o o o o |
-----------

(3, 2)

_________
| o o o |
| o o o |
---------

(1, 1)

o
</code>```

If you can't tell from the test-cases, the top and bottom are width*2+3 underscores and dashes, and each row has pipes for the sides, o's for the little things, and everything is separated by spaces.

The only exception for this is (1, 1), which is just a single o.

You will never get 0 for any of the dimensions.

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

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

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

```

Body:
Minkolang 0.15, <s>58</s> <s>57</s> 56 bytes

Yes, that's right. I golfed off <s>one</s> two stinkin' little bytes...

nn$d*1-5&"o"O.rd2*3+$z1$([" o"]" ||"2Rlkr$Dlz["-_"0G]$O.

Try it here!

Explanation

nn                Take two numbers from input (stack is now [w h])

                  C special case C
  $d              Duplicate stack
    *1-           Multiply and subtract 1
       5&         Jump 5 spaces if truthy
         "o"O.    Top of stack was 1*1-1=0, so output "o" and stop.

                     C precalculates width of top and bottom lines for later use C
         r           Reverse stack (now [h w])
          d          Duplicate top of stack
           2*3+      Multiply top of stack by 2 and add 3
               $z    Pop this and store in register (z = 2*w+3)

                                       C generates the row C
                 1$(                   Open while loop prepopulated with top of stack
                    [" o"]             w times, push "o "
                          " ||"        Push "|| "
                               2R      Rotate twice to the right
                                 l     Push newline (10)
                                  k    Break out of while loop

                                           C duplicates the row h times C
                                   r       Reverse stack
                                    $D     Duplicate whole stack h times
                                      l    Push newline

                     C this is for the top and bottom lines C
        z[           Open for loop that repeats z times
          "-_"       Push "_-"
              0G     Relocate top of stack to bottom of stack
                ]    Close for loop

                 $O.    Output whole stack as characters and stop.

Okay, that's two significant rewrites of the explanation for two bytes saved. I don't think I can or will golf anything more out of this one. :P


答:
V, <s>43, 40, 38</s> 36 bytes

One of the longest V answers I've ever written...

```<code>Àio ddÀPñóo î½o
u2Pí.«/| °|
Vr-HVr_
</code>```

Try it online!

Since this contains unicode and unprintable characters, here is a reversible hexdump:

```<code>0000000: c069 6f20 1b64 64c0 50f1 f36f 20ee bd6f  .io .dd.P..o ..o
0000010: 0d0a 7532 50ed 2eab 2f7c 20b0 7c0d 0a56  ..u2P.../| .|..V
0000020: 722d 4856 725f                           r-HVr_
</code>```

This challenge is about manipulating text, so perfect for V! On the other hand, V is terrible at conditionals and math, so the differing output for (1, 1) really screwed it up... :(

Explanation:

```<code>À                   "Arg1 times:
 io <esc>           "Insert 'o '
         dd         "Delete this line, and
           À        "Arg2 times:
            P       "Paste it
</code>```

Now we have 'Height' lines of o's with spaces between them.

```<code>ñ                   "Wrap all of the next lines in a macro. This makes it so that if any
                    "Search fails, execution will stop (to handle for the [1, 1] case)
 ó                  "Search and replace
  o î½o             "'o'+space+0 or 1 newlines+another 'o'

u                   "Undo this last search/replace
 2P                 "Paste twice
   í                "Search and replace on every line
    .«/| °|         "A compressed regex. This surrounds every non-empty line with bars.

Vr-                 "Replace the current (last) line with '-'
   H                "Move to line one
    Vr_             "Replace this line with '_'
</code>```

Non-competing version (31 bytes):

Try it online!

This version uses several features that are newer then this challenge to be 5 bytes shorter!

Second explanation:

```<code>ddÀP
</code>```

which is "Delete line, and paste it n times" is replaced with ÀÄ which is "Repeat this line n times". (-2 bytes)

```<code>óo î½o
u
</code>```

which was "Replace the first match of this regex; Undo" was replaced with

```<code>/o î½o
</code>```

Which is just "Search for a match of this regex" (-1 byte)

And lastly, Ò is just a simple synonym for Vr, which both "Replace every character on this line with 'x'". (-2 bytes)

Title: Print a Lego piece

Body:
V, <s>43, 40, 38</s> 36 bytes

One of the longest V answers I've ever written...

Àio ddÀPñóo î½o
u2Pí.«/| °|
Vr-HVr_

Try it online!

Since this contains unicode and unprintable characters, here is a reversible hexdump:

0000000: c069 6f20 1b64 64c0 50f1 f36f 20ee bd6f  .io .dd.P..o ..o
0000010: 0d0a 7532 50ed 2eab 2f7c 20b0 7c0d 0a56  ..u2P.../| .|..V
0000020: 722d 4856 725f                           r-HVr_

This challenge is about manipulating text, so perfect for V! On the other hand, V is terrible at conditionals and math, so the differing output for (1, 1) really screwed it up... :(

Explanation:

À                   "Arg1 times:
 io <esc>           "Insert 'o '
         dd         "Delete this line, and
           À        "Arg2 times:
            P       "Paste it

Now we have 'Height' lines of o's with spaces between them.

ñ                   "Wrap all of the next lines in a macro. This makes it so that if any
                    "Search fails, execution will stop (to handle for the [1, 1] case)
 ó                  "Search and replace
  o î½o             "'o'+space+0 or 1 newlines+another 'o'

u                   "Undo this last search/replace
 2P                 "Paste twice
   í                "Search and replace on every line
    .«/| °|         "A compressed regex. This surrounds every non-empty line with bars.

Vr-                 "Replace the current (last) line with '-'
   H                "Move to line one
    Vr_             "Replace this line with '_'

Non-competing version (31 bytes):

Try it online!

This version uses several features that are newer then this challenge to be 5 bytes shorter!

Second explanation:

ddÀP

which is "Delete line, and paste it n times" is replaced with ÀÄ which is "Repeat this line n times". (-2 bytes)

óo î½o
u

which was "Replace the first match of this regex; Undo" was replaced with

/o î½o

Which is just "Search for a match of this regex" (-1 byte)

And lastly, Ò is just a simple synonym for Vr, which both "Replace every character on this line with 'x'". (-2 bytes)


答:
Python 2, <s>75</s> <s>73</s> 72 bytes

```<code>lambda x,y:(x*'__'+'___\n'+('| '+'o '*x+'|\n')*y+'-'*(x*2+3),'o')[x<2>y]
</code>```

Returns a string, with a conditional to handle the 1,1 block.

Thanks to Lynn and Chepner for two bytes

Title: Print a Lego piece

Body:
Python 2, <s>75</s> <s>73</s> 72 bytes

lambda x,y:(x*'__'+'___\n'+('| '+'o '*x+'|\n')*y+'-'*(x*2+3),'o')[x<2>y]

Returns a string, with a conditional to handle the 1,1 block.

Thanks to Lynn and Chepner for two bytes


答:
Reng v.4, 82 bytes, noncompeting

I pushed a bug fix that fixes functions being overwritten by themselves (please don't ask; my stuff is haunted)

```<code>i#wi#hhw+2e1+ø ~*x}o:{"-"ö<
"_"{:o}w2*3+#xx*2ø
"o"o~
ö"|"o"o"{Wo:o}w*"| "ooh1-?^#h
</code>```

Takes input as space-joined numbers, like 4 2. Try it here!

Title: Print a Lego piece

Body:
Reng v.4, 82 bytes, noncompeting

I pushed a bug fix that fixes functions being overwritten by themselves (please don't ask; my stuff is haunted)

i#wi#hhw+2e1+ø ~*x}o:{"-"ö<
"_"{:o}w2*3+#xx*2ø
"o"o~
ö"|"o"o"{Wo:o}w*"| "ooh1-?^#h

Takes input as space-joined numbers, like 4 2. Try it here!


问:
Tips for golfing in Java

Are there any useful shortcuts that can be used in Java?

As shown below, import already adds at least 17 characters to a program.

import java.io.*;
```

I understand that the simple solution would be to use another language, but it seems to be a real challenge to shorten Java programs.

Tips should be specific to Java: if they're applicable to most C-like languages, they belong in the more general list of tips.

答:
In most cases, your program will be single-threaded, i.e it'll have only one thread running. You can exploit this fact by returning from the main method when you have to exit instantly.

```<code>static void main(String[]a){if(condition)return;}
</code>```

Compare it to "properly" terminating the program:

```<code>static void main(String[]a){if(condition)System.exit(0);}
</code>```

Or pointing to null:

```<code>static void main(String[]a){if(condition)throw null;}
</code>```

Or dividing by 0:

```<code>static void main(String[]a){if(condition)int A=1/0;}
</code>```

Title: Tips for golfing in Java

Body:
In most cases, your program will be single-threaded, i.e it'll have only one thread running. You can exploit this fact by returning from the main method when you have to exit instantly.

static void main(String[]a){if(condition)return;}

Compare it to "properly" terminating the program:

static void main(String[]a){if(condition)System.exit(0);}

Or pointing to null:

static void main(String[]a){if(condition)throw null;}

Or dividing by 0:

static void main(String[]a){if(condition)int A=1/0;}


答:
Jolf, 36 bytes

```<code>?w*jJρΡ,a+3ώj+2J'-"-+"d*'_lH"  ' o'o
?w*jJ                             'o   return "o" if j * J - 1
       ,a                              make a box
         +3ώj                           of width +3ώj = 3+2*j
             +2J                        of height +2J = 2+J
                '-                      specifying corners as "-"
      Ρ           "-+"                 replacing the first run of "-"s
                      d*'_lH            with a run of "_"s of equal length
     ρ                      "  '       replacing all "  "
                               ' o      with " o"
</code>```

Jolf, 24 bytes, noncompeting

Well, I made a better box builtin.

```<code>?w*jJ,AhώjJ"_-'_-'|' o'o
</code>```

Jolf, <s>38</s> 37 bytes

```<code>?w*jJΆ+*'_γ+3ώjS*JΆ'|*j" o' |
"*'-γ'o
</code>```

Simple stuff, really. Saved a byte by noting that !Ζ (math zeta, or the stand deviance) is only 0 when both arguments are 1, and is falsey otherwise (for our case).

Title: Print a Lego piece

Body:
Jolf, 36 bytes

?w*jJρΡ,a+3ώj+2J'-"-+"d*'_lH"  ' o'o
?w*jJ                             'o   return "o" if j * J - 1
       ,a                              make a box
         +3ώj                           of width +3ώj = 3+2*j
             +2J                        of height +2J = 2+J
                '-                      specifying corners as "-"
      Ρ           "-+"                 replacing the first run of "-"s
                      d*'_lH            with a run of "_"s of equal length
     ρ                      "  '       replacing all "  "
                               ' o      with " o"

Jolf, 24 bytes, noncompeting

Well, I made a better box builtin.

?w*jJ,AhώjJ"_-'_-'|' o'o

Jolf, <s>38</s> 37 bytes

?w*jJΆ+*'_γ+3ώjS*JΆ'|*j" o' |
"*'-γ'o

Simple stuff, really. Saved a byte by noting that !Ζ (math zeta, or the stand deviance) is only 0 when both arguments are 1, and is falsey otherwise (for our case).


答:
Java, 318 312 297 294 260 258 bytes

Saved 15 bytes thanks to cliffroot!

```<code>interface a{static void main(String[]A){int b=Byte.valueOf(A[0]),B=Byte.valueOf(A[1]),C=3+b*2;String c="";if(b<2&B<2)c="o";else{for(;C-->0;)c+="_";for(;B-->0;){c+="\n|";for(C=b;C-->0;)c+=" o";c+=" |";}c+="\n";for(C=3+b*2;C-->0;)c+="-";}System.out.print(c);}}
</code>```

It works with command line arguments.

Ungolfed In a human-readable form:

```<code>interface a {
    static void main(String[] A) {
        int b = Byte.valueOf(A[0]),
            B = Byte.valueOf(A[1]),
            C = 3 + b*2;
        String c = "";
        if (b < 2 & B < 2)
            c = "o";
        else {
            for (; C-- > 0;)
                c += "_";
            for (; B-- > 0;) {
                c += "\n|";
                for (C = b; C-- >0;)
                    c += " o";
                c += " |";
            }
            c += "\n";
            for(C = 3 + b*2; C-- >0;)
                c += "-";
        }
        System.out.print(c);
    }
}
</code>```

Yes, it's still difficult to understand what's going on even when the program is ungolfed. So here goes a step-by-step explanation:

```<code>static void main(String[] A)
</code>```

The first two command line arguments -which we'll use to get dimensions- can be used in the program as A[0] and A[1] (respectively).

```<code>int b = Byte.valueOf(A[0]),
    B = Byte.valueOf(A[1]),
    C = 3 + b*2;
String c = "";
</code>```

b is the number of columns, B is the number of rows and C is a variable dedicated for use in for loops.

c is the Lego piece. We'll append rows to it and then print it at the end.

```<code>if (b < 2 & B < 2)
    c = "o";
else {
</code>```

If the piece to be printed is 1x1, then both b (number of columns) and B (number of rows) should be smaller than 2. So we simply set c to a single o and then skip to the statement that System.out.prints the piece if that's the case.

```<code>for (; C-- > 0; C)
    c += "_";
</code>```

Here, we append (integerValueOfA[0] * 2) + 3 underscores to c. This is the topmost row above all holes.

```<code>for (; B > 0; B--) {
    c += "\n|";
    for(C = b; C-- > 0;)
        c+=" o";
    c += " |";
}
</code>```

This is the loop where we construct the piece one row at a time. What's going on inside is impossible to explain without examples. Let's say that the piece is 4x4:

```<code>Before entering the loop, c looks like this:
___________

After the first iteration (\n denotes a line feed):
___________\n
| o o o o |

After the second iteration:
___________\n
| o o o o |\n
| o o o o |

After the third iteration:
___________\n
| o o o o |\n
| o o o o |\n
| o o o o |
</code>```

.

```<code>c += "\n";
for (C = 3 + b*2; C-- > 0;)
    c += "-";
</code>```

Here, we append (integerValueOfA[0] * 2) + 3 hyphens to the piece. This is the row at the very bottom, below all holes.

The 4x4 piece I used for explaining the for loop where the piece is actually constructed now looks like this:

```<code>___________\n
| o o o o |\n
| o o o o |\n
| o o o o |\n
| o o o o |\n
-----------
</code>```

```<code>interface a {
    static void main(String[] A) {
        int b = Byte.valueOf(A[0]),
            B = Byte.valueOf(A[1]),
            C = 3 + b*2;
        String c = "";
        if (b < 2 & B < 2)
            c = "o";
        else {
            for (; C-- > 0;)
                c += "_";
            for (; B-- > 0;) {
                c += "\n|";
                for (C = b; C-- >0;)
                    c += " o";
                c += " |";
            }
            c += "\n";
            for(C = 3 + b*2; C-- >0;)
                c += "-";
        }
        System.out.print(c);
    }
}
</code>```0

And finally, we print the piece!

Title: Print a Lego piece

Body:
Java, 318 312 297 294 260 258 bytes

Saved 15 bytes thanks to cliffroot!

interface a{static void main(String[]A){int b=Byte.valueOf(A[0]),B=Byte.valueOf(A[1]),C=3+b*2;String c="";if(b<2&B<2)c="o";else{for(;C-->0;)c+="_";for(;B-->0;){c+="\n|";for(C=b;C-->0;)c+=" o";c+=" |";}c+="\n";for(C=3+b*2;C-->0;)c+="-";}System.out.print(c);}}

It works with command line arguments.

Ungolfed In a human-readable form:

interface a {
    static void main(String[] A) {
        int b = Byte.valueOf(A[0]),
            B = Byte.valueOf(A[1]),
            C = 3 + b*2;
        String c = "";
        if (b < 2 & B < 2)
            c = "o";
        else {
            for (; C-- > 0;)
                c += "_";
            for (; B-- > 0;) {
                c += "\n|";
                for (C = b; C-- >0;)
                    c += " o";
                c += " |";
            }
            c += "\n";
            for(C = 3 + b*2; C-- >0;)
                c += "-";
        }
        System.out.print(c);
    }
}

Yes, it's still difficult to understand what's going on even when the program is ungolfed. So here goes a step-by-step explanation:

static void main(String[] A)

The first two command line arguments -which we'll use to get dimensions- can be used in the program as A[0] and A[1] (respectively).

int b = Byte.valueOf(A[0]),
    B = Byte.valueOf(A[1]),
    C = 3 + b*2;
String c = "";

b is the number of columns, B is the number of rows and C is a variable dedicated for use in for loops.

c is the Lego piece. We'll append rows to it and then print it at the end.

if (b < 2 & B < 2)
    c = "o";
else {

If the piece to be printed is 1x1, then both b (number of columns) and B (number of rows) should be smaller than 2. So we simply set c to a single o and then skip to the statement that System.out.prints the piece if that's the case.

for (; C-- > 0; C)
    c += "_";

Here, we append (integerValueOfA[0] * 2) + 3 underscores to c. This is the topmost row above all holes.

for (; B > 0; B--) {
    c += "\n|";
    for(C = b; C-- > 0;)
        c+=" o";
    c += " |";
}

This is the loop where we construct the piece one row at a time. What's going on inside is impossible to explain without examples. Let's say that the piece is 4x4:

Before entering the loop, c looks like this:
___________

After the first iteration (\n denotes a line feed):
___________\n
| o o o o |

After the second iteration:
___________\n
| o o o o |\n
| o o o o |

After the third iteration:
___________\n
| o o o o |\n
| o o o o |\n
| o o o o |

.

c += "\n";
for (C = 3 + b*2; C-- > 0;)
    c += "-";

Here, we append (integerValueOfA[0] * 2) + 3 hyphens to the piece. This is the row at the very bottom, below all holes.

The 4x4 piece I used for explaining the for loop where the piece is actually constructed now looks like this:

___________\n
| o o o o |\n
| o o o o |\n
| o o o o |\n
| o o o o |\n
-----------

System.out.print(c);

And finally, we print the piece!


问:
matrix determinant

Calculate the determinant of an n x n matrix.

Rules

read matrix from standard input

write to standard output

do not use ready solutions from library or language

input: columns separated by any space char

input: lines separated by cr and/or lf

Winner

The shortest code :)

答:
Python 233

```<code>def d(x):
 l=len(x)
 if l<2:return x[0][0]
 return sum([(-1)**i*x[i][0]*d(m(x,i))for i in range(l)])
def m(x,i):y=x[:];del(y[i]);y=zip(*y);del(y[0]);return zip(*y)
x=[input()]
for i in (len(x[0])-1)*[1]:x+=[input()]
print d(x)
</code>```

Ungolfed:

```<code>def det(x):
    l = len(x)
    if l == 1:
        return x[0][0]
    return sum([(-1)**i*x[i][0]*det(minor(x,i+1,1)) for i in range(l)])

def minor(x,i,j):
    y = x[:]
    del(y[i-1])
    y=zip(*y)
    del(y[j-1])
    return zip(*y)

def main():
    x = [input()]
    for i in range(len(x[0])-1):
        x += [input()]
    print det(x)

if __name__ == '__main__':
    main()
</code>```

Usage

As requested, input is on stdin and output is to stdout.

I interpreted columns separated by any space char to mean that I can use comma delimited numbers. If this is not the case, I will rework my solution.

This could be about 30 characters shorter if I could specify my input matrix in the form [[a,b,c],[d,e,f],[g,h,i]].

```<code>./det.py
1,-4,9
-6,7,3
1,2,3
</code>```

Result

```<code>-240
</code>```

The determinant is found using Laplace Expansion

Title: matrix determinant

Body:
Python 233

def d(x):
 l=len(x)
 if l<2:return x[0][0]
 return sum([(-1)**i*x[i][0]*d(m(x,i))for i in range(l)])
def m(x,i):y=x[:];del(y[i]);y=zip(*y);del(y[0]);return zip(*y)
x=[input()]
for i in (len(x[0])-1)*[1]:x+=[input()]
print d(x)

Ungolfed:

def det(x):
    l = len(x)
    if l == 1:
        return x[0][0]
    return sum([(-1)**i*x[i][0]*det(minor(x,i+1,1)) for i in range(l)])

def minor(x,i,j):
    y = x[:]
    del(y[i-1])
    y=zip(*y)
    del(y[j-1])
    return zip(*y)

def main():
    x = [input()]
    for i in range(len(x[0])-1):
        x += [input()]
    print det(x)

if __name__ == '__main__':
    main()

Usage

As requested, input is on stdin and output is to stdout.

I interpreted columns separated by any space char to mean that I can use comma delimited numbers. If this is not the case, I will rework my solution.

This could be about 30 characters shorter if I could specify my input matrix in the form [[a,b,c],[d,e,f],[g,h,i]].

./det.py
1,-4,9
-6,7,3
1,2,3

Result

-240

The determinant is found using Laplace Expansion


答:
Bash, 186,163,156, 148,131, 130 Bytes

```<code> ## Arg1 - Lego width
 ## Arg2 - Lego height
function print_lego() {
(($1+$2>2))&&{
printf _%.0s `seq -1 $1`
echo
for((i=$2;i--;)){
 printf \|
 for((j=$1;j--;)){
  printf o
 }
 echo \|
}
printf =%.0s `seq -1 $1`
echo
}||echo o
}
</code>```

Note: If you really need the lego to have hyphens for the last line, then change the last printf to

```<code>printf -- -%.0s `seq -1 $1`
</code>```

and add two bytes.

Title: Print a Lego piece

Body:
Bash, 186,163,156, 148,131, 130 Bytes

 ## Arg1 - Lego width
 ## Arg2 - Lego height
function print_lego() {
(($1+$2>2))&&{
printf _%.0s `seq -1 $1`
echo
for((i=$2;i--;)){
 printf \|
 for((j=$1;j--;)){
  printf o
 }
 echo \|
}
printf =%.0s `seq -1 $1`
echo
}||echo o
}

Note: If you really need the lego to have hyphens for the last line, then change the last printf to

printf -- -%.0s `seq -1 $1`

and add two bytes.