问:
Fibonacci function or sequence
The Fibonacci sequence is a sequence of numbers, where every number in the sequence is the sum of the two numbers preceding it.  The first two numbers in the sequence are both 1. Here are the first few terms:

```<code>1 1 2 3 5 8 13 21 34 55 89 ...
</code>```

Write the shortest code that either:

Generates the Fibonacci sequence without end.

Given n calculates the nth term of the sequence. (Either 1 or zero indexed)

You may use standard forms of input and output.

(I gave both options in case one is easier to do in your chosen language than the other.)

For the function that takes an n, a reasonably large return value (the largest Fibonacci number that fits your computer's normal word size, at a minimum) has to be supported.

Leaderboard

/* Configuration */

var QUESTION_ID = 85; // 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 = 3; // 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: 290px;
  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

```

答:
Ouroboros, 10 bytes

Outputs an infinite Fibonacci sequence, starting at 0, separated by newlines.

```<code>.!+.@.nao+
</code>```

Explanation

Each line of an Ouroboros program represents a snake eating its own tail. When execution reaches the end of the line, it loops back to the beginning. Each snake has a stack to store values.

If this is the first pass through the code, we need to initialize the stack by turning the top into a 1. (The empty stack is treated as containing infinite zeros.) .! dups and logically negates (1 if the value was 0, otherwise 0), and + adds that result to the top value. This has the effect of pushing a 1 if the stack was empty, and doing nothing if the stack contained a nonzero value.

Now, call the two numbers on the stack x and y, where x is smaller and y is on the top of the stack. .@.n copies y, rotates x to the top, and outputs a copy of it. a pushes 10 and o outputs it as a character (printing a newline). Finally, + adds x to a copy of y. The stack now contains y and x+y, and we proceed to the next iteration.

Try it out

// Define Stack class
function Stack() {
  this.stack = [];
  this.length = 0;
}
Stack.prototype.push = function(item) {
  this.stack.push(item);
  this.length++;
}
Stack.prototype.pop = function() {
  var result = 0;
  if (this.length > 0) {
    result = this.stack.pop();
    this.length--;
  }
  return result;
}
Stack.prototype.top = function() {
  var result = 0;
  if (this.length > 0) {
    result = this.stack[this.length - 1];
  }
  return result;
}
Stack.prototype.toString = function() {
  return "" + this.stack;
}

// Define Snake class
function Snake(code) {
  this.code = code;
  this.length = this.code.length;
  this.ip = 0;
  this.ownStack = new Stack();
  this.currStack = this.ownStack;
  this.alive = true;
  this.wait = 0;
  this.partialString = this.partialNumber = null;
}
Snake.prototype.step = function() {
  if (!this.alive) {
    return null;
  }
  if (this.wait > 0) {
    this.wait--;
    return null;
  }
  var instruction = this.code.charAt(this.ip);
  var output = null;
  console.log("Executing instruction " + instruction);
  if (this.partialString !== null) {
    // We're in the middle of a double-quoted string
    if (instruction == '"') {
      // Close the string and push its character codes in reverse order
      for (var i = this.partialString.length - 1; i >= 0; i--) {
        this.currStack.push(this.partialString.charCodeAt(i));
      }
      this.partialString = null;
    } else {
      this.partialString += instruction;
    }
  } else if (instruction == '"') {
    this.partialString = "";
  } else if ("0" <= instruction && instruction <= "9") {
    if (this.partialNumber !== null) {
      this.partialNumber = this.partialNumber + instruction;  // NB: concatenation!
    } else {
      this.partialNumber = instruction;
    }
    next = this.code.charAt((this.ip + 1) % this.length);
    if (next < "0" || "9" < next) {
      // Next instruction is non-numeric, so end number and push it
      this.currStack.push(+this.partialNumber);
      this.partialNumber = null;
    }
  } else if ("a" <= instruction && instruction <= "f") {
    // a-f push numbers 10 through 15
    var value = instruction.charCodeAt(0) - 87;
    this.currStack.push(value);
  } else if (instruction == "$") {
    // Toggle the current stack
    if (this.currStack === this.ownStack) {
      this.currStack = this.program.sharedStack;
    } else {
      this.currStack = this.ownStack;
    }
  } else if (instruction == "s") {
    this.currStack = this.ownStack;
  } else if (instruction == "S") {
    this.currStack = this.program.sharedStack;
  } else if (instruction == "l") {
    this.currStack.push(this.ownStack.length);
  } else if (instruction == "L") {
    this.currStack.push(this.program.sharedStack.length);
  } else if (instruction == ".") {
    var item = this.currStack.pop();
    this.currStack.push(item);
    this.currStack.push(item);
  } else if (instruction == "m") {
    var item = this.ownStack.pop();
    this.program.sharedStack.push(item);
  } else if (instruction == "M") {
    var item = this.program.sharedStack.pop();
    this.ownStack.push(item);
  } else if (instruction == "y") {
    var item = this.ownStack.top();
    this.program.sharedStack.push(item);
  } else if (instruction == "Y") {
    var item = this.program.sharedStack.top();
    this.ownStack.push(item);
  } else if (instruction == "\\") {
    var top = this.currStack.pop();
    var next = this.currStack.pop()
    this.currStack.push(top);
    this.currStack.push(next);
  } else if (instruction == "@") {
    var c = this.currStack.pop();
    var b = this.currStack.pop();
    var a = this.currStack.pop();
    this.currStack.push(b);
    this.currStack.push(c);
    this.currStack.push(a);
  } else if (instruction == ";") {
    this.currStack.pop();
  } else if (instruction == "+") {
    var b = this.currStack.pop();
    var a = this.currStack.pop();
    this.currStack.push(a + b);
  } else if (instruction == "-") {
    var b = this.currStack.pop();
    var a = this.currStack.pop();
    this.currStack.push(a - b);
  } else if (instruction == "*") {
    var b = this.currStack.pop();
    var a = this.currStack.pop();
    this.currStack.push(a * b);
  } else if (instruction == "/") {
    var b = this.currStack.pop();
    var a = this.currStack.pop();
    this.currStack.push(a / b);
  } else if (instruction == "%") {
    var b = this.currStack.pop();
    var a = this.currStack.pop();
    this.currStack.push(a % b);
  } else if (instruction == "_") {
    this.currStack.push(-this.currStack.pop());
  } else if (instruction == "I") {
    var value = this.currStack.pop();
    if (value < 0) {
      this.currStack.push(Math.ceil(value));
    } else {
      this.currStack.push(Math.floor(value));
    }
  } else if (instruction == ">") {
    var b = this.currStack.pop();
    var a = this.currStack.pop();
    this.currStack.push(+(a > b));
  } else if (instruction == "<") {
    var b = this.currStack.pop();
    var a = this.currStack.pop();
    this.currStack.push(+(a < b));
  } else if (instruction == "=") {
    var b = this.currStack.pop();
    var a = this.currStack.pop();
    this.currStack.push(+(a == b));
  } else if (instruction == "!") {
    this.currStack.push(+ !this.currStack.pop());
  } else if (instruction == "?") {
    this.currStack.push(Math.random());
  } else if (instruction == "n") {
    output = "" + this.currStack.pop();
  } else if (instruction == "o") {
    output = String.fromCharCode(this.currStack.pop());
  } else if (instruction == "r") {
    var input = this.program.io.getNumber();
    this.currStack.push(input);
  } else if (instruction == "i") {
    var input = this.program.io.getChar();
    this.currStack.push(input);
  } else if (instruction == "(") {
    this.length -= Math.floor(this.currStack.pop());
    this.length = Math.max(this.length, 0);
  } else if (instruction == ")") {
    this.length += Math.floor(this.currStack.pop());
    this.length = Math.min(this.length, this.code.length);
  } else if (instruction == "w") {
    this.wait = this.currStack.pop();
  }
  // Any unrecognized character is a no-op
  if (this.ip >= this.length) {
    // We've swallowed the IP, so this snake dies
    this.alive = false;
    this.program.snakesLiving--;
  } else {
    // Increment IP and loop if appropriate
    this.ip = (this.ip + 1) % this.length;
  }
  return output;
}
Snake.prototype.getHighlightedCode = function() {
  var result = "";
  for (var i = 0; i < this.code.length; i++) {
    if (i == this.length) {
      result += '';
    }
    if (i == this.ip) {
      if (this.wait > 0) {
        result += '';
      } else {
        result += '';
      }
      result += escapeEntities(this.code.charAt(i)) + '';
    } else {
      result += escapeEntities(this.code.charAt(i));
    }
  }
  if (this.length < this.code.length) {
    result += '';
  }
  return result;
}

// Define Program class
function Program(source, speed, io) {
  this.sharedStack = new Stack();
  this.snakes = source.split(/\r?\n/).map(function(snakeCode) {
    var snake = new Snake(snakeCode);
    snake.program = this;
    snake.sharedStack = this.sharedStack;
    return snake;
  }.bind(this));
  this.snakesLiving = this.snakes.length;
  this.io = io;
  this.speed = speed || 10;
  this.halting = false;
}
Program.prototype.run = function() {
  this.step();
  if (this.snakesLiving) {
    this.timeout = window.setTimeout(this.run.bind(this), 1000 / this.speed);
  }
}
Program.prototype.step = function() {
   for (var s = 0; s < this.snakes.length; s++) {
    var output = this.snakes[s].step();
    if (output) {
      this.io.print(output);
    }
  }
  this.io.displaySource(this.snakes.map(function (snake) {
      return snake.getHighlightedCode();
    }).join("
"));
 }
Program.prototype.halt = function() {
  window.clearTimeout(this.timeout);
}

var ioFunctions = {
  print: function (item) {
    var stdout = document.getElementById('stdout');
    stdout.value += "" + item;
  },
  getChar: function () {
    if (inputData) {
      var inputChar = inputData[0];
      inputData = inputData.slice(1);
      result = inputChar.charCodeAt(0);
    } else {
      result = -1;
    }
    var stdinDisplay = document.getElementById('stdin-display');
    stdinDisplay.innerHTML = escapeEntities(inputData);
    return result;
  },
  getNumber: function () {
    while (inputData && (inputData[0] < "0" || "9" < inputData[0])) {
      inputData = inputData.slice(1);
    }
    if (inputData) {
      var inputNumber = inputData.match(/\d+/)[0];
      inputData = inputData.slice(inputNumber.length);
      result = +inputNumber;
    } else {
      result = -1;
    }
    var stdinDisplay = document.getElementById('stdin-display');
    stdinDisplay.innerHTML = escapeEntities(inputData);
    return result;
  },
  displaySource: function (formattedCode) {
    var sourceDisplay = document.getElementById('source-display');
    sourceDisplay.innerHTML = formattedCode;
  }
};
var program = null;
var inputData = null;
function showEditor() {
  var source = document.getElementById('source'),
    sourceDisplayWrapper = document.getElementById('source-display-wrapper'),
    stdin = document.getElementById('stdin'),
    stdinDisplayWrapper = document.getElementById('stdin-display-wrapper');

  source.style.display = "block";
  stdin.style.display = "block";
  sourceDisplayWrapper.style.display = "none";
  stdinDisplayWrapper.style.display = "none";

  source.focus();
}
function hideEditor() {
  var source = document.getElementById('source'),
    sourceDisplay = document.getElementById('source-display'),
    sourceDisplayWrapper = document.getElementById('source-display-wrapper'),
    stdin = document.getElementById('stdin'),
    stdinDisplay = document.getElementById('stdin-display'),
    stdinDisplayWrapper = document.getElementById('stdin-display-wrapper');

  source.style.display = "none";
  stdin.style.display = "none";
  sourceDisplayWrapper.style.display = "block";
  stdinDisplayWrapper.style.display = "block";

  var sourceHeight = getComputedStyle(source).height,
    stdinHeight = getComputedStyle(stdin).height;
  sourceDisplayWrapper.style.minHeight = sourceHeight;
  sourceDisplayWrapper.style.maxHeight = sourceHeight;
  stdinDisplayWrapper.style.minHeight = stdinHeight;
  stdinDisplayWrapper.style.maxHeight = stdinHeight;
  sourceDisplay.textContent = source.value;
  stdinDisplay.textContent = stdin.value;
}
function escapeEntities(input) {
  return input.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
}
function resetProgram() {
  var stdout = document.getElementById('stdout');
  stdout.value = null;
  if (program !== null) {
    program.halt();
  }
  program = null;
  inputData = null;
  showEditor();
}
function initProgram() {
  var source = document.getElementById('source'),
    stepsPerSecond = document.getElementById('steps-per-second'),
    stdin = document.getElementById('stdin');
  program = new Program(source.value, +stepsPerSecond.innerHTML, ioFunctions);
  hideEditor();
  inputData = stdin.value;
}
function runBtnClick() {
  if (program === null || program.snakesLiving == 0) {
    resetProgram();
    initProgram();
  } else {
    program.halt();
    var stepsPerSecond = document.getElementById('steps-per-second');
    program.speed = +stepsPerSecond.innerHTML;
  }
  program.run();
}
function stepBtnClick() {
  if (program === null) {
    initProgram();
  } else {
    program.halt();
  }
  program.step();
}
function sourceDisplayClick() {
  resetProgram();
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.container {
    width: 100%;
}
.so-box {
    font-family:'Helvetica Neue', Arial, sans-serif;
    font-weight: bold;
    color: #fff;
    text-align: center;
    padding: .3em .7em;
    font-size: 1em;
    line-height: 1.1;
    border: 1px solid #c47b07;
    -webkit-box-shadow: 0 2px 2px rgba(0, 0, 0, 0.3), 0 2px 0 rgba(255, 255, 255, 0.15) inset;
    text-shadow: 0 0 2px rgba(0, 0, 0, 0.5);
    background: #f88912;
    box-shadow: 0 2px 2px rgba(0, 0, 0, 0.3), 0 2px 0 rgba(255, 255, 255, 0.15) inset;
}
.control {
    display: inline-block;
    border-radius: 6px;
    float: left;
    margin-right: 25px;
    cursor: pointer;
}
.option {
    padding: 10px 20px;
    margin-right: 25px;
    float: left;
}
h1 {
    text-align: center;
    font-family: Georgia, 'Times New Roman', serif;
}
a {
    text-decoration: none;
}
input, textarea {
    box-sizing: border-box;
}
textarea {
    display: block;
    white-space: pre;
    overflow: auto;
    height: 100px;
    width: 100%;
    max-width: 100%;
    min-height: 25px;
}
span[contenteditable] {
    padding: 2px 6px;
    background: #cc7801;
    color: #fff;
}
#stdout-container, #stdin-container {
    height: auto;
    padding: 6px 0;
}
#reset {
    float: right;
}
#source-display-wrapper , #stdin-display-wrapper{
    display: none;
    width: 100%;
    height: 100%;
    overflow: auto;
    border: 1px solid black;
    box-sizing: border-box;
}
#source-display , #stdin-display{
    font-family: monospace;
    white-space: pre;
    padding: 2px;
}
.activeToken {
    background: #f93;
}
.nextActiveToken {
    background: #bbb;
}
.swallowedCode{
    color: #999;
}
.clearfix:after {
    content:".";
    display: block;
    height: 0;
    clear: both;
    visibility: hidden;
}
.clearfix {
    display: inline-block;
}
* html .clearfix {
    height: 1%;
}
.clearfix {
    display: block;
}</code>```

<textarea id="source" placeholder="Enter your program here" wrap="off">.!+.@.nao+</textarea>

<textarea id="stdin" placeholder="Input" wrap="off"></textarea>

<input type="button" id="run" class="control so-box" value="Run" onclick="runBtnClick()" /><input type="button" id="pause" class="control so-box" value="Pause" onclick="program.halt()" /><input type="button" id="step" class="control so-box" value="Step" onclick="stepBtnClick()" /><input type="button" id="reset" class="control so-box" value="Reset" onclick="resetProgram()" />

<textarea id="stdout" placeholder="Output" wrap="off" readonly></textarea>

Steps per Second:
20

```

Title: Fibonacci function or sequence

Body:
Ouroboros, 10 bytes

Outputs an infinite Fibonacci sequence, starting at 0, separated by newlines.

.!+.@.nao+

Explanation

Each line of an Ouroboros program represents a snake eating its own tail. When execution reaches the end of the line, it loops back to the beginning. Each snake has a stack to store values.

If this is the first pass through the code, we need to initialize the stack by turning the top into a 1. (The empty stack is treated as containing infinite zeros.) .! dups and logically negates (1 if the value was 0, otherwise 0), and + adds that result to the top value. This has the effect of pushing a 1 if the stack was empty, and doing nothing if the stack contained a nonzero value.

Now, call the two numbers on the stack x and y, where x is smaller and y is on the top of the stack. .@.n copies y, rotates x to the top, and outputs a copy of it. a pushes 10 and o outputs it as a character (printing a newline). Finally, + adds x to a copy of y. The stack now contains y and x+y, and we proceed to the next iteration.

Try it out

// Define Stack class
function Stack() {
  this.stack = [];
  this.length = 0;
}
Stack.prototype.push = function(item) {
  this.stack.push(item);
  this.length++;
}
Stack.prototype.pop = function() {
  var result = 0;
  if (this.length > 0) {
    result = this.stack.pop();
    this.length--;
  }
  return result;
}
Stack.prototype.top = function() {
  var result = 0;
  if (this.length > 0) {
    result = this.stack[this.length - 1];
  }
  return result;
}
Stack.prototype.toString = function() {
  return "" + this.stack;
}

// Define Snake class
function Snake(code) {
  this.code = code;
  this.length = this.code.length;
  this.ip = 0;
  this.ownStack = new Stack();
  this.currStack = this.ownStack;
  this.alive = true;
  this.wait = 0;
  this.partialString = this.partialNumber = null;
}
Snake.prototype.step = function() {
  if (!this.alive) {
    return null;
  }
  if (this.wait > 0) {
    this.wait--;
    return null;
  }
  var instruction = this.code.charAt(this.ip);
  var output = null;
  console.log("Executing instruction " + instruction);
  if (this.partialString !== null) {
    // We're in the middle of a double-quoted string
    if (instruction == '"') {
      // Close the string and push its character codes in reverse order
      for (var i = this.partialString.length - 1; i >= 0; i--) {
        this.currStack.push(this.partialString.charCodeAt(i));
      }
      this.partialString = null;
    } else {
      this.partialString += instruction;
    }
  } else if (instruction == '"') {
    this.partialString = "";
  } else if ("0" <= instruction && instruction <= "9") {
    if (this.partialNumber !== null) {
      this.partialNumber = this.partialNumber + instruction;  // NB: concatenation!
    } else {
      this.partialNumber = instruction;
    }
    next = this.code.charAt((this.ip + 1) % this.length);
    if (next < "0" || "9" < next) {
      // Next instruction is non-numeric, so end number and push it
      this.currStack.push(+this.partialNumber);
      this.partialNumber = null;
    }
  } else if ("a" <= instruction && instruction <= "f") {
    // a-f push numbers 10 through 15
    var value = instruction.charCodeAt(0) - 87;
    this.currStack.push(value);
  } else if (instruction == "$") {
    // Toggle the current stack
    if (this.currStack === this.ownStack) {
      this.currStack = this.program.sharedStack;
    } else {
      this.currStack = this.ownStack;
    }
  } else if (instruction == "s") {
    this.currStack = this.ownStack;
  } else if (instruction == "S") {
    this.currStack = this.program.sharedStack;
  } else if (instruction == "l") {
    this.currStack.push(this.ownStack.length);
  } else if (instruction == "L") {
    this.currStack.push(this.program.sharedStack.length);
  } else if (instruction == ".") {
    var item = this.currStack.pop();
    this.currStack.push(item);
    this.currStack.push(item);
  } else if (instruction == "m") {
    var item = this.ownStack.pop();
    this.program.sharedStack.push(item);
  } else if (instruction == "M") {
    var item = this.program.sharedStack.pop();
    this.ownStack.push(item);
  } else if (instruction == "y") {
    var item = this.ownStack.top();
    this.program.sharedStack.push(item);
  } else if (instruction == "Y") {
    var item = this.program.sharedStack.top();
    this.ownStack.push(item);
  } else if (instruction == "\\") {
    var top = this.currStack.pop();
    var next = this.currStack.pop()
    this.currStack.push(top);
    this.currStack.push(next);
  } else if (instruction == "@") {
    var c = this.currStack.pop();
    var b = this.currStack.pop();
    var a = this.currStack.pop();
    this.currStack.push(b);
    this.currStack.push(c);
    this.currStack.push(a);
  } else if (instruction == ";") {
    this.currStack.pop();
  } else if (instruction == "+") {
    var b = this.currStack.pop();
    var a = this.currStack.pop();
    this.currStack.push(a + b);
  } else if (instruction == "-") {
    var b = this.currStack.pop();
    var a = this.currStack.pop();
    this.currStack.push(a - b);
  } else if (instruction == "*") {
    var b = this.currStack.pop();
    var a = this.currStack.pop();
    this.currStack.push(a * b);
  } else if (instruction == "/") {
    var b = this.currStack.pop();
    var a = this.currStack.pop();
    this.currStack.push(a / b);
  } else if (instruction == "%") {
    var b = this.currStack.pop();
    var a = this.currStack.pop();
    this.currStack.push(a % b);
  } else if (instruction == "_") {
    this.currStack.push(-this.currStack.pop());
  } else if (instruction == "I") {
    var value = this.currStack.pop();
    if (value < 0) {
      this.currStack.push(Math.ceil(value));
    } else {
      this.currStack.push(Math.floor(value));
    }
  } else if (instruction == ">") {
    var b = this.currStack.pop();
    var a = this.currStack.pop();
    this.currStack.push(+(a > b));
  } else if (instruction == "<") {
    var b = this.currStack.pop();
    var a = this.currStack.pop();
    this.currStack.push(+(a < b));
  } else if (instruction == "=") {
    var b = this.currStack.pop();
    var a = this.currStack.pop();
    this.currStack.push(+(a == b));
  } else if (instruction == "!") {
    this.currStack.push(+ !this.currStack.pop());
  } else if (instruction == "?") {
    this.currStack.push(Math.random());
  } else if (instruction == "n") {
    output = "" + this.currStack.pop();
  } else if (instruction == "o") {
    output = String.fromCharCode(this.currStack.pop());
  } else if (instruction == "r") {
    var input = this.program.io.getNumber();
    this.currStack.push(input);
  } else if (instruction == "i") {
    var input = this.program.io.getChar();
    this.currStack.push(input);
  } else if (instruction == "(") {
    this.length -= Math.floor(this.currStack.pop());
    this.length = Math.max(this.length, 0);
  } else if (instruction == ")") {
    this.length += Math.floor(this.currStack.pop());
    this.length = Math.min(this.length, this.code.length);
  } else if (instruction == "w") {
    this.wait = this.currStack.pop();
  }
  // Any unrecognized character is a no-op
  if (this.ip >= this.length) {
    // We've swallowed the IP, so this snake dies
    this.alive = false;
    this.program.snakesLiving--;
  } else {
    // Increment IP and loop if appropriate
    this.ip = (this.ip + 1) % this.length;
  }
  return output;
}
Snake.prototype.getHighlightedCode = function() {
  var result = "";
  for (var i = 0; i < this.code.length; i++) {
    if (i == this.length) {
      result += '<span class="swallowedCode">';
    }
    if (i == this.ip) {
      if (this.wait > 0) {
        result += '<span class="nextActiveToken">';
      } else {
        result += '<span class="activeToken">';
      }
      result += escapeEntities(this.code.charAt(i)) + '</span>';
    } else {
      result += escapeEntities(this.code.charAt(i));
    }
  }
  if (this.length < this.code.length) {
    result += '</span>';
  }
  return result;
}

// Define Program class
function Program(source, speed, io) {
  this.sharedStack = new Stack();
  this.snakes = source.split(/\r?\n/).map(function(snakeCode) {
    var snake = new Snake(snakeCode);
    snake.program = this;
    snake.sharedStack = this.sharedStack;
    return snake;
  }.bind(this));
  this.snakesLiving = this.snakes.length;
  this.io = io;
  this.speed = speed || 10;
  this.halting = false;
}
Program.prototype.run = function() {
  this.step();
  if (this.snakesLiving) {
    this.timeout = window.setTimeout(this.run.bind(this), 1000 / this.speed);
  }
}
Program.prototype.step = function() {
   for (var s = 0; s < this.snakes.length; s++) {
    var output = this.snakes[s].step();
    if (output) {
      this.io.print(output);
    }
  }
  this.io.displaySource(this.snakes.map(function (snake) {
      return snake.getHighlightedCode();
    }).join("<br>"));
 }
Program.prototype.halt = function() {
  window.clearTimeout(this.timeout);
}

var ioFunctions = {
  print: function (item) {
    var stdout = document.getElementById('stdout');
    stdout.value += "" + item;
  },
  getChar: function () {
    if (inputData) {
      var inputChar = inputData[0];
      inputData = inputData.slice(1);
      result = inputChar.charCodeAt(0);
    } else {
      result = -1;
    }
    var stdinDisplay = document.getElementById('stdin-display');
    stdinDisplay.innerHTML = escapeEntities(inputData);
    return result;
  },
  getNumber: function () {
    while (inputData && (inputData[0] < "0" || "9" < inputData[0])) {
      inputData = inputData.slice(1);
    }
    if (inputData) {
      var inputNumber = inputData.match(/\d+/)[0];
      inputData = inputData.slice(inputNumber.length);
      result = +inputNumber;
    } else {
      result = -1;
    }
    var stdinDisplay = document.getElementById('stdin-display');
    stdinDisplay.innerHTML = escapeEntities(inputData);
    return result;
  },
  displaySource: function (formattedCode) {
    var sourceDisplay = document.getElementById('source-display');
    sourceDisplay.innerHTML = formattedCode;
  }
};
var program = null;
var inputData = null;
function showEditor() {
  var source = document.getElementById('source'),
    sourceDisplayWrapper = document.getElementById('source-display-wrapper'),
    stdin = document.getElementById('stdin'),
    stdinDisplayWrapper = document.getElementById('stdin-display-wrapper');

  source.style.display = "block";
  stdin.style.display = "block";
  sourceDisplayWrapper.style.display = "none";
  stdinDisplayWrapper.style.display = "none";

  source.focus();
}
function hideEditor() {
  var source = document.getElementById('source'),
    sourceDisplay = document.getElementById('source-display'),
    sourceDisplayWrapper = document.getElementById('source-display-wrapper'),
    stdin = document.getElementById('stdin'),
    stdinDisplay = document.getElementById('stdin-display'),
    stdinDisplayWrapper = document.getElementById('stdin-display-wrapper');

  source.style.display = "none";
  stdin.style.display = "none";
  sourceDisplayWrapper.style.display = "block";
  stdinDisplayWrapper.style.display = "block";

  var sourceHeight = getComputedStyle(source).height,
    stdinHeight = getComputedStyle(stdin).height;
  sourceDisplayWrapper.style.minHeight = sourceHeight;
  sourceDisplayWrapper.style.maxHeight = sourceHeight;
  stdinDisplayWrapper.style.minHeight = stdinHeight;
  stdinDisplayWrapper.style.maxHeight = stdinHeight;
  sourceDisplay.textContent = source.value;
  stdinDisplay.textContent = stdin.value;
}
function escapeEntities(input) {
  return input.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
}
function resetProgram() {
  var stdout = document.getElementById('stdout');
  stdout.value = null;
  if (program !== null) {
    program.halt();
  }
  program = null;
  inputData = null;
  showEditor();
}
function initProgram() {
  var source = document.getElementById('source'),
    stepsPerSecond = document.getElementById('steps-per-second'),
    stdin = document.getElementById('stdin');
  program = new Program(source.value, +stepsPerSecond.innerHTML, ioFunctions);
  hideEditor();
  inputData = stdin.value;
}
function runBtnClick() {
  if (program === null || program.snakesLiving == 0) {
    resetProgram();
    initProgram();
  } else {
    program.halt();
    var stepsPerSecond = document.getElementById('steps-per-second');
    program.speed = +stepsPerSecond.innerHTML;
  }
  program.run();
}
function stepBtnClick() {
  if (program === null) {
    initProgram();
  } else {
    program.halt();
  }
  program.step();
}
function sourceDisplayClick() {
  resetProgram();
}

.container {
    width: 100%;
}
.so-box {
    font-family:'Helvetica Neue', Arial, sans-serif;
    font-weight: bold;
    color: #fff;
    text-align: center;
    padding: .3em .7em;
    font-size: 1em;
    line-height: 1.1;
    border: 1px solid #c47b07;
    -webkit-box-shadow: 0 2px 2px rgba(0, 0, 0, 0.3), 0 2px 0 rgba(255, 255, 255, 0.15) inset;
    text-shadow: 0 0 2px rgba(0, 0, 0, 0.5);
    background: #f88912;
    box-shadow: 0 2px 2px rgba(0, 0, 0, 0.3), 0 2px 0 rgba(255, 255, 255, 0.15) inset;
}
.control {
    display: inline-block;
    border-radius: 6px;
    float: left;
    margin-right: 25px;
    cursor: pointer;
}
.option {
    padding: 10px 20px;
    margin-right: 25px;
    float: left;
}
h1 {
    text-align: center;
    font-family: Georgia, 'Times New Roman', serif;
}
a {
    text-decoration: none;
}
input, textarea {
    box-sizing: border-box;
}
textarea {
    display: block;
    white-space: pre;
    overflow: auto;
    height: 100px;
    width: 100%;
    max-width: 100%;
    min-height: 25px;
}
span[contenteditable] {
    padding: 2px 6px;
    background: #cc7801;
    color: #fff;
}
#stdout-container, #stdin-container {
    height: auto;
    padding: 6px 0;
}
#reset {
    float: right;
}
#source-display-wrapper , #stdin-display-wrapper{
    display: none;
    width: 100%;
    height: 100%;
    overflow: auto;
    border: 1px solid black;
    box-sizing: border-box;
}
#source-display , #stdin-display{
    font-family: monospace;
    white-space: pre;
    padding: 2px;
}
.activeToken {
    background: #f93;
}
.nextActiveToken {
    background: #bbb;
}
.swallowedCode{
    color: #999;
}
.clearfix:after {
    content:".";
    display: block;
    height: 0;
    clear: both;
    visibility: hidden;
}
.clearfix {
    display: inline-block;
}
* html .clearfix {
    height: 1%;
}
.clearfix {
    display: block;
}

<!--
Designed and written 2015 by D. Loscutoff
Much of the HTML and CSS was taken from this Befunge interpreter by Ingo Bürk: http://codegolf.stackexchange.com/a/40331/16766
-->
<div class="container">
<textarea id="source" placeholder="Enter your program here" wrap="off">.!+.@.nao+</textarea>
<div id="source-display-wrapper" onclick="sourceDisplayClick()"><div id="source-display"></div></div></div><div id="stdin-container" class="container">
<textarea id="stdin" placeholder="Input" wrap="off"></textarea>
<div id="stdin-display-wrapper" onclick="stdinDisplayClick()"><div id="stdin-display"></div></div></div><div id="controls-container" class="container clearfix"><input type="button" id="run" class="control so-box" value="Run" onclick="runBtnClick()" /><input type="button" id="pause" class="control so-box" value="Pause" onclick="program.halt()" /><input type="button" id="step" class="control so-box" value="Step" onclick="stepBtnClick()" /><input type="button" id="reset" class="control so-box" value="Reset" onclick="resetProgram()" /></div><div id="stdout-container" class="container"><textarea id="stdout" placeholder="Output" wrap="off" readonly></textarea></div><div id="options-container" class="container"><div class="option so-box">Steps per Second:
<span id="steps-per-second" contenteditable>20</span></div></div>


问:
Find the Centroid of a Polygon
From Wikipedia:

The centroid of a non-self-intersecting closed polygon
  defined by n vertices (x0,y0),
  (x1,y1), ...,
  (xn−1,yn−1) is the point (Cx,
  Cy), where

and where A is the polygon's signed area,

In these formulas, the vertices are assumed to be numbered in order of
  their occurrence along the polygon's perimeter. Furthermore, the
  vertex ( xn, yn ) is assumed to be the same as
  ( x0, y0 ), meaning i + 1 on the last case
  must loop around to i = 0. Note that if the points are numbered in
  clockwise order the area A, computed as above, will have a negative
  sign; but the centroid coordinates will be correct even in this case.

Given a list of vertices in order (either clockwise, or counter-clockwise), find the centroid of the non-self-intersecting closed polygon represented by the vertices.

If it helps, you may assume input to be only CW, or only CCW. Say so in your answer if you require this.

The coordinates are not required to be integers, and may contain negative numbers.

Input will always be valid and contain at least three vertices.

Inputs only need to be handled that fit in your language's native floating point data type.

You may assume that input numbers will always contain a decimal point.

You may assume that input integers end in . or .0.

You may use complex numbers for input.

Output should be accurate to the nearest thousandth.

Examples

```<code>[(0.,0.), (1.,0.), (1.,1.), (0.,1.)]        -> (0.5, 0.5)
[(-15.21,0.8), (10.1,-0.3), (-0.07,23.55)]  -> -1.727 8.017
[(-39.00,-55.94), (-56.08,-4.73), (-72.64,12.12), (-31.04,53.58), (-30.36,28.29), (17.96,59.17), (0.00,0.00), (10.00,0.00), (20.00,0.00), (148.63,114.32), (8.06,-41.04), (-41.25,34.43)]   -> 5.80104769975, 15.0673812762
</code>```

Too see each polygon on a coordinate plane, paste the coordinates without the square brackets in the "Edit" menu of this page.

I confirmed my results using this Polygon Centroid Point Calculator, which is awful. I couldn't find one that you can input all vertices at once, or that didn't try to erase your - sign when you type it first. I'll post my Python solution for your use after people have had a chance to answer.

ContentLicense: CC BY-SA 3.0

Title: Find the Centroid of a Polygon

Body:
J, 29 bytes

2+/@(+/\(*%3*1#.])-/ .*\)],{.

Applies the formula shown in the problem.

Usage

   f =: 2+/@(+/\(*%3*1#.])-/ .*\)],{.
   f 0 0 , 1 0 , 1 1 ,: 0 1
0.5 0.5
   f _15.21 0.8 , 10.1 _0.3 ,: _0.07 23.55
_1.72667 8.01667
   f _39 _55.94 , _56.08 _4.73 , _72.64 12.12 , _31.04 53.58 , _30.36 28.29 , 17.96 59.17 , 0 0 , 10 0 , 20 0 , 148.63 114.32 , 8.06 _41.04 ,: _41.25 34.43
5.80105 15.0674

Explanation

2+/@(+/\(*%3*1#.])-/ .*\)],{.  Input: 2d array of points P [[x1 y1] [x2 y2] ...]
                           {.  Head of P
                         ]     Get P
                          ,    Join, makes the end cycle back to the front
2                              The constant 2
2                      \       For each pair of points
                  -/ .*        Take the determinant
2    +/\                       Sum each pair of points
         *                     Multiply the sum of each pair by its determinant
          %                    Divide each by
             1#.]              The sum of the determinants
           3*                  Multiplied by 3
 +/@                           Sum and return


答:
Jelly, <s>25</s> <s>24</s> <s>22</s> <s>21</s> 18 bytes

```<code>S×3÷@×"
ṙ-żµÆḊçS€S
</code>```

Applies the formula shown in the problem.

Saved 3 bytes with help from @Jonathan Allan.

Try it online! or Verify all test cases.

Explanation

```<code>S×3÷@×"  Helper link. Input: determinants on LHS, sum of pairs on RHS
S        Sum the determinants
 ×3      Multiply by 3
     ×"  Vectorized multiply between determinants and sums
   ÷@    Divide that by the determinant sum multipled by 3 and return

ṙ-żµÆḊçS€S  Main link. Input: 2d list of points
ṙ-          Rotate the list of points by 1 to the right
  ż         Interleave those with the original points
            This creates all overlapping slices of length 2
   µ        Start new monadic chain
    ÆḊ      Get the determinant of each slice
       S€   Get the sum of each slice (sum of pairs of points)
      ç     Call the helper link
         S  Sum and return
</code>```

Title: Find the Centroid of a Polygon

Body:
From Wikipedia:

The centroid of a non-self-intersecting closed polygon
  defined by n vertices (x0,y0),
  (x1,y1), ...,
  (xn−1,yn−1) is the point (Cx,
  Cy), where

and where A is the polygon's signed area,

In these formulas, the vertices are assumed to be numbered in order of
  their occurrence along the polygon's perimeter. Furthermore, the
  vertex ( xn, yn ) is assumed to be the same as
  ( x0, y0 ), meaning i + 1 on the last case
  must loop around to i = 0. Note that if the points are numbered in
  clockwise order the area A, computed as above, will have a negative
  sign; but the centroid coordinates will be correct even in this case.

Given a list of vertices in order (either clockwise, or counter-clockwise), find the centroid of the non-self-intersecting closed polygon represented by the vertices.

If it helps, you may assume input to be only CW, or only CCW. Say so in your answer if you require this.

The coordinates are not required to be integers, and may contain negative numbers.

Input will always be valid and contain at least three vertices.

Inputs only need to be handled that fit in your language's native floating point data type.

You may assume that input numbers will always contain a decimal point.

You may assume that input integers end in . or .0.

You may use complex numbers for input.

Output should be accurate to the nearest thousandth.

Examples

```<code>[(0.,0.), (1.,0.), (1.,1.), (0.,1.)]        -> (0.5, 0.5)
[(-15.21,0.8), (10.1,-0.3), (-0.07,23.55)]  -> -1.727 8.017
[(-39.00,-55.94), (-56.08,-4.73), (-72.64,12.12), (-31.04,53.58), (-30.36,28.29), (17.96,59.17), (0.00,0.00), (10.00,0.00), (20.00,0.00), (148.63,114.32), (8.06,-41.04), (-41.25,34.43)]   -> 5.80104769975, 15.0673812762
</code>```

Too see each polygon on a coordinate plane, paste the coordinates without the square brackets in the "Edit" menu of this page.

I confirmed my results using this Polygon Centroid Point Calculator, which is awful. I couldn't find one that you can input all vertices at once, or that didn't try to erase your - sign when you type it first. I'll post my Python solution for your use after people have had a chance to answer.

Body:
Jelly, <s>25</s> <s>24</s> <s>22</s> <s>21</s> 18 bytes

S×3÷@×"
ṙ-żµÆḊçS€S

Applies the formula shown in the problem.

Saved 3 bytes with help from @Jonathan Allan.

Try it online! or <a href="http://jelly.tryitonline.net/#code=U8OXM8O3QMOXIgrhuZktxbzCtcOG4biKw6dT4oKsUwrDh-KCrEc&input=&args=W1swLCAwXSwgWzEsIDBdLCBbMSwgMV0sIFswLCAxXV0sIFtbLTE1LjIxLCAwLjhdLCBbMTAuMSwgLTAuM10sIFstMC4wNywgMjMuNTVdXSwgW1stMzkuMCwgLTU1Ljk0XSwgWy01Ni4wOCwgLTQuNzNdLCBbLTcyLjY0LCAxMi4xMl0sIFstMzEuMDQsIDUzLjU4XSwgWy0zMC4zNiwgMjguMjldLCBbMTcuOTYsIDU5LjE3XSwgWzAuMCwgMC4wXSwgWzEwLjAsIDAuMF0sIFsyMC4wLCAwLjBdLCBbMTQ4LjYzLCAxMTQuMzJdLCBbOC4wNiwgLTQxLjA0XSwgWy00MS4yNSwgMzQuNDNdXQ" rel="nofollow noreferrer">Verify all test cases.

Explanation

S×3÷@×"  Helper link. Input: determinants on LHS, sum of pairs on RHS
S        Sum the determinants
 ×3      Multiply by 3
     ×"  Vectorized multiply between determinants and sums
   ÷@    Divide that by the determinant sum multipled by 3 and return

ṙ-żµÆḊçS€S  Main link. Input: 2d list of points
ṙ-          Rotate the list of points by 1 to the right
  ż         Interleave those with the original points
            This creates all overlapping slices of length 2
   µ        Start new monadic chain
    ÆḊ      Get the determinant of each slice
       S€   Get the sum of each slice (sum of pairs of points)
      ç     Call the helper link
         S  Sum and return


Title: Find the Centroid of a Polygon

Body:
Maxima, <s>124 118 116 112</s> 106 byte

f(l):=(l:endcons(l[1],l),l:sum([3,l[i-1]+l[i]]*determinant(matrix(l[i-1],l[i])),i,2,length(l)),l[2]/l[1]);

I'm not experienced with Maxima, so any hints are welcome.

Usage:

(%i6) f([[-15.21,0.8], [10.1,-0.3], [-0.07,23.55]]);
(%o6)              [- 1.726666666666668, 8.016666666666668]


答:
Mathematica, 23 bytes

```<code>RegionCentroid@*Polygon
</code>```

<s>Take THAT, Jelly!</s>

Edit: One does not simply beat Jelly...

Explanation

```<code>Polygon
</code>```

Generate a polygon with vertices at the points specified.

```<code>RegionCentroid
</code>```

Find the centroid of the polygon.

Title: Find the Centroid of a Polygon

Body:
Mathematica, 23 bytes

RegionCentroid@*Polygon

<s>Take THAT, Jelly!</s>

Edit: One does not simply beat Jelly...

Explanation

Polygon

Generate a polygon with vertices at the points specified.

RegionCentroid

Find the centroid of the polygon.


问:
Spaced-out numbers
Given a list of N non-negative integers, output those numbers with each left-padded by spaces to a length of N. (Alternatively, return a character/string list.) You may assume that N is greater than or equal to the number of digits of the largest number in the list. Trailing spaces are allowed in the output.

You may also take a string containing these numbers, but N is not the length of the string, but rather the number of elements in the list; also, you may take a list of strings e.g. ["1", "2", "3"].

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

Test cases

```<code>input => 'output'
0 => '0'
1 => '1'
2 3 => ' 2 3'
2 10 => ' 210'
4 5 6 => '  4  5  6'
17 19 20 => ' 17 19 20'
7 8 9 10 => '   7   8   9  10'
100 200 300 0 => ' 100 200 300   0'
1000 400 30 7 => '1000 400  30   7'
1 33 333 7777 => '   1  33 3337777'
0 0 0 0 0 0 => '     0     0     0     0     0     0'
</code>```

答:
C#, 39 bytes

```<code>s=>s.ConvertAll(c=>c.PadLeft(s.Count));
</code>```

Takes a List<string> and outputs a List<string>.

Explanation:

```<code>/*Func<List<string>, List<string>> Lambda =*/ s =>
    s.ConvertAll(c =>                                // Create a new List<string> by...
        c.PadLeft(s.Count)                           // ...padding each element by 'N'
    )
;
</code>```

Would've been a few bytes shorter to use LINQ if the import isn't counted and then returning IEnumerable<string> instead of a full blown list:

C#, 35+18 = 53 bytes

```<code>using System.Linq;s=>s.Select(c=>c.PadLeft(s.Count));
</code>```

Title: Spaced-out numbers

Body:
C#, 39 bytes

s=>s.ConvertAll(c=>c.PadLeft(s.Count));

Takes a List<string> and outputs a List<string>.

Explanation:

/*Func<List<string>, List<string>> Lambda =*/ s =>
    s.ConvertAll(c =>                                // Create a new List<string> by...
        c.PadLeft(s.Count)                           // ...padding each element by 'N'
    )
;

Would've been a few bytes shorter to use LINQ if the import isn't counted and then returning IEnumerable<string> instead of a full blown list:

C#, 35+18 = 53 bytes

using System.Linq;s=>s.Select(c=>c.PadLeft(s.Count));


问:
N(e(s(t))) a string
To "function nest" a string, you must:

Treat the first character as a function, and the following characters as the arguments to that function. For example, if the input string was Hello, then the first step would be:

```<code>H(ello)
</code>```

Then, repeat this same step for every substring. So we get:

```<code>H(ello)
H(e(llo))
H(e(l(lo)))
H(e(l(l(o))))
</code>```

Your task is to write a program or function that "function nests" a string. For example, if the input string was Hello world!, then you should output:

```<code>H(e(l(l(o( (w(o(r(l(d(!)))))))))))
</code>```

The input will only ever contain printable ASCII, and you may take the input and the output in any reasonable format. For example, STDIN/STDOUT, function arguments and return value, reading and writing to a file, etc.

For simplicity's sake, you may also assume the input will not contain parentheses, and will not be empty.

```<code>Input:
Nest a string
Output:
N(e(s(t( (a( (s(t(r(i(n(g))))))))))))

Input:
foobar
Output:
f(o(o(b(a(r)))))

Input:
1234567890
Output:
1(2(3(4(5(6(7(8(9(0)))))))))

Input:
code-golf
Output:
c(o(d(e(-(g(o(l(f))))))))

Input:
a
Output:
a

Input:
42
Output:
4(2)
</code>```

As usual, all of our default rules and loopholes apply, and the shortest answer scored in bytes wins!

答:
C#, 32 bytes

```<code>F=s=>*s+++(0<*s?$"({F(s)})":"");
</code>```

This lambda must be a static method, would I need to count any extra bytes for that requirement? Normally I wouldn't use a lambda for recursion in C#, but then I think it would be shorter not to use recursion.

```<code>/*unsafe delegate string Function(char* s);*/ // Lambda signature
/*static unsafe Function*/ F = s =>
    *s++                               // Take first char and increment pointer to next one
    + (0 < *s                          // Check if any chars left
        ? $"({F(s)})"                  // If so concat surrounding parens around recursion
        : ""                           // Otherwise done
    )
;
</code>```

Title: N(e(s(t))) a string

Body:
C#, 32 bytes

F=s=>*s+++(0<*s?$"({F(s)})":"");

This lambda must be a static method, would I need to count any extra bytes for that requirement? Normally I wouldn't use a lambda for recursion in C#, but then I think it would be shorter not to use recursion.

/*unsafe delegate string Function(char* s);*/ // Lambda signature
/*static unsafe Function*/ F = s =>
    *s++                               // Take first char and increment pointer to next one
    + (0 < *s                          // Check if any chars left
        ? $"({F(s)})"                  // If so concat surrounding parens around recursion
        : ""                           // Otherwise done
    )
;


答:
Brain-Flak, <s>118</s> 84 + 1 = 85 bytes

Try it online

```<code>([[]]<{({}<>)((((()()()()()){}){}){})<>}>()){({}()<(<>({})<>())>)}{}<>{}{({}<>)<>}<>
</code>```

This requires the -fc flag to run giving it an extra byte.  -f flag is standard for passing input.

Explanation

```<code>([[]]<        #Store a copy of the stack height before hand in the scope
 {            #While there is something on the stack...
  ({}<>)      #Move something over and...
  ((((()()()()()){}){}){}) #Put a paren on top
  <>          #Swap back
}
>())          #Put the 1-stack height down
{             #While that is not zero
 ({}()<       #Add one and
  (<>({})<>())#Silently move a copy of the top of the other stack over (close paren)
 >)
}{}
<>{}          #Remove extra open paren
{({}<>)<>}<>  #Combine the two stacks
</code>```

Title: N(e(s(t))) a string

Body:
To "function nest" a string, you must:

Treat the first character as a function, and the following characters as the arguments to that function. For example, if the input string was Hello, then the first step would be:

```<code>H(ello)
</code>```

Then, repeat this same step for every substring. So we get:

```<code>H(ello)
H(e(llo))
H(e(l(lo)))
H(e(l(l(o))))
</code>```

Your task is to write a program or function that "function nests" a string. For example, if the input string was Hello world!, then you should output:

```<code>H(e(l(l(o( (w(o(r(l(d(!)))))))))))
</code>```

The input will only ever contain printable ASCII, and you may take the input and the output in any reasonable format. For example, STDIN/STDOUT, function arguments and return value, reading and writing to a file, etc.

For simplicity's sake, you may also assume the input will not contain parentheses, and will not be empty.

```<code>Input:
Nest a string
Output:
N(e(s(t( (a( (s(t(r(i(n(g))))))))))))

Input:
foobar
Output:
f(o(o(b(a(r)))))

Input:
1234567890
Output:
1(2(3(4(5(6(7(8(9(0)))))))))

Input:
code-golf
Output:
c(o(d(e(-(g(o(l(f))))))))

Input:
a
Output:
a

Input:
42
Output:
4(2)
</code>```

As usual, all of our default rules and loopholes apply, and the shortest answer scored in bytes wins!

Body:
Brain-Flak, <s>118</s> 84 + 1 = 85 bytes

Try it online

([[]]<{({}<>)((((()()()()()){}){}){})<>}>()){({}()<(<>({})<>())>)}{}<>{}{({}<>)<>}<>

This requires the -fc flag to run giving it an extra byte.  -f flag is standard for passing input.

Explanation

([[]]<        #Store a copy of the stack height before hand in the scope
 {            #While there is something on the stack...
  ({}<>)      #Move something over and...
  ((((()()()()()){}){}){}) #Put a paren on top
  <>          #Swap back
}
>())          #Put the 1-stack height down
{             #While that is not zero
 ({}()<       #Add one and
  (<>({})<>())#Silently move a copy of the top of the other stack over (close paren)
 >)
}{}
<>{}          #Remove extra open paren
{({}<>)<>}<>  #Combine the two stacks


答:
Turtlèd, <s>25</s> 27 bytes

(original didn't work for single char inputs ;_;)

This is what Turtlèd ended up being for even though it as originally ascii art stuff.

```<code>!-l[*+.r'(r_]l-_[*-')r_]"  [2 trailing spaces]
</code>```

Try it online!

Explanation:

```<code>put the input on to the cells with ( after each char

!                        Take a string as input
 -                       decrement the string pointer, so it points at last char
  l                      move left
   [*       ]            while the current cell is not *
     +.r                 increment string pointer and write the pointed char, move right
        '(r              write (, move right
           _             write * if pointed char is last char, else " "

Write the terminating parens, the first one overwriting the last open paren

             l-           move left, decrement string pointer
               _          write * if pointed char is last char, else " "
                [*     ]  while the current cell is not *
                  -')r    decrement string pointer, write ), move right
                      _   write * if pointed char is last char, else " "

                        "[2 spaces]  Remove the last *, or two *s if input is one char
</code>```

Title: N(e(s(t))) a string

Body:
Turtlèd, <s>25</s> 27 bytes

(original didn't work for single char inputs ;_;)

This is what Turtlèd ended up being for even though it as originally ascii art stuff.

!-l[*+.r'(r_]l-_[*-')r_]"  [2 trailing spaces]

Try it online!

Explanation:

put the input on to the cells with ( after each char

!                        Take a string as input
 -                       decrement the string pointer, so it points at last char
  l                      move left
   [*       ]            while the current cell is not *
     +.r                 increment string pointer and write the pointed char, move right
        '(r              write (, move right
           _             write * if pointed char is last char, else " "

Write the terminating parens, the first one overwriting the last open paren

             l-           move left, decrement string pointer
               _          write * if pointed char is last char, else " "
                [*     ]  while the current cell is not *
                  -')r    decrement string pointer, write ), move right
                      _   write * if pointed char is last char, else " "

                        "[2 spaces]  Remove the last *, or two *s if input is one char


答:
Racket 195 bytes

```<code>(let p((r "")(l(reverse(string->list s)))(i 0))(cond[(= i(length l))r][(= i 0)(set! r(string(list-ref l i)))
(p r l(+ 1 i))][(set! r(string-append(string(list-ref l i))"("r")" ))(p r l(+ 1 i))]))
</code>```

Ungolfed:

```<code>(define (f s)
  (let loop ((r "")
             (l (reverse (string->list s)))
             (i 0))
    (cond
      [(>= i (length l)) r]
      [(= i 0) (set! r (string (list-ref l i)))
               (loop r l (add1 i))]
      [else (set! r (string-append (string (list-ref l i)) "(" r ")" ))
            (loop r l (add1 i))]
      )))
</code>```

Testing:

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

Output:

```<code>"H(e(l(l(o))))"
</code>```

Edit: 2 bytes saved following suggestion by @JonathanFrech (add1 to + 1)

Title: N(e(s(t))) a string

Body:
Racket 195 bytes

(let p((r "")(l(reverse(string->list s)))(i 0))(cond[(= i(length l))r][(= i 0)(set! r(string(list-ref l i)))
(p r l(+ 1 i))][(set! r(string-append(string(list-ref l i))"("r")" ))(p r l(+ 1 i))]))

Ungolfed:

(define (f s)
  (let loop ((r "")
             (l (reverse (string->list s)))
             (i 0))
    (cond
      [(>= i (length l)) r]
      [(= i 0) (set! r (string (list-ref l i)))
               (loop r l (add1 i))]
      [else (set! r (string-append (string (list-ref l i)) "(" r ")" ))
            (loop r l (add1 i))]
      )))

Testing:

(f "Hello")

Output:

"H(e(l(l(o))))"

Edit: 2 bytes saved following suggestion by @JonathanFrech (add1 to + 1)

ContentLicense: CC BY-SA 4.0


答:
Python 3, 40 chars

```<code>s=input()
print("(".join(s)+len(s)*")")
</code>```

Title: N(e(s(t))) a string

Body:
Python 3, 40 chars

s=input()
print("(".join(s)+len(s)*")")


问:
Chebyshev Rotation
Consider a regular grid, where each cell has integer coordinates. We can group the cells into (square-shaped) "rings" where the cells in each ring have the same Chebyshev distance (or chessboard distance) from the origin. Your task is to take such a cell coordinate and rotate that cell by one position counter-clockwise within its ring. This implements the following mapping:

So for example if the input is (3, -2) you should output (3, -1). Note that (0, 0) is the only input that should map to itself.

Rules

The I/O format is fairly flexible. You can use two individual numbers, a pair/list/array/tuple of numbers, a single complex number, a string containing two numbers, etc.

You may assume that -128 < x,y < 128.

You may write a program or a function and use any of the our standard methods of receiving input and providing output.

You may use any programming language, but note that these loopholes are forbidden by default.

This is code-golf, so the shortest valid answer – measured in bytes – wins.

Test Cases

```<code>(0, 0)       => (0, 0)
(1, 0)       => (1, 1)
(1, 1)       => (0, 1)
(0, 1)       => (-1, 1)
(-1, 1)      => (-1, 0)
(-1, 0)      => (-1, -1)
(-1, -1)     => (0, -1)
(0, -1)      => (1, -1)
(1, -1)      => (1, 0)
(95, -12)    => (95, -11)
(127, 127)   => (126, 127)
(-2, 101)    => (-3, 101)
(-65, 65)    => (-65, 64)
(-127, 42)   => (-127, 41)
(-9, -9)     => (-8, -9)
(126, -127)  => (127, -127)
(105, -105)  => (105, -104)
</code>```

答:
JavaScript (ES6), 57 bytes (55–63†)

Accepts an [x, y] array, modifies it in-place, and returns it.

```<code>c=>([x,y]=c,i=x>y|x==y&x<0,c[i^x<-y|x==-y]-=-i|!!(x|y),c)
</code>```

How it works

```<code>c=>(
</code>```

This is a single-parameter arrow function with a return-free concise body.

```<code>[x,y]=c
</code>```

The parameter is immediately destructured into x and y variables.

```<code>,
</code>```

The comma operator combines multiple expressions into one, using the result of the last.

```<code>i=x>y|x==y&x<0
</code>```

i is used for differentiating increment and decrement cases. When x is greater than y, we are in either the bottom or right quadrant, and need to advance in one dimension (i=1 by boolean-to-number coercion). Likewise when we are on the negative portion of the dividing x = y diagonal. In all other cases—including the origin—no increment is required (i=0).

```<code>c[i^x<-y|x==-y]
</code>```

We use a somewhat similar expression for controlling which array index to adjust. When we are incrementing and not in the left or bottom quadrants (or when we are not incrementing and in the left or bottom), then the bitwise XOR will produce 1 and we will adjust the y value. Likewise for when we are on the dividing x = -y diagonal (including the origin). In all other cases, the index will be 0 (x).

```<code>-=-i|!!(x|y)
</code>```

When i is 1, we will add it to the specified value. When i is 0, we will subtract 1 from the value if and only if we are not at the origin. The latter is detected by x|y yielding nonzero, clipped to {0, 1} by boolean coercion, and the negation of i allows us to use bitwise OR instead of logical (since -1 has no zero bits, it is safe from modification).

```<code>c
</code>```

The array is last, so it will be returned.

Testing

let f =
    c=>([x,y]=c,i=x>y|x==y&x<0,c[i^x<-y|x==-y]-=-i|!!(x|y),c)

let cases = `
(0, 0)       => (0, 0)
(1, 0)       => (1, 1)
(1, 1)       => (0, 1)
(0, 1)       => (-1, 1)
(-1, 1)      => (-1, 0)
(-1, 0)      => (-1, -1)
(-1, -1)     => (0, -1)
(0, -1)      => (1, -1)
(1, -1)      => (1, 0)
(95, -12)    => (95, -11)
(127, 127)   => (126, 127)
(-2, 101)    => (-3, 101)
(-65, 65)    => (-65, 64)
(-127, 42)   => (-127, 41)
(-9, -9)     => (-8, -9)
(126, -127)  => (127, -127)
(105, -105)  => (105, -104)
`;

let failures = cases.trim().split("\n").filter(l => {
    const FAIL = true;
    let m = /.*?(-?\d+).*?(-?\d+).*?(-?\d+).*?(-?\d+)/.exec(l);
    if (!m) return FAIL;
    let [_, x, y, X, Y] = m;
    let [x2, y2] = f([+x, +y]);
    if (x2==X && y2==Y) return !FAIL;
    console.log("(%s) yielded (%s); expected (%s)", [x, y], [x2, y2], [X, Y]);
    return FAIL;
});
console.log("failures: " + failures.length);
// => failures: 0```
</div>
</div>
</p>

<h2>†Variations</h2>

<p>We can save two more bytes by skipping a meaningful return value and using <em>only</em> the input mutation:</p>

```c=>([x,y]=c,i=x>y|x==y&x<0,c[i^x<-y|x==-y]-=-i|!!(x|y))
```

<p>…or we can skip input mutation and make all variables local for a pure function, at the cost of six bytes:</p>

```([x,y],i=x>y|x==y&x<0,c=[x,y])=>(c[i^x<-y|x==-y]-=-i|!!(x|y),c)
```

Title: Chebyshev Rotation

Body:
JavaScript (ES6), 57 bytes (55–63†)

Accepts an [x, y] array, modifies it in-place, and returns it.

c=>([x,y]=c,i=x>y|x==y&x<0,c[i^x<-y|x==-y]-=-i|!!(x|y),c)

How it works

c=>(

This is a single-parameter arrow function with a return-free concise body.

[x,y]=c

The parameter is immediately destructured into x and y variables.

,

The comma operator combines multiple expressions into one, using the result of the last.

i=x>y|x==y&x<0

i is used for differentiating increment and decrement cases. When x is greater than y, we are in either the bottom or right quadrant, and need to advance in one dimension (i=1 by boolean-to-number coercion). Likewise when we are on the negative portion of the dividing x = y diagonal. In all other cases—including the origin—no increment is required (i=0).

c[i^x<-y|x==-y]

We use a somewhat similar expression for controlling which array index to adjust. When we are incrementing and not in the left or bottom quadrants (or when we are not incrementing and in the left or bottom), then the bitwise XOR will produce 1 and we will adjust the y value. Likewise for when we are on the dividing x = -y diagonal (including the origin). In all other cases, the index will be 0 (x).

-=-i|!!(x|y)

When i is 1, we will add it to the specified value. When i is 0, we will subtract 1 from the value if and only if we are not at the origin. The latter is detected by x|y yielding nonzero, clipped to {0, 1} by boolean coercion, and the negation of i allows us to use bitwise OR instead of logical (since -1 has no zero bits, it is safe from modification).

c

The array is last, so it will be returned.

Testing

let f =
    c=>([x,y]=c,i=x>y|x==y&x<0,c[i^x<-y|x==-y]-=-i|!!(x|y),c)

let cases = `
(0, 0)       => (0, 0)
(1, 0)       => (1, 1)
(1, 1)       => (0, 1)
(0, 1)       => (-1, 1)
(-1, 1)      => (-1, 0)
(-1, 0)      => (-1, -1)
(-1, -1)     => (0, -1)
(0, -1)      => (1, -1)
(1, -1)      => (1, 0)
(95, -12)    => (95, -11)
(127, 127)   => (126, 127)
(-2, 101)    => (-3, 101)
(-65, 65)    => (-65, 64)
(-127, 42)   => (-127, 41)
(-9, -9)     => (-8, -9)
(126, -127)  => (127, -127)
(105, -105)  => (105, -104)
`;

let failures = cases.trim().split("\n").filter(l => {
    const FAIL = true;
    let m = /.*?(-?\d+).*?(-?\d+).*?(-?\d+).*?(-?\d+)/.exec(l);
    if (!m) return FAIL;
    let [_, x, y, X, Y] = m;
    let [x2, y2] = f([+x, +y]);
    if (x2==X && y2==Y) return !FAIL;
    console.log("(%s) yielded (%s); expected (%s)", [x, y], [x2, y2], [X, Y]);
    return FAIL;
});
console.log("failures: " + failures.length);
// => failures: 0

†Variations

We can save two more bytes by skipping a meaningful return value and using only the input mutation:

c=>([x,y]=c,i=x>y|x==y&x<0,c[i^x<-y|x==-y]-=-i|!!(x|y))

…or we can skip input mutation and make all variables local for a pure function, at the cost of six bytes:

([x,y],i=x>y|x==y&x<0,c=[x,y])=>(c[i^x<-y|x==-y]-=-i|!!(x|y),c)


答:
Java, <s>83</s> 82 bytes

a->{String s="";for(int i=a.length,j=i;i-->0;)s+="%"+j+"s";return s.format(s,a);};
```

<p>Constructs a format string designed to pad the given arguments by a number of spaces equal to the length of the array. The format string is used as an argument for <code>String.format</code>, and the result is then returned. The functional interface can accept either a <code>String[]</code> or an <code>Integer[]</code> or similar.</p>

<p>Full class:</p>

<pre class="lang-java prettyprint-override"><code>public class Test {
    public static void main(String[] args) {
        java.util.function.Function<Integer[], String> f = a -> {
            String s = "";
            for (int i = a.length, j = i; i-- > 0;)
                s += "%" + j + "s";
            return s.format(s, a);
        };

        System.out.println(f.apply(new Integer[] {0}));
        System.out.println(f.apply(new Integer[] {2, 10}));
        System.out.println(f.apply(new Integer[] {7, 8, 9, 10}));
        System.out.println(f.apply(new Integer[] {1, 33, 333, 7777}));
        System.out.println(f.apply(new Integer[] {0, 0, 0, 0, 0, 0}));
    }
}
</code>```

Try it on Ideone.

-1 byte thanks to @KevinCruijssen.

Title: Spaced-out numbers

Body:
Given a list of N non-negative integers, output those numbers with each left-padded by spaces to a length of N. (Alternatively, return a character/string list.) You may assume that N is greater than or equal to the number of digits of the largest number in the list. Trailing spaces are allowed in the output.

You may also take a string containing these numbers, but N is not the length of the string, but rather the number of elements in the list; also, you may take a list of strings e.g. ["1", "2", "3"].

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

Test cases

```<code>input => 'output'
0 => '0'
1 => '1'
2 3 => ' 2 3'
2 10 => ' 210'
4 5 6 => '  4  5  6'
17 19 20 => ' 17 19 20'
7 8 9 10 => '   7   8   9  10'
100 200 300 0 => ' 100 200 300   0'
1000 400 30 7 => '1000 400  30   7'
1 33 333 7777 => '   1  33 3337777'
0 0 0 0 0 0 => '     0     0     0     0     0     0'
</code>```

Body:
Java, <s>83</s> 82 bytes

a->{String s="";for(int i=a.length,j=i;i-->0;)s+="%"+j+"s";return s.format(s,a);};

Constructs a format string designed to pad the given arguments by a number of spaces equal to the length of the array. The format string is used as an argument for String.format, and the result is then returned. The functional interface can accept either a String[] or an Integer[] or similar.

Full class:

public class Test {
    public static void main(String[] args) {
        java.util.function.Function<Integer[], String> f = a -> {
            String s = "";
            for (int i = a.length, j = i; i-- > 0;)
                s += "%" + j + "s";
            return s.format(s, a);
        };

        System.out.println(f.apply(new Integer[] {0}));
        System.out.println(f.apply(new Integer[] {2, 10}));
        System.out.println(f.apply(new Integer[] {7, 8, 9, 10}));
        System.out.println(f.apply(new Integer[] {1, 33, 333, 7777}));
        System.out.println(f.apply(new Integer[] {0, 0, 0, 0, 0, 0}));
    }
}

Try it on Ideone.

-1 byte thanks to @KevinCruijssen.


Title: Find the Centroid of a Polygon

Body:
Racket 420 bytes

(let*((lr list-ref)(getx(lambda(i)(lr(lr l i)0)))(gety(lambda(i)(lr(lr l i)1)))(n(length l))(j(λ(i)(if(= i(sub1 n))0(add1 i))))
(A(/(for/sum((i n))(-(*(getx i)(gety(j i)))(*(getx(j i))(gety i))))2))
(cx(/(for/sum((i n))(*(+(getx i)(getx(j i)))(-(*(getx i)(gety(j i)))(*(getx(j i))(gety i)))))(* 6 A)))
(cy(/(for/sum((i n))(*(+(gety i)(gety(j i)))(-(*(getx i)(gety(j i)))(*(getx(j i))(gety i)))))(* 6 A))))
(list cx cy))

Ungolfed:

(define(f l)
  (let* ((lr list-ref)
         (getx (lambda(i)(lr (lr l i)0)))
         (gety (lambda(i)(lr (lr l i)1)))
         (n (length l))
         (j (lambda(i) (if (= i (sub1 n)) 0 (add1 i))))
         (A (/(for/sum ((i n))
                (-(* (getx i) (gety (j i)))
                  (* (getx (j i)) (gety i))))
              2))
         (cx (/(for/sum ((i n))
                 (*(+(getx i)(getx (j i)))
                   (-(*(getx i)(gety (j i)))
                     (*(getx (j i))(gety i)))))
               (* 6 A)))
         (cy (/(for/sum ((i n))
                 (*(+(gety i)(gety (j i)))
                   (-(*(getx i)(gety (j i)))
                     (*(getx (j i))(gety i)))))
               (* 6 A))))
    (list cx cy)))

Testing:

(f '[(-15.21 0.8)  (10.1 -0.3)  (-0.07 23.55)] )
(f '[(-39.00 -55.94)  (-56.08 -4.73)  (-72.64 12.12)  (-31.04 53.58)
     (-30.36 28.29)  (17.96 59.17)  (0.00 0.00)  (10.00 0.00)
     (20.00 0.00) (148.63 114.32)  (8.06 -41.04)  (-41.25 34.43)])

Output:

'(-1.7266666666666677 8.01666666666667)
'(5.8010476997538465 15.067381276150996)


答:
Perl, <s>24</s> 23 bytes

Includes +1 for -p

Give string on STDIN without newline (or add a -l option to the program)

```<code>echo -n Hello | nest.pl
</code>```

nest.pl:

```<code>#!/usr/bin/perl -p
$\=")"x s/.(?=.)/$&(/g
</code>```

Title: N(e(s(t))) a string

Body:
Perl, <s>24</s> 23 bytes

Includes +1 for -p

Give string on STDIN without newline (or add a -l option to the program)

echo -n Hello | nest.pl

nest.pl:

#!/usr/bin/perl -p
$\=")"x s/.(?=.)/$&(/g


答:
Zsh, 36 Bytes

```<code>z=${1:1};<<<${1[1]}${z///(}${z//?/)}
</code>```

This should be possible in 34 bytes, but zsh syntax is inconsistent. $a[1] will return the first character of the string $a, but $1[1] returns the entire contents of $1 plus the string "[1]". I'd love to know if this is intended behavior, or just on a long list of zsh documentation not covering edge cases.

The logic used is

Assign all but the first character of the first argument to a variable z

Print the first character of the input

Print z, with "the empty string replaced with (" which actually places a ( before each character of z

Print z, with all of the characters replaced with )

I don't think its golfable much farther from here, even though I how many characters it takes to just split the first character from the rest of the string. There is probably a more efficient "logic" though, I just couldn't find one that synergizes with zsh or bash.

Speaking of bash, this doesn't work because the cute trick with sed-style replacing the empty string does not do anything in bash. I will edit with a solution that is better designed for bash-compatible syntax.

Title: N(e(s(t))) a string

Body:
Zsh, 36 Bytes

z=${1:1};<<<${1[1]}${z///(}${z//?/)}

This should be possible in 34 bytes, but zsh syntax is inconsistent. $a[1] will return the first character of the string $a, but $1[1] returns the entire contents of $1 plus the string "[1]". I'd love to know if this is intended behavior, or just on a long list of zsh documentation not covering edge cases.

The logic used is

Assign all but the first character of the first argument to a variable z

Print the first character of the input

Print z, with "the empty string replaced with (" which actually places a ( before each character of z

Print z, with all of the characters replaced with )

I don't think its golfable much farther from here, even though I how many characters it takes to just split the first character from the rest of the string. There is probably a more efficient "logic" though, I just couldn't find one that synergizes with zsh or bash.

Speaking of bash, this doesn't work because the cute trick with sed-style replacing the empty string does not do anything in bash. I will edit with a solution that is better designed for bash-compatible syntax.


问:
Appease Your Google Overlords: Draw the "G" Logo
Write a program or function that takes in a positive integer N, and outputs an N×N pixel image of Google's "G" logo according to this* construction:

For example, if N is 400, a 400×400 pixel logo should be output, with correct dimensions and colors:

It should look accurate regardless of how large or small N is. e.g. here is N = 13:

Your code should not need to connect to the internet. For example, scaling an externally hosted svg is not allowed. (Scaling an svg encoded in your code would be fine though.)

Anti-aliasing may be used or not. It's up to you.

Notice that the horizontal bar of the "G" does not extend all the way to the right edge of the image. The circle curves normally inward on the right edge before it is cut off.

The shortest code in bytes wins.

* The construction of the logo has been simplified for this challenge. The correct construction can be seen here and here.

答:
Go, 379 bytes

import ."fmt"
func f(a int)(s string){
m:=map[string]float64{"fbbc05":-45,"ea4335":45,"4285f4":168.5,"34a853":225}
for k,v:=range m{s+=Sprintf("<use xlink:href=#c fill=#%v transform=rotate(%v,5,5) />",k,v)}
return Sprintf("<svg width=%v viewBox=0,0,10,10><def><path id=c d=M0,5A5,5,0,0,1,5,0V2A3,3,0,0,0,2,5 /></def>%v<rect x=5 y=4 fill=#4285f4 width=4.9 height=2 /></svg>",a,s)}
```
<p>The function <code>f</code> takes a single <code>int</code> argument (the scale factor) and outputs an SVG image scaled appropriately.</p>
<p>Try it online at Ideone.</p>
<p>Example output:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><svg width=333 viewBox=0,0,10,10><def><path id=c d=M0,5A5,5,0,0,1,5,0V2A3,3,0,0,0,2,5 /></def><use xlink:href=#c fill=#34a853 transform=rotate(225,5,5) /><use xlink:href=#c fill=#fbbc05 transform=rotate(-45,5,5) /><use xlink:href=#c fill=#ea4335 transform=rotate(45,5,5) /><use xlink:href=#c fill=#4285f4 transform=rotate(168.5,5,5) /><rect x=5 y=4 fill=#4285f4 width=4.9 height=2 /></svg></code>```

It seems wrong to appease our Google overlords in any programming language except their own.

Body:
Go, 379 bytes

import ."fmt"
func f(a int)(s string){
m:=map[string]float64{"fbbc05":-45,"ea4335":45,"4285f4":168.5,"34a853":225}
for k,v:=range m{s+=Sprintf("<use xlink:href=#c fill=#%v transform=rotate(%v,5,5) />",k,v)}
return Sprintf("<svg width=%v viewBox=0,0,10,10><def><path id=c d=M0,5A5,5,0,0,1,5,0V2A3,3,0,0,0,2,5 /></def>%v<rect x=5 y=4 fill=#4285f4 width=4.9 height=2 /></svg>",a,s)}

The function f takes a single int argument (the scale factor) and outputs an SVG image scaled appropriately.

Try it online at Ideone.

Example output:

<svg width=333 viewBox=0,0,10,10><def><path id=c d=M0,5A5,5,0,0,1,5,0V2A3,3,0,0,0,2,5 /></def><use xlink:href=#c fill=#34a853 transform=rotate(225,5,5) /><use xlink:href=#c fill=#fbbc05 transform=rotate(-45,5,5) /><use xlink:href=#c fill=#ea4335 transform=rotate(45,5,5) /><use xlink:href=#c fill=#4285f4 transform=rotate(168.5,5,5) /><rect x=5 y=4 fill=#4285f4 width=4.9 height=2 /></svg>

It seems wrong to appease our Google overlords in any programming language except their own.


答:
R, 47 bytes

```<code>cat(sprintf("%*.f",length(n<-scan()),n),sep="")
</code>```

Reads input from stdin and uses C-style formating with sprintf. There should be some way the cat function is not needed but couldn't find a way to suppress the quotes on each element without it. If we only want start and end quotes we could use the slightly longer option:

```<code>paste0(sprintf("%*.f",length(n<-scan()),n),collapse="")
</code>```

Title: Spaced-out numbers

Body:
R, 47 bytes

cat(sprintf("%*.f",length(n<-scan()),n),sep="")

Reads input from stdin and uses C-style formating with sprintf. There should be some way the cat function is not needed but couldn't find a way to suppress the quotes on each element without it. If we only want start and end quotes we could use the slightly longer option:

paste0(sprintf("%*.f",length(n<-scan()),n),collapse="")


答:
Acc!!, 129 bytes

Not bad for a fairly verbose Turing tarpit...

```<code>N
Count i while _%128-9 {
Count x while _/128%2 {
Write 40
_+128
}
Write _%128
_+128-_%128+N
}
Count j while _/256-j {
Write 41
}
</code>```

(Yes, all that whitespace is mandatory.)

Note: because of the input limitations of Acc!!, it is impossible to read an arbitrary string of characters without some ending delimiter. Therefore, this program expects input (on stdin) as a string followed by a tab character.

Acc!!?

It's a language I created that only appears to be unusable. The only data type is integers, the only control flow construct is the Count x while y loop, and the only way to store data is a single accumulator _. Input and output are done one character at a time, using the special value N and the Write statement. Despite these limitations, I'm quite sure that Acc!! is Turing-complete.

Explanation

The basic strategy in Acc!! programming is to use mod % and integer division / to conceptually partition the accumulator, allowing it to store multiple values at once. In this program, we use three such sections: the lowest-order seven bits (_%128) store an ASCII code from input; the next bit (_/128%2) stores a flag value; and the remaining bits (_/256) count the number of close-parens we will need.

Input in Acc!! comes from the special value N, which reads a single character and evaluates to its ASCII code. Any statement that consists solely of an expression assigns the result of that expression to the accumulator. So we start by storing the first character's code in the accumulator.

_%128 will store the most recently read character. So the first loop runs while _%128-9 is nonzero--that is, until the current character is a tab.

Inside the loop, we want to print ( unless we're on the first iteration. Since Acc!! has no if statement, we have to use loops for conditionals. We use the 128's bit of the accumulator, _/128%2, as a flag value. On the first pass, the only thing in the accumulator is an ASCII value < 128, so the flag is 0 and the loop is skipped. On every subsequent pass, we will make sure the flag is 1.

Inside the Count x loop (whenever the flag is 1), we write an open paren (ASCII 40) and add 128 to the accumulator, thereby setting the flag to 0 and exiting the loop. This also happens to increment the value of _/256, which we will use as our tally of close-parens to be output.

Regardless of the flag's value, we write the most recent input char, which is simply _%128.

The next assignment (_+128-_%128+N) does two things. First, by adding 128, it sets the flag for the next time through the loop. Second, it zeros out the _%128 slot, reads another character, and stores it there. Then we loop.

When the Count i loop exits, we have just read a tab character, and the accumulator value breaks down like this:

_%128: 9 (the tab character)

_/128%2: 1 (the flag)

_/256: number of characters read, minus 1

(The minus 1 is because we only add 128 to the accumulator once during the first pass through the main loop.) All that we need now are the close-parens. Count j while _/256-j loops _/256 times, writing a close-paren (ASCII 41) each time. Voila!

Title: N(e(s(t))) a string

Body:
Acc!!, 129 bytes

Not bad for a fairly verbose Turing tarpit...

N
Count i while _%128-9 {
Count x while _/128%2 {
Write 40
_+128
}
Write _%128
_+128-_%128+N
}
Count j while _/256-j {
Write 41
}

(Yes, all that whitespace is mandatory.)

Note: because of the input limitations of Acc!!, it is impossible to read an arbitrary string of characters without some ending delimiter. Therefore, this program expects input (on stdin) as a string followed by a tab character.

Acc!!?

It's a language I created that only appears to be unusable. The only data type is integers, the only control flow construct is the Count x while y loop, and the only way to store data is a single accumulator _. Input and output are done one character at a time, using the special value N and the Write statement. Despite these limitations, I'm quite sure that Acc!! is Turing-complete.

Explanation

The basic strategy in Acc!! programming is to use mod % and integer division / to conceptually partition the accumulator, allowing it to store multiple values at once. In this program, we use three such sections: the lowest-order seven bits (_%128) store an ASCII code from input; the next bit (_/128%2) stores a flag value; and the remaining bits (_/256) count the number of close-parens we will need.

Input in Acc!! comes from the special value N, which reads a single character and evaluates to its ASCII code. Any statement that consists solely of an expression assigns the result of that expression to the accumulator. So we start by storing the first character's code in the accumulator.

_%128 will store the most recently read character. So the first loop runs while _%128-9 is nonzero--that is, until the current character is a tab.

Inside the loop, we want to print ( unless we're on the first iteration. Since Acc!! has no if statement, we have to use loops for conditionals. We use the 128's bit of the accumulator, _/128%2, as a flag value. On the first pass, the only thing in the accumulator is an ASCII value < 128, so the flag is 0 and the loop is skipped. On every subsequent pass, we will make sure the flag is 1.

Inside the Count x loop (whenever the flag is 1), we write an open paren (ASCII 40) and add 128 to the accumulator, thereby setting the flag to 0 and exiting the loop. This also happens to increment the value of _/256, which we will use as our tally of close-parens to be output.

Regardless of the flag's value, we write the most recent input char, which is simply _%128.

The next assignment (_+128-_%128+N) does two things. First, by adding 128, it sets the flag for the next time through the loop. Second, it zeros out the _%128 slot, reads another character, and stores it there. Then we loop.

When the Count i loop exits, we have just read a tab character, and the accumulator value breaks down like this:

_%128: 9 (the tab character)

_/128%2: 1 (the flag)

_/256: number of characters read, minus 1

(The minus 1 is because we only add 128 to the accumulator once during the first pass through the main loop.) All that we need now are the close-parens. Count j while _/256-j loops _/256 times, writing a close-paren (ASCII 41) each time. Voila!


答:
Haskell, 47 bytes

```<code>k=length
f l=map(\s->replicate(k l-k s)' '++s)l
</code>```

That’s a function from a list of strings to a list of strings, like the JavaScript answers. replicate allows one to get a list (Haskell strings are lists of characters) of a given size, so I use it — and the bolded assumption in the problem — to generate the padding (its length is N − <length of element>, for each element of the input list). I would have preferred to use a printf based solution rather than this one with replicate (it would have been shorter, for one thing) but the import statement kills any savings done on the function itself.

Title: Spaced-out numbers

Body:
Haskell, 47 bytes

k=length
f l=map(\s->replicate(k l-k s)' '++s)l

That’s a function from a list of strings to a list of strings, like the JavaScript answers. replicate allows one to get a list (Haskell strings are lists of characters) of a given size, so I use it — and the bolded assumption in the problem — to generate the padding (its length is N − <length of element>, for each element of the input list). I would have preferred to use a printf based solution rather than this one with replicate (it would have been shorter, for one thing) but the import statement kills any savings done on the function itself.


答:
JavaScript (ES6), 47

Anonymous function, input: array of strings, output: array of strings

Using a recursive padding function

a=>a.map(x=>p(x),p=x=>x[a.length-1]?x:p(' '+x))
```
<p>For an integer/string array as input, 49 bytes:</p>
<pre class="lang-js prettyprint-override"><code>a=>a.map(x=>p(x),p=x=>(y=' '+x)[a.length]?x:p(y))
</code>```

Test

f=
a=>a.map(x=>p(x),p=x=>x[a.length-1]?x:p(' '+x))

function update() {
  var l=I.value.match(/\d+/g)||[]
  O.textContent = f(l)
}

update()
 ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input id=I oninput='update()' value='1000,400,30,7'>
<pre id=O>``````

Title: Spaced-out numbers

Body:
JavaScript (ES6), 47

Anonymous function, input: array of strings, output: array of strings

Using a recursive padding function

a=>a.map(x=>p(x),p=x=>x[a.length-1]?x:p(' '+x))

For an integer/string array as input, 49 bytes:

a=>a.map(x=>p(x),p=x=>(y=' '+x)[a.length]?x:p(y))

Test

f=
a=>a.map(x=>p(x),p=x=>x[a.length-1]?x:p(' '+x))

function update() {
  var l=I.value.match(/\d+/g)||[]
  O.textContent = f(l)
}

update()

<input id=I oninput='update()' value='1000,400,30,7'>
<pre id=O></pre>


问:
Nest a string inside an array n times
You must produce a function which nests a string s inside an array, n times

```<code>>>> N("stackoverflow",2)
[['stackoverflow']]
</code>```

Parameters:

s - An ascii string

n - An integer >= 0

Rules

Shortest code wins.

The output will be a nested array, list or tuple (or similar type based off an array)

Test Cases

```<code>>>> N("stackoverflow",0)
'stackoverflow'
>>> N("stackoverflow",1)
['stackoverflow']
>>> N("stackoverflow",5)
[[[[['stackoverflow']]]]]
</code>```

Inspired by: Nesting a string inside a list n times ie list of a list of a list

答:
tinylisp (repl), 34 bytes

```<code>(d F(q((S N)(i N(F(c S())(s N 1))S
</code>```

Defines a function F. Technically, tinylisp doesn't have strings, but this code will work for any data type it's given.

Ungolfed (key to builtins: d = define, q = quote, i = if, c = cons, s = subtract):

```<code>(d nest
 (q
  ((item number)
   (i number
    (nest (c item ()) (s number 1))
    item))))
</code>```

Example usage:

```<code>tl> (d F(q((S N)(i N(F(c S())(s N 1))S
F
tl> (F 2 3)
(((2)))
tl> (F () 1)
(())
tl> (F (q Hello!) 7)
(((((((Hello!)))))))
tl> (F c 3)
(((<builtin function tl_cons>)))
</code>```

Title: Nest a string inside an array n times

Body:
tinylisp (repl), 34 bytes

(d F(q((S N)(i N(F(c S())(s N 1))S

Defines a function F. Technically, tinylisp doesn't have strings, but this code will work for any data type it's given.

Ungolfed (key to builtins: d = define, q = quote, i = if, c = cons, s = subtract):

(d nest
 (q
  ((item number)
   (i number
    (nest (c item ()) (s number 1))
    item))))

Example usage:

tl> (d F(q((S N)(i N(F(c S())(s N 1))S
F
tl> (F 2 3)
(((2)))
tl> (F () 1)
(())
tl> (F (q Hello!) 7)
(((((((Hello!)))))))
tl> (F c 3)
(((<builtin function tl_cons>)))


答:
Gema, <s>31</s> 13 characters

Shamelessly borrowing Titus's idea from his recursive PHP solution.

```<code>\B?=?
?#=(?#)
</code>```

Sample run:

```<code>bash-4.3$ echo -n 'Hello world!' | gema '\B?=?;?#=(?#)'
H(e(l(l(o( (w(o(r(l(d(!)))))))))))
</code>```

Title: N(e(s(t))) a string

Body:
To "function nest" a string, you must:

Treat the first character as a function, and the following characters as the arguments to that function. For example, if the input string was Hello, then the first step would be:

```<code>H(ello)
</code>```

Then, repeat this same step for every substring. So we get:

```<code>H(ello)
H(e(llo))
H(e(l(lo)))
H(e(l(l(o))))
</code>```

Your task is to write a program or function that "function nests" a string. For example, if the input string was Hello world!, then you should output:

```<code>H(e(l(l(o( (w(o(r(l(d(!)))))))))))
</code>```

The input will only ever contain printable ASCII, and you may take the input and the output in any reasonable format. For example, STDIN/STDOUT, function arguments and return value, reading and writing to a file, etc.

For simplicity's sake, you may also assume the input will not contain parentheses, and will not be empty.

```<code>Input:
Nest a string
Output:
N(e(s(t( (a( (s(t(r(i(n(g))))))))))))

Input:
foobar
Output:
f(o(o(b(a(r)))))

Input:
1234567890
Output:
1(2(3(4(5(6(7(8(9(0)))))))))

Input:
code-golf
Output:
c(o(d(e(-(g(o(l(f))))))))

Input:
a
Output:
a

Input:
42
Output:
4(2)
</code>```

As usual, all of our default rules and loopholes apply, and the shortest answer scored in bytes wins!

Body:
Gema, <s>31</s> 13 characters

Shamelessly borrowing Titus's idea from his recursive PHP solution.

\B?=?
?#=(?#)

Sample run:

bash-4.3$ echo -n 'Hello world!' | gema '\B?=?;?#=(?#)'
H(e(l(l(o( (w(o(r(l(d(!)))))))))))


问:
Expand an encoded string
There's the classic run length encoding and decoding.

```<code>input   output
a3b2c5  aaabbccccc
</code>```

And that's fairly straight forward and done before.

The challenge is to also account for a non-standard behavior when multiple characters precede the run length (a single digit from 0-9). Each character before the run length digit (the last digit before a non-digit or end of the string) has that value applied to it individually and printed out in order.

Some test input and output including some edge cases:

```<code>input   output
ab3c5   aaabbbccccc
a0b3    bbb
13b1    111b
a13b1   aaa111b
a123b1  aaa111222b
aa2a1b1 aaaaab
</code>```

A character sequence ([a-zA-Z0-9]+) must be followed by its run length length ([0-9])

Only valid input needs to be considered (([a-zA-Z0-9]+[0-9])*)

yes, empty string is valid input.

Input is via standard input, output via standard output

This is code golf, number of bytes determines the winner.

答:
Java 7, 175 bytes

```<code>String c(String s){String r="",a[];for(String x:s.split("(?<=(\\d)(?!\\d))")){a=x.split("");for(int i=0,j,l=a.length-1;i<l;i++)for(j=0;j++<new Short(a[l]);r+=a[i]);}return r;}
</code>```

The challenge is harder than it looks, imo..

Ungolfed & test code:

Try it here.

```<code>class M{
  static String c(String s){
    String r = "",
           a[];
    for(String x : s.split("(?<=(\\d)(?!\\d))")){
      a = x.split("");
      for(int i = 0, j, l = a.length-1; i < l; i++){
        for(j = 0; j++ < new Short(a[l]); r += a[i]);
      }
    }
    return r;
  }

  public static void main(String[] a){
    System.out.println(c("ab3c5"));
    System.out.println(c("a0b3"));
    System.out.println(c("13b1"));
    System.out.println(c("a13b1"));
    System.out.println(c("a123b1"));
    System.out.println(c("aa2a1b1"));
    System.out.println(c("123"));
  }
}
</code>```

Output:

```<code>aaabbbccccc
bbb
111b
aaa111b
aaa111222b
aaaaab
111222
</code>```

Title: Expand an encoded string

Body:
Java 7, 175 bytes

String c(String s){String r="",a[];for(String x:s.split("(?<=(\\d)(?!\\d))")){a=x.split("");for(int i=0,j,l=a.length-1;i<l;i++)for(j=0;j++<new Short(a[l]);r+=a[i]);}return r;}

The challenge is harder than it looks, imo..

Ungolfed & test code:

Try it here.

class M{
  static String c(String s){
    String r = "",
           a[];
    for(String x : s.split("(?<=(\\d)(?!\\d))")){
      a = x.split("");
      for(int i = 0, j, l = a.length-1; i < l; i++){
        for(j = 0; j++ < new Short(a[l]); r += a[i]);
      }
    }
    return r;
  }

  public static void main(String[] a){
    System.out.println(c("ab3c5"));
    System.out.println(c("a0b3"));
    System.out.println(c("13b1"));
    System.out.println(c("a13b1"));
    System.out.println(c("a123b1"));
    System.out.println(c("aa2a1b1"));
    System.out.println(c("123"));
  }
}

Output:

aaabbbccccc
bbb
111b
aaa111b
aaa111222b
aaaaab
111222


问:
Division of not so little numbers
Write a program or function that takes in positive integers a, b and c, and prints or returns a/b to c decimal places, using the operations +-*/% [add, subtract, multiply, divide, modulate] on the positive integers: you can use all that your language allows, but not on floating point numbers. The range of a,b,c would be the range allowed for unsigned integers in your language.
The number result will be truncated to the last digit to print (so no round).

This means that if your language does not have an integer type (only float), you can participate by using these float numbers as positive integers only.
The clue of this exercise it would be to write the function that find the
digits in a float point division, using only the operation +-*/%  on
[unsigned] integers.

Examples

print(1,2,1) would print 0.5

print(1,2,2) would print 0.50

print(13,7,27) would print 1.857142857142857142857142857

print(2,3,1) would print 0.6

print(4,5,7) would print 0.8000000

print(4,5,1) would print 0.8

print(9999,23,1) would print 434.7

print(12345613,2321,89) would print if your Language has 32 bit unsigned 5319.09220163722533390779836277466609220163722533390779836277466609220163722533390779836277466

The shortest code in bytes wins. I'm sorry if this appear not clear... I don't know languages too, not remember words well...
It is better to have one link to Ideone.com or some other place for easily try the answer especially for to test some input different from proposed.

Title: Division of not so little numbers

Body:
Batch, 122 bytes

@set/as=%1/%2,r=%1%%%2
@set s=%s%.
@for /l %%a in (1,1,%3)do @set/ad=r*10/%2,r=r*10%%%2&call set s=%%s%%%%d%%
@echo %s%


答:
Jellyfish, <s>19</s> 18 bytes

```<code>P
,+>`
_  {I
/'␁'(
</code>```

The character ␁ is the unprintable control character with byte value 0x1. Try it online!

Explanation

This is a pretty complex Jellyfish program, since many values are used in multiple places.

I is raw input, read from STDIN as a string.

'( is the character literal (.

The { (left identity) takes '( and I as inputs, and returns '(.
The return value is never actually used.

` is thread. It modifies { to return the character ( for each character of I, resulting in a string of (s with the same length as I.

> is tail; it takes the string of (s as input and chops off the first character.

+ takes as arguments the string of (s and the unprintable byte, and adds the byte value (1) to each character. This gives an equal-length string of )s.
Using the character ␁ guarantees that the return value is a string, and not a list of integers.

On the lower left corner, / takes the unprintable byte, and returns a function that takes two arguments, and joins the second argument with the first one once (since the byte value is 1).

_ takes this function, grabs the arguments of the lower { (which were '( and I), and calls the funtion with them. This inserts the character ( between every pair of characters in I.

, concatenates this string with the string of )s, and P prints the result.

Title: N(e(s(t))) a string

Body:
Jellyfish, <s>19</s> 18 bytes

P
,+>`
_  {I
/'␁'(

The character ␁ is the unprintable control character with byte value 0x1. Try it online!

Explanation

This is a pretty complex Jellyfish program, since many values are used in multiple places.

I is raw input, read from STDIN as a string.

'( is the character literal (.

The { (left identity) takes '( and I as inputs, and returns '(.
The return value is never actually used.

` is thread. It modifies { to return the character ( for each character of I, resulting in a string of (s with the same length as I.

> is tail; it takes the string of (s as input and chops off the first character.

+ takes as arguments the string of (s and the unprintable byte, and adds the byte value (1) to each character. This gives an equal-length string of )s.
Using the character ␁ guarantees that the return value is a string, and not a list of integers.

On the lower left corner, / takes the unprintable byte, and returns a function that takes two arguments, and joins the second argument with the first one once (since the byte value is 1).

_ takes this function, grabs the arguments of the lower { (which were '( and I), and calls the funtion with them. This inserts the character ( between every pair of characters in I.

, concatenates this string with the string of )s, and P prints the result.


答:
Clojure, 24 bytes

```<code>#(nth(iterate list %)%2)
</code>```

Clojure is somewhat competitive here. iterate creates a sequence of x, (f x), (f (f x)) ..., nth returns needed element.

See it online: https://ideone.com/2rQ166

Title: Nest a string inside an array n times

Body:
You must produce a function which nests a string s inside an array, n times

```<code>>>> N("stackoverflow",2)
[['stackoverflow']]
</code>```

Parameters:

s - An ascii string

n - An integer >= 0

Rules

Shortest code wins.

The output will be a nested array, list or tuple (or similar type based off an array)

Test Cases

```<code>>>> N("stackoverflow",0)
'stackoverflow'
>>> N("stackoverflow",1)
['stackoverflow']
>>> N("stackoverflow",5)
[[[[['stackoverflow']]]]]
</code>```

Inspired by: Nesting a string inside a list n times ie list of a list of a list

Body:
Clojure, 24 bytes

#(nth(iterate list %)%2)

Clojure is somewhat competitive here. iterate creates a sequence of x, (f x), (f (f x)) ..., nth returns needed element.

See it online: https://ideone.com/2rQ166


答:
SWI-Prolog, 82 bytes

```<code>q([H],[H]).
q([H|T],[H,40|S]):-q(T,R),append(R,[41],S).
X*Y:-q(X,Z),atom_codes(Y,Z).
</code>```

Called like: `Hello World!`*X.

Online interpreter

Title: N(e(s(t))) a string

Body:
SWI-Prolog, 82 bytes

q([H],[H]).
q([H|T],[H,40|S]):-q(T,R),append(R,[41],S).
X*Y:-q(X,Z),atom_codes(Y,Z).

Called like: `Hello World!`*X.

Online interpreter