问:
Is this number a prime?
Believe it or not, we do not yet have a code golf challenge for a simple primality test. While it may not be the most interesting challenge, particularly for "usual" languages, it can be nontrivial in many languages.

Rosetta code features lists by language of idiomatic approaches to primality testing, one using the Miller-Rabin test specifically and another using trial division. However, "most idiomatic" often does not coincide with "shortest." In an effort to make Programming Puzzles and Code Golf the go-to site for code golf, this challenge seeks to compile a catalog of the shortest approach in every language, similar to "Hello, World!" and Golf you a quine for great good!.

Furthermore, the capability of implementing a primality test is part of our definition of programming language, so this challenge will also serve as a directory of proven programming languages.

Task

Write a full program that, given a strictly positive integer n as input, determines whether n is prime and prints a truthy or falsy value accordingly.

For the purpose of this challenge, an integer is prime if it has exactly two strictly positive divisors. Note that this excludes 1, who is its only strictly positive divisor.

Your algorithm must be deterministic (i.e., produce the correct output with probability 1) and should, in theory, work for arbitrarily large integers. In practice, you may assume that the input can be stored in your data type, as long as the program works for integers from 1 to 255.

Input

If your language is able to read from STDIN, accept command-line arguments or any other alternative form of user input, you can read the integer as its decimal representation, unary representation (using a character of your choice), byte array (big or little endian) or single byte (if this is your languages largest data type).

If (and only if) your language is unable to accept any kind of user input, you may hardcode the input in your program.

In this case, the hardcoded integer must be easily exchangeable. In particular, it may appear only in a single place in the entire program.

For scoring purposes, submit the program that corresponds to the input 1.

Output

Output has to be written to STDOUT or closest alternative.

If possible, output should consist solely of a truthy or falsy value (or a string representation thereof), optionally followed by a single newline.

The only exception to this rule is constant output of your language's interpreter that cannot be suppressed, such as a greeting, ANSI color codes or indentation.

Additional rules

This is not about finding the language with the shortest approach for prime testing, this is about finding the shortest approach in every language. Therefore, no answer will be marked as accepted.

Submissions in most languages will be scored in bytes in an appropriate preexisting encoding, usually (but not necessarily) UTF-8.

The language Piet, for example, will be scored in codels, which is the natural choice for this language.

Some languages, like Folders, are a bit tricky to score. If in doubt, please ask on Meta.

Unlike our usual rules, feel free to use a language (or language version) even if it's newer than this challenge. If anyone wants to abuse this by creating a language where the empty program performs a primality test, then congrats for paving the way for a very boring answer.

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

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

Built-in functions for testing primality are allowed. This challenge is meant to catalog the shortest possible solution in each language, so if it's shorter to use a built-in in your language, go for it.

Unless they have been overruled earlier, all standard code-golf rules apply, including the http://meta.codegolf.stackexchange.com/q/1061.

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

Catalog

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

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

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

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

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

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

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

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

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

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

Shortest Solution by Language

Language	User	Score

Leaderboard

	Author	Language	Size

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

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

```

答:
CASIO-BASIC, 28 bytes

```<code>?->A:For 2->B To A:A Rmdr B=0=>B->A:Next
</code>```

This prompts for a number, then outputs the number if it is prime, else zero.

I'm not really sure how this works. I originally thought it would output the value from the last assignment (stored in Ans), but then it would output the lowest factor of the number, not zero.

Note: -> and => are ASCII representations of one symbol each (the assign-to and conditional operators).

The size was calculated as the size of this program (60 bytes) minus the size of an empty program (32 bytes).

Title: Is this number a prime?

Body:
CASIO-BASIC, 28 bytes

?->A:For 2->B To A:A Rmdr B=0=>B->A:Next

This prompts for a number, then outputs the number if it is prime, else zero.

I'm not really sure how this works. I originally thought it would output the value from the last assignment (stored in Ans), but then it would output the lowest factor of the number, not zero.

Note: -> and => are ASCII representations of one symbol each (the assign-to and conditional operators).

The size was calculated as the size of this program (60 bytes) minus the size of an empty program (32 bytes).


问:
Make a (somewhat) self-referential string
You want to make a string where the (1-indexed) character at index n is n. When n is less than 10, this is easy: "123456789". When n is 12, for example, it becomes impossible, since numbers greater than 9 (in base 10) take up more than one character. We can compromise by dividing the string into two-character substrings: "020406081012". Now the index of the end of each substring n is n.

This can be generalized for any d-digit number. Here's an explanation for the "0991021" part of the string for a three-digit number:

```<code>Index:     ... * 97  98  99*100 101 102*103 ...
               *           *           *
               *---+---+---*---+---+---*---+
Character: ... * 0 | 9 | 9 * 1 | 0 | 2 * 1 | ...
               *---+---+---*---+---+---*---+
</code>```

If you haven't figured it out yet, you are to write a program/function that takes a string or integer and output its self-referential string as specified above. You can also output an array of single-digit numbers, chars, or single-character strings.

The given integer will always be positive and divisible by its length (e.g. 126 is divisible by 3; 4928 is divisible by 4). Your program should theoretically work for an arbitrarily large input, but you can assume it is smaller than your language's maximum integer and/or string length.

Some observations if you still don't get it: The length of the output will always be the input itself, and the numbers that appear in the output will be divisible by the number of digits in the input.

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

Test cases

```<code>1    => 1
9    => 123456789
10   => 0204060810
105  => 003006009012015018021024027030033036039042045048051054057060063066069072075078081084087090093096099102105
1004 => 00040008001200160020002400280032003600400044004800520056006000640068007200760080008400880092009601000104010801120116012001240128013201360140014401480152015601600164016801720176018001840188019201960200020402080212021602200224022802320236024002440248025202560260026402680272027602800284028802920296030003040308031203160320032403280332033603400344034803520356036003640368037203760380038403880392039604000404040804120416042004240428043204360440044404480452045604600464046804720476048004840488049204960500050405080512051605200524052805320536054005440548055205560560056405680572057605800584058805920596060006040608061206160620062406280632063606400644064806520656066006640668067206760680068406880692069607000704070807120716072007240728073207360740074407480752075607600764076807720776078007840788079207960800080408080812081608200824082808320836084008440848085208560860086408680872087608800884088808920896090009040908091209160920092409280932093609400944094809520956096009640968097209760980098409880992099610001004
</code>```

答:
Actually, 30 bytes

```<code>;╝R╛$l;)*@#"%0{}d"f╗`#╜%`MΣ╛@H
</code>```

Try it online!

I'm not happy with the length of this code, but I'm not sure that it can be made much shorter (if at all).

Explanation:

```<code>;╝R╛$l;)*@#"%0{}d"f╗`#╜%`MΣ╛@H
;╝                              duplicate input, push a copy to reg1
  R                             range(1, input+1)
   ╛$l                          push input from reg1, stringify, length
      ;)                        duplicate and move copy to bottom of stack
        *                       multiply range by length of input
         @#                     swap range with length, make length a 1-element list
           "%0{}d"f             "%0{}d".format(length) (old-style Python format string for zero-padding integers to length of input)
                   ╗            save format string in reg0
                    `#╜%`M      for each value in range:
                     #            make it a 1-element list
                      ╜%          format using the format string
                          Σ     concatenate
                           ╛@H  take only the first (input) characters in the resulting string
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Actually, 30 bytes

;╝R╛$l;)*@#"%0{}d"f╗`#╜%`MΣ╛@H

Try it online!

I'm not happy with the length of this code, but I'm not sure that it can be made much shorter (if at all).

Explanation:

;╝R╛$l;)*@#"%0{}d"f╗`#╜%`MΣ╛@H
;╝                              duplicate input, push a copy to reg1
  R                             range(1, input+1)
   ╛$l                          push input from reg1, stringify, length
      ;)                        duplicate and move copy to bottom of stack
        *                       multiply range by length of input
         @#                     swap range with length, make length a 1-element list
           "%0{}d"f             "%0{}d".format(length) (old-style Python format string for zero-padding integers to length of input)
                   ╗            save format string in reg0
                    `#╜%`M      for each value in range:
                     #            make it a 1-element list
                      ╜%          format using the format string
                          Σ     concatenate
                           ╛@H  take only the first (input) characters in the resulting string


问:
Random Golf of the Day #7: A distinctly random character

About the Series

This is a guest entry for the Random Golf of the Day series.

First off, you may treat this like any other code golf challenge, and answer it without worrying about the series at all. However, there is a leaderboard across all challenges. You can find the leaderboard along with some more information about the series in the first post.

Input

No input is taken.

Output

A single letter of the alphabet (case irrelevant), with an optional trailing newline. Each letter must have non-zero probability of being chosen, and all 26 probabilities must be distinct. To remove all ambiguity: Distinct means that there must not be two probabilities that are equal to each other.

Scoring

This is code golf. Shortest code in bytes wins.

A valid entry is a full program or function that has zero probability of not terminating.

Alphabet

To avoid confusion, the particular alphabet to be used is the Latin alphabet:

Either

```<code>ABCDEFGHIJKLMNOPQRSTUVWXYZ
</code>```

or

```<code>abcdefghijklmnopqrstuvwxyz
</code>```

You may choose to output upper case or lower case. Alternatively, you may choose to output different cases on different runs if that helps. The probability for a given letter is the probability of that letter appearing in either case (upper or lower).

Explanation

As it won't be at all obvious from the output, please include a clear explanation of how you achieved the 26 distinct probabilities.

Leaderboard

(from here)

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

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

```
</div>
</div>
</p>

<p><strong>The first post of the series also generates an overall leaderboard.</strong></p>

<p>To make sure that your answers show up, please start every answer with a headline, using the following Markdown template:</p>

```## Language Name, N bytes
```

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

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

(The language is not currently shown, but the snippet does require and parse it, and I may add a by-language leaderboard in the future.)

答:
Dyalog APL, 14 bytes

See this meta post for information about the code page.

(?351)⊃⎕A/⍨⍳26
```

Gives instant results. Works by selecting an evenly distributed random character among "ABBCCCDDDD..."

(?351) RandInt(1,351)

⊃picks among

⎕A "ABC...Z"

/⍨ element-by-element replicated

⍳26 {1, 2, 3, ..., 26} times

TryAPL online!

Body:
Dyalog APL, 14 bytes

See this meta post for information about the code page.

(?351)⊃⎕A/⍨⍳26

Gives instant results. Works by selecting an evenly distributed random character among "ABBCCCDDDD..."

(?351) RandInt(1,351)

⊃picks among

⎕A "ABC...Z"

/⍨ element-by-element replicated

⍳26 {1, 2, 3, ..., 26} times

TryAPL online!


问:
Shortest code to determine if a string is a palindrome
A palindrome is some string that is spelled the same way both backwards and forwards.  For instance, 'Eva, can I stab bats in a cave?' is a palindrome (EVACANISTAB | BATSINACAVE)

For this code golf, using the language of your choice, determine if a given string is a palindrome or not.

Edge Cases:

Punctuation is not counted towards palindrominess.

Control characters are not counted towards palindrominess.

Whitespace is not counted towards palindrominess.

Numbers are counted towards palindrominess.

Case in this challenge is not counted towards palindrominess.

There is no limit to the length of strings to evaluate, except for what is imposed by your language of choice.

For this challenge, limit yourself to the ASCII character set.

Technical Requirements:

Only method bodies are needed; additional things like method signatures, data structure declarations, etc. do not count towards the victory requirement.

Code must compile or interpret without compile-time errors or exceptions.

Code must not throw any unhandled exceptions or crash.  (Almost needless to say.  Almost.)

Code must return some value indicating palindrominess.  The data type depends on the language you use (e.g. a C# user might use a bool, whereas a JavaScript user could use a var.)

You may not write your own interpreter that performs this task as a 'native' capability so you can 'golf' a near-winning score.  (Hopefully needless to say.)

Victory Condition:

The shortest code in characters wins.

Current Leader: tmartin (k, 25 characters)

...Want the magic green check mark by your answer?  Beat this guy's answer!

答:
Racket, 132 bytes

Pretty embarrassing, but maybe somebody can see a way of making this shorter!

((λ(l[n(floor(/(length l)2))])(equal?(take l n)(take(reverse l)n)))(string->list(regexp-replace*"[^0-9a-z]"(string-downcase s)"")))
```

<h3>Code listing with test module</h3>

<pre class="lang-rkt prettyprint-override"><code>#lang racket

(define/contract (palindrome? s)
  (string? . -> . boolean?)
  ((λ(l[n(floor(/(length l)2))])(equal?(take l n)(take(reverse l)n)))(string->list(regexp-replace*"[^0-9a-z]"(string-downcase s)""))))

(module+ test
  (require rackunit)
  (define tests
    '(("Eva, can I stab bats in a cave?" . #t)
      ("A man, a plan, a canal. Panama!" . #t)
      ("Madam, I'm Adam Corolla." . #f)
      ("757" . #t)
      ("Boeing 757" . #f)
      ("A man, a plan, a big shovel, a canal. Panama!" . #f)
      ("A man, a plan, a canoe, pasta, heros, rajahs, a coloratura, maps, snipe, percale, macaroni, a gag, a banana bag, a tan, a tag, a banana bag again (or a camel), a crepe, pins, Spam, a rut, a Rolo, cash, a jar, sore hats, a peon, a canal >> __Panama__" . #t)))
  (for ([t tests])
    (check-equal? (palindrome? (car t)) (cdr t) (~a t))))
</code>```

Body:
Racket, 132 bytes

Pretty embarrassing, but maybe somebody can see a way of making this shorter!

((λ(l[n(floor(/(length l)2))])(equal?(take l n)(take(reverse l)n)))(string->list(regexp-replace*"[^0-9a-z]"(string-downcase s)"")))

Code listing with test module

#lang racket

(define/contract (palindrome? s)
  (string? . -> . boolean?)
  ((λ(l[n(floor(/(length l)2))])(equal?(take l n)(take(reverse l)n)))(string->list(regexp-replace*"[^0-9a-z]"(string-downcase s)""))))

(module+ test
  (require rackunit)
  (define tests
    '(("Eva, can I stab bats in a cave?" . #t)
      ("A man, a plan, a canal. Panama!" . #t)
      ("Madam, I'm Adam Corolla." . #f)
      ("757" . #t)
      ("Boeing 757" . #f)
      ("A man, a plan, a big shovel, a canal. Panama!" . #f)
      ("A man, a plan, a canoe, pasta, heros, rajahs, a coloratura, maps, snipe, percale, macaroni, a gag, a banana bag, a tan, a tag, a banana bag again (or a camel), a crepe, pins, Spam, a rut, a Rolo, cash, a jar, sore hats, a peon, a canal >> __Panama__" . #t)))
  (for ([t tests])
    (check-equal? (palindrome? (car t)) (cdr t) (~a t))))


问:
Pretty Smooth Moves
In arithmetic, an n-smooth number, where n is a given prime number, is mathematically defined as a positive integer that has no prime factors greater than n. For example, 42 is 7-smooth because all its prime factors are less than or equal to 7, but 44 is not 7-smooth because it also has 11 as a prime factor.

Define a pretty smooth number as a number with no prime factors greater than its own square root. Thus, the list of pretty smooth numbers can be formulated as follows:

(EDITED!) 1 is a pretty smooth number, due to its complete lack of any prime factors. (Note that in the original version of this question, 1 was erroneously excluded from the list, so if you exclude it from your outputs you won't be marked wrong.)

Between 4 (= 22) and 8, the pretty smooth numbers are 2-smooth, meaning they have 2 as their only prime factor.

Between 9 (= 32) and 24, the pretty smooth numbers are 3-smooth, and can have 2s and 3s in their prime factorizations.

Between 25 (= 52) and 48, the pretty smooth numbers are 5-smooth, and can have 2s, 3s, and 5s in their prime factorizations.

And so on, upgrading the criteria every time the square of the next prime number is reached.

The list of pretty smooth numbers is fixed, and begins as follows: 1, 4, 8, 9, 12, 16, 18, 24, 25, ...

Your challenge is to write code that will output all pretty smooth numbers up to and including 10,000 (= 1002). There must be at least one separator (it doesn't matter what kind -- space, comma, newline, anything) between each number in the list and the next, but it is completely irrelevant what character is used.

As per usual, lowest byte count wins -- obviously, simply outputting the list isn't going to be too beneficial to you here. Good luck!

答:
Haskell, 53 bytes

r=[1..10^4]
[n|n<-r,product[x|x<-r,x*x<=n]^n`mod`n<1]
```

I don't have time to golf this now, but I want to illustrate a method for testing if n is pretty smooth: Multiply the numbers from 1 to sqrt(n) (i.e. compute a factorial), raise the product to a high power, and check if the result is a multiple of n.

Change to r=[2..10^4] if 1 should not be output.

Title: Pretty Smooth Moves

Body:
Haskell, 53 bytes

r=[1..10^4]
[n|n<-r,product[x|x<-r,x*x<=n]^n`mod`n<1]

I don't have time to golf this now, but I want to illustrate a method for testing if n is pretty smooth: Multiply the numbers from 1 to sqrt(n) (i.e. compute a factorial), raise the product to a high power, and check if the result is a multiple of n.

Change to r=[2..10^4] if 1 should not be output.


答:
Pyke, <s>13</s> <s>12</s> 11 bytes

```<code>T4^S#DP#X<!
</code>```

Try it here!

(Link only goes up to 10^3 because 10^4 times out)

```<code>T4^S        -  one_range(10^4)
    #DP#X<! - filter_true(V, ^): (as i)
      P     -   factors(i)
       #X<! -  filter_true(V, ^):
        X   -   ^ ** 2
         <! -    not (i < ^)
</code>```

Title: Pretty Smooth Moves

Body:
In arithmetic, an n-smooth number, where n is a given prime number, is mathematically defined as a positive integer that has no prime factors greater than n. For example, 42 is 7-smooth because all its prime factors are less than or equal to 7, but 44 is not 7-smooth because it also has 11 as a prime factor.

Define a pretty smooth number as a number with no prime factors greater than its own square root. Thus, the list of pretty smooth numbers can be formulated as follows:

(EDITED!) 1 is a pretty smooth number, due to its complete lack of any prime factors. (Note that in the original version of this question, 1 was erroneously excluded from the list, so if you exclude it from your outputs you won't be marked wrong.)

Between 4 (= 22) and 8, the pretty smooth numbers are 2-smooth, meaning they have 2 as their only prime factor.

Between 9 (= 32) and 24, the pretty smooth numbers are 3-smooth, and can have 2s and 3s in their prime factorizations.

Between 25 (= 52) and 48, the pretty smooth numbers are 5-smooth, and can have 2s, 3s, and 5s in their prime factorizations.

And so on, upgrading the criteria every time the square of the next prime number is reached.

The list of pretty smooth numbers is fixed, and begins as follows: 1, 4, 8, 9, 12, 16, 18, 24, 25, ...

Your challenge is to write code that will output all pretty smooth numbers up to and including 10,000 (= 1002). There must be at least one separator (it doesn't matter what kind -- space, comma, newline, anything) between each number in the list and the next, but it is completely irrelevant what character is used.

As per usual, lowest byte count wins -- obviously, simply outputting the list isn't going to be too beneficial to you here. Good luck!

Body:
Pyke, <s>13</s> <s>12</s> 11 bytes

T4^S#DP#X<!

Try it here!

(Link only goes up to 10^3 because 10^4 times out)

T4^S        -  one_range(10^4)
    #DP#X<! - filter_true(V, ^): (as i)
      P     -   factors(i)
       #X<! -  filter_true(V, ^):
        X   -   ^ ** 2
         <! -    not (i < ^)


问:
Automatic box expander

Introduction

Sometimes, my boxes are too small to fit anything in it. I need you to make a box expander! So, what makes a box a box in this challenge.

```<code> OOOO
O    O
O    O
O    O
 OOOO
</code>```

The corners of the box are always spaces. The box itself can be made out of the same character. That character can be any printable ASCII character, except a space. So, that's these characters:

```<code>!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~
</code>```

The side lengths of the box above are 4, 3. You may assume that the side length is always positive. That means that this is the smallest box you need to handle:

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

In order to expand a box, you need to increment each side length. Let's go through this, step by step, with the above example. We first take the upper side of the box, which is:

```<code> OOOO
</code>```

We expand this by one, so we get:

```<code> OOOOO
</code>```

This is the upper and lower part of the box now. After that, we do the same with the sides on the left and right:

```<code>O
O
O
</code>```

Becomes:

```<code>O
O
O
O
</code>```

Now we reassemble the box, which results into:

```<code> OOOOO
O     O
O     O
O     O
O     O
 OOOOO
</code>```

The task

Given a box, expand it by 1. The box can be given in multiple lines, or in an array.

Test cases

```<code> OOOO          OOOOO
O    O    >   O     O
 OOOO         O     O
               OOOOO

 XXXXXX        XXXXXXX
X      X  >   X       X
X      X      X       X
 XXXXXX       X       X
               XXXXXXX

 ~             ~~
~ ~       >   ~  ~
 ~            ~  ~
               ~~
</code>```

This is code-golf, so the submission with the least amount of bytes wins!

答:
Dyalog APL, 14 bytes

(1 2,1↓⍳)¨∘⍴⌷⊢
```

<blockquote>
  <blockquote>
    <p><code>(</code></p>

    <blockquote>
      <p><code>1 2,</code> {1, 2} prepended to</p>

      <p><code>1↓</code> one element dropped from</p>

      <p><code>⍳</code> the indices</p>
    </blockquote>

    <p><code>)¨</code> of each</p>
  </blockquote>

  <p><code>∘</code> of</p>

  <blockquote>
    <p><code>⍴</code> the {row-count, column-count}</p>
  </blockquote>

  <p><code>⌷</code> indexes into</p>

  <blockquote>
    <p><code>⊢</code> the argument</p>
  </blockquote>
</blockquote>

<p>E.g. for </p>

<pre class="lang-apl prettyprint-override"><code> XX
X  X
 XX
</code>```

we find the indices; {1, 2, 3} for the rows, and {1, 2, 3, 4} for the columns. Now we drop the initial elements to get {2, 3} and {2, 3, 4}, and then prepend with {1, 2}, giving {1, 2, 2, 3} and {1, 2, 2, 3, 4}. Finally, we use this to select rows and columns, simultaneously doubling row 2 and column 2.

TryAPL online!

Title: Automatic box expander

Body:
Dyalog APL, 14 bytes

(1 2,1↓⍳)¨∘⍴⌷⊢

(

1 2, {1, 2} prepended to

1↓ one element dropped from

⍳ the indices

)¨ of each

∘ of

⍴ the {row-count, column-count}

⌷ indexes into

⊢ the argument

E.g. for

 XX
X  X
 XX

we find the indices; {1, 2, 3} for the rows, and {1, 2, 3, 4} for the columns. Now we drop the initial elements to get {2, 3} and {2, 3, 4}, and then prepend with {1, 2}, giving {1, 2, 2, 3} and {1, 2, 2, 3, 4}. Finally, we use this to select rows and columns, simultaneously doubling row 2 and column 2.

TryAPL online!


答:
05AB1E, <s>16</s> <s>14</s> 13 bytes

```<code>4°L¦vyf¤yt›_—
</code>```

Explanation

```<code>4°L¦v             # for each y in range 2..10000
      yf¤         # largest prime factor of y
         yt       # square root of y
           ›_     # less than or equal
             —    # if true then print y with newline
</code>```

Try it online

Title: Pretty Smooth Moves

Body:
05AB1E, <s>16</s> <s>14</s> 13 bytes

4°L¦vyf¤yt›_—

Explanation

4°L¦v             # for each y in range 2..10000
      yf¤         # largest prime factor of y
         yt       # square root of y
           ›_     # less than or equal
             —    # if true then print y with newline

Try it online


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

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

The Rules

Each submission must be a full program.

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

The program must not write anything to STDERR.

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

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

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

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

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

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

For inspiration, check the Hello World Collection.

The Catalogue

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

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

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

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

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

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

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

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

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

/* Configuration */

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

/* App */

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

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

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

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

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

getAnswers();

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

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

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

function process() {
  var valid = [];

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

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

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

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

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

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

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

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

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

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

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

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

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

table thead {
  font-weight: bold;
}

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

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

Shortest Solution by Language

Language	User	Score

Leaderboard

	Author	Language	Size

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

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

```

答:
ARMv7 machine language on Linux, <s>40 36</s> 32 bytes

```<code> 0: fa000002         blx 12          ;put string addr in lr; thumb mode
 4: 48 65 6c 6c 6f   "Hello, World!\0"
    2c 20 57 6f 72
    6c 64 21 00
12: 2001             movs r0, #1     ;stdout is fd=1
14: 220d             movs r2, #13    ;length of string
16: 4671             mov r1, lr      ;put string addr in r1
18: 2704             movs r7, #4     ;select write() syscall
1a: df00             svc 0           ;syscall
1c: 2701             movs r7, #1     ;select exit() syscall
1e: df00             svc 0           ;syscall
</code>```

To try this out on a Raspberry Pi or Android device with GNURoot, compile and run the following

```<code>const char main[]="\2\0\0\xfaHello, World!\0\1 \r\"qF\4'\0\xdf\1'\0\xdf";
</code>```

ContentLicense: CC BY-SA 4.0

Title: "Hello, World!"

Body:
ARMv7 machine language on Linux, <s>40 36</s> 32 bytes

 0: fa000002         blx 12          ;put string addr in lr; thumb mode
 4: 48 65 6c 6c 6f   "Hello, World!\0"
    2c 20 57 6f 72
    6c 64 21 00
12: 2001             movs r0, #1     ;stdout is fd=1
14: 220d             movs r2, #13    ;length of string
16: 4671             mov r1, lr      ;put string addr in r1
18: 2704             movs r7, #4     ;select write() syscall
1a: df00             svc 0           ;syscall
1c: 2701             movs r7, #1     ;select exit() syscall
1e: df00             svc 0           ;syscall

To try this out on a Raspberry Pi or Android device with GNURoot, compile and run the following

const char main[]="\2\0\0\xfaHello, World!\0\1 \r\"qF\4'\0\xdf\1'\0\xdf";


答:
PHP, 83 78 bytes

```<code><?$a=$argv[1];$i=$y=strlen($a);while($y<=$a){printf('%0'.$i.'d', $y);$y+=$i;}
</code>```

Tips are more then welcome. Manage to golf it myself by one byte by changing it from a for loop to a while loop.

This code assumes that this is being execute from the command line and that $argv[1] is the int.

Thanks to:

@AlexGittemeier
His suggestion (see comments) golfed this by 5 bytes to 78 bytes.

Title: Make a (somewhat) self-referential string

Body:
You want to make a string where the (1-indexed) character at index n is n. When n is less than 10, this is easy: "123456789". When n is 12, for example, it becomes impossible, since numbers greater than 9 (in base 10) take up more than one character. We can compromise by dividing the string into two-character substrings: "020406081012". Now the index of the end of each substring n is n.

This can be generalized for any d-digit number. Here's an explanation for the "0991021" part of the string for a three-digit number:

```<code>Index:     ... * 97  98  99*100 101 102*103 ...
               *           *           *
               *---+---+---*---+---+---*---+
Character: ... * 0 | 9 | 9 * 1 | 0 | 2 * 1 | ...
               *---+---+---*---+---+---*---+
</code>```

If you haven't figured it out yet, you are to write a program/function that takes a string or integer and output its self-referential string as specified above. You can also output an array of single-digit numbers, chars, or single-character strings.

The given integer will always be positive and divisible by its length (e.g. 126 is divisible by 3; 4928 is divisible by 4). Your program should theoretically work for an arbitrarily large input, but you can assume it is smaller than your language's maximum integer and/or string length.

Some observations if you still don't get it: The length of the output will always be the input itself, and the numbers that appear in the output will be divisible by the number of digits in the input.

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

Test cases

```<code>1    => 1
9    => 123456789
10   => 0204060810
105  => 003006009012015018021024027030033036039042045048051054057060063066069072075078081084087090093096099102105
1004 => 00040008001200160020002400280032003600400044004800520056006000640068007200760080008400880092009601000104010801120116012001240128013201360140014401480152015601600164016801720176018001840188019201960200020402080212021602200224022802320236024002440248025202560260026402680272027602800284028802920296030003040308031203160320032403280332033603400344034803520356036003640368037203760380038403880392039604000404040804120416042004240428043204360440044404480452045604600464046804720476048004840488049204960500050405080512051605200524052805320536054005440548055205560560056405680572057605800584058805920596060006040608061206160620062406280632063606400644064806520656066006640668067206760680068406880692069607000704070807120716072007240728073207360740074407480752075607600764076807720776078007840788079207960800080408080812081608200824082808320836084008440848085208560860086408680872087608800884088808920896090009040908091209160920092409280932093609400944094809520956096009640968097209760980098409880992099610001004
</code>```

Body:
PHP, 83 78 bytes

<?$a=$argv[1];$i=$y=strlen($a);while($y<=$a){printf('%0'.$i.'d', $y);$y+=$i;}

Tips are more then welcome. Manage to golf it myself by one byte by changing it from a for loop to a while loop.

This code assumes that this is being execute from the command line and that $argv[1] is the int.

Thanks to:

@AlexGittemeier
His suggestion (see comments) golfed this by 5 bytes to 78 bytes.


问:
Evaluate an expression of ternary operators
Consider a grammar over the alphabet {0, 1, ?, :} defined by the production rule

s → 0 ┃ 1 ┃ 0 ? s : s ┃ 1 ? s : s

Given a string generated from s, parse it as an expression where ?: is right-associative (for example, a?B?X:Y:c?d:e?f:g means a?(B?X:Y):(c?d:(e?f:g))) and evaluate it with the following semantics:

```<code>eval(0) = 0
eval(1) = 1
eval(0?a:b) = eval(b)
eval(1?a:b) = eval(a)
</code>```

If the result is 0, output some fixed value; if the output is 1, output a different fixed value. Specify your chosen output values (e.g. 0/1, or False/True) in your answer.

Test cases

```<code>0 -> 0
1 -> 1
0?0:1 -> 1
0?1:0 -> 0
1?0:1 -> 0
1?1:0 -> 1
0?1?0:1:1 -> 1
1?0?1:1:1 -> 1
1?0:1?0:1?1:1 -> 0
1?1?1:0?1?0:0:0:0 -> 1
1?0:1?0?1:1?1:0:1?1?1:1:1?0:1 -> 0
1?1?1:0?0?1:1:0?1:0:1?1?0?0:0:1?1:0:0?1?0:1:1?0:1 -> 1
0?0?1?0?0:1:0?0:0:0?0?1:1:1?0:1:0?0?0?1:0:0?1:1:1?1?0:1:1 -> 0
</code>```

Rules

You may not use language built-ins that interpret strings as code in some programming language and run it (such as JavaScript/Perl/Ruby/Python’s eval).

That said, your code doesn’t actually have to parse and then evaluate the input string. You can take any approach the achieves equivalent results and doesn’t violate the previous rule.

Your program will be checked against perl -le 'print eval<>'.

The shortest code (in bytes) wins.

答:
Retina, 23 bytes

```<code>r-1=+`0\?.:|1\?(.):.
$1
</code>```

Try it online! (The first line enables a linefeed-separated test suite.)

Explanation

It's fairly simple actually. The input is reduced to the result by repeatedly (+) evaluating ternaries that contain only literals. To make sure this is done right-associatively, we look for matches from right to left (r) and replace only the last match we find (-1=).

The regex itself either matches 0\?.: and removes it (leaving only the stuff after :) or 1\?.:. and replaces it with the value after the ?.

Body:
Retina, 23 bytes

r-1=+`0\?.:|1\?(.):.
$1

Try it online! (The first line enables a linefeed-separated test suite.)

Explanation

It's fairly simple actually. The input is reduced to the result by repeatedly (+) evaluating ternaries that contain only literals. To make sure this is done right-associatively, we look for matches from right to left (r) and replace only the last match we find (-1=).

The regex itself either matches 0\?.: and removes it (leaving only the stuff after :) or 1\?.:. and replaces it with the value after the ?.


Title: Pretty Smooth Moves

Body:
J, 20 bytes

(#~{:@q:<:%:)2+i.1e4

Result:

   (#~{:@q:<:%:)2+i.1e4
4 8 9 12 16 18 24 25 27 30 32 36 40 45 48 49 50 54 56 60 63 64 70 72 75 80...

Try it online here.


问:
Print an alphabet wave
You are to print this exact text:

```<code>ABABABABABABABABABABABABAB
BCBCBCBCBCBCBCBCBCBCBCBCBC
CDCDCDCDCDCDCDCDCDCDCDCDCD
DEDEDEDEDEDEDEDEDEDEDEDEDE
EFEFEFEFEFEFEFEFEFEFEFEFEF
FGFGFGFGFGFGFGFGFGFGFGFGFG
GHGHGHGHGHGHGHGHGHGHGHGHGH
HIHIHIHIHIHIHIHIHIHIHIHIHI
IJIJIJIJIJIJIJIJIJIJIJIJIJ
JKJKJKJKJKJKJKJKJKJKJKJKJK
KLKLKLKLKLKLKLKLKLKLKLKLKL
LMLMLMLMLMLMLMLMLMLMLMLMLM
MNMNMNMNMNMNMNMNMNMNMNMNMN
NONONONONONONONONONONONONO
OPOPOPOPOPOPOPOPOPOPOPOPOP
PQPQPQPQPQPQPQPQPQPQPQPQPQ
QRQRQRQRQRQRQRQRQRQRQRQRQR
RSRSRSRSRSRSRSRSRSRSRSRSRS
STSTSTSTSTSTSTSTSTSTSTSTST
TUTUTUTUTUTUTUTUTUTUTUTUTU
UVUVUVUVUVUVUVUVUVUVUVUVUV
VWVWVWVWVWVWVWVWVWVWVWVWVW
WXWXWXWXWXWXWXWXWXWXWXWXWX
XYXYXYXYXYXYXYXYXYXYXYXYXY
YZYZYZYZYZYZYZYZYZYZYZYZYZ
ZAZAZAZAZAZAZAZAZAZAZAZAZA
</code>```

Specs

You can print all lowercase instead of all uppercase. However, case must be consistent throughout the output.

You may print one extra trailing linefeed.

Scoring

Since this is an alphabet wave that fluctuates to a small extent, your code should also be small in terms of byte-count. In fact, the smallest code in terms of byte-count wins.

答:
PHP, 70 66 64 Bytes

```<code><?$a=A;$b=B;while($a!=AA)echo str_repeat($a++.($b++)[0],13)."
";
</code>```

3 bytes short (if I would remove the <? as well) from @insertusernamehere answer. So close!

EDIT:
Actually got it to 66 bytes (64 without the <?)! Doing A and B without quotes actually seem to work. Seems to be the shortest PHP one as time of write :D

EDIT 2:
Also removed " " from AA. Still seems to be working.

Title: Print an alphabet wave

Body:
PHP, 70 66 64 Bytes

<?$a=A;$b=B;while($a!=AA)echo str_repeat($a++.($b++)[0],13)."
";

3 bytes short (if I would remove the <? as well) from @insertusernamehere answer. So close!

EDIT:
Actually got it to 66 bytes (64 without the <?)! Doing A and B without quotes actually seem to work. Seems to be the shortest PHP one as time of write :D

EDIT 2:
Also removed " " from AA. Still seems to be working.


答:
Python 2, 89 bytes

```<code>s=input()
while'?'<=s[1:]:
 n=s<'1'
 while n:s=s[2:];n+=-(s[1]<'?')|1
 s=s[2:]
print s[0]
</code>```

Input is taken as a string literal.

Title: Evaluate an expression of ternary operators

Body:
Consider a grammar over the alphabet {0, 1, ?, :} defined by the production rule

s → 0 ┃ 1 ┃ 0 ? s : s ┃ 1 ? s : s

Given a string generated from s, parse it as an expression where ?: is right-associative (for example, a?B?X:Y:c?d:e?f:g means a?(B?X:Y):(c?d:(e?f:g))) and evaluate it with the following semantics:

```<code>eval(0) = 0
eval(1) = 1
eval(0?a:b) = eval(b)
eval(1?a:b) = eval(a)
</code>```

If the result is 0, output some fixed value; if the output is 1, output a different fixed value. Specify your chosen output values (e.g. 0/1, or False/True) in your answer.

Test cases

```<code>0 -> 0
1 -> 1
0?0:1 -> 1
0?1:0 -> 0
1?0:1 -> 0
1?1:0 -> 1
0?1?0:1:1 -> 1
1?0?1:1:1 -> 1
1?0:1?0:1?1:1 -> 0
1?1?1:0?1?0:0:0:0 -> 1
1?0:1?0?1:1?1:0:1?1?1:1:1?0:1 -> 0
1?1?1:0?0?1:1:0?1:0:1?1?0?0:0:1?1:0:0?1?0:1:1?0:1 -> 1
0?0?1?0?0:1:0?0:0:0?0?1:1:1?0:1:0?0?0?1:0:0?1:1:1?1?0:1:1 -> 0
</code>```

Rules

You may not use language built-ins that interpret strings as code in some programming language and run it (such as JavaScript/Perl/Ruby/Python’s eval).

That said, your code doesn’t actually have to parse and then evaluate the input string. You can take any approach the achieves equivalent results and doesn’t violate the previous rule.

Your program will be checked against perl -le 'print eval<>'.

The shortest code (in bytes) wins.

Body:
Python 2, 89 bytes

s=input()
while'?'<=s[1:]:
 n=s<'1'
 while n:s=s[2:];n+=-(s[1]<'?')|1
 s=s[2:]
print s[0]

Input is taken as a string literal.


答:
Matlab, <s>58</s> <s>57</s> <s>56</s> <s>52</s> 48 bytes

```<code>for k=1:1e4
if factor(k).^2<=k
disp(k)
end
end
</code>```

For each number it checks if all factors squared are not larger than the number itself. If yes, displays that number.

Thanks to @Luis Mendo for golfing this approach

Another approach (50 bytes):

```<code>n=1:10^4;for k=n
z(k)=max(factor(k))^2>k;end
n(~z)
</code>```

For each number computes whether its maximum prime factor squared is less than the number itself. Then uses it for indexing.

Title: Pretty Smooth Moves

Body:
Matlab, <s>58</s> <s>57</s> <s>56</s> <s>52</s> 48 bytes

for k=1:1e4
if factor(k).^2<=k
disp(k)
end
end

For each number it checks if all factors squared are not larger than the number itself. If yes, displays that number.

Thanks to @Luis Mendo for golfing this approach

Another approach (50 bytes):

n=1:10^4;for k=n
z(k)=max(factor(k))^2>k;end
n(~z)

For each number computes whether its maximum prime factor squared is less than the number itself. Then uses it for indexing.


问:
Wave-Particle Duality Laterally Programmatically
Write a program or function that takes in a nonempty single-line string. The string will either be zero or more spaces followed by one period (a particle), such as . or          ., or the string will be a sequence of one or more alternating forward and back slashes (a wave) that could start with either one, such as \ or /\/ or \/\/\/\/\/\/.

In either case, propagate the particle/wave to the right by one unit.

Specifically, in the particle case, insert a space before the ., moving it one place to the right, then output the resulting string. For example:

. →  .

 . →   .

  . →    .

   . →     .

    . →      .

     . →       .

      . →        .

       . →         .

In the wave case, append either / or \ appropriately so the wave keeps alternating and it's length increases by one, then output the resulting string. For example:

/ → /\

\ → \/

/\ → /\/

\/ → \/\

/\/ → /\/\

\/\ → \/\/

/\/\ → /\/\/

\/\/ → \/\/\

In either case, the output may not have trailing spaces but an optional trailing newline is allowed.

The shortest code in bytes wins.

答:
05AB1E, <s>17</s> 15 bytes

```<code>D'.åiðìë¤„\/s-J
</code>```

Explanation

```<code>D'.åi              # if input contains dot
     ðì            # prepend a space
       ë           # else
        ¤„\/s-     # subtract last char of input from "\/"
              J    # join remainder to input
                   # implicitly print
</code>```

Try it online

Body:
05AB1E, <s>17</s> 15 bytes

D'.åiðìë¤„\/s-J

Explanation

D'.åi              # if input contains dot
     ðì            # prepend a space
       ë           # else
        ¤„\/s-     # subtract last char of input from "\/"
              J    # join remainder to input
                   # implicitly print

Try it online


问:
Lemon-Limify a String
Write a program or function that takes in a nonempty single-line string. You may assume it only contains printable ASCII excluding space.

Print or return an ASCII art lozenge shape similar to a lemon or lime made from the prefixes of the string.

Suppose the input string is n letters long. Then, such a shape consists of 2n − 1 columns of ASCII art stitched together, each consisting of 2n − 1 lines. Counting from 1, the k-th column is f(k) = min(k, 2n − k) characters wide, and contains f(k) copies of the first f(k) characters of input, centered vertically, with single blank lines separating the copies.

For example, if the input is Lemon, the output should be:

```<code>          Lemon
      Lemo     Lemo
   Lem    Lemon    Lem
 Le   Lemo     Lemo   Le
L  Lem    Lemon    Lem  L
 Le   Lemo     Lemo   Le
   Lem    Lemon    Lem
      Lemo     Lemo
          Lemon
</code>```

If the input is lime the output should be:

```<code>      lime
   lim    lim
 li   lime   li
l  lim    lim  l
 li   lime   li
   lim    lim
      lime
</code>```

And the same pattern is followed for other inputs:

```<code>a

a

Be

 Be
B  B
 Be

/\

 /\
/  /
 /\

cat

   cat
 ca   ca
c  cat  c
 ca   ca
   cat

|||

   |||
 ||   ||
|  |||  |
 ||   ||
   |||

.__.

      .__.
   .__    .__
 ._   .__.   ._
.  .__    .__  .
 ._   .__.   ._
   .__    .__
      .__.

$tring

               $tring
          $trin      $trin
      $tri     $tring     $tri
   $tr    $trin      $trin    $tr
 $t   $tri     $tring     $tri   $t
$  $tr    $trin      $trin    $tr  $
 $t   $tri     $tring     $tri   $t
   $tr    $trin      $trin    $tr
      $tri     $tring     $tri
          $trin      $trin
               $tring
</code>```

Lines in the output may have trailing spaces and there may be one optional trailing newline.

The shortest code in bytes wins.

答:
TSQL, 259 bytes

Golfed:

```<code>DECLARE @ VARCHAR(30)='TSQL'

,@o VARCHAR(max),@i INT=0,@j INT,@t VARCHAR(max)SET @j=LEN(@)z:WHILE @i<LEN(@)SELECT @o=x+ISNULL(@o+x,''),@i+=1FROM(SELECT LEFT(IIF((@j-@i)%2=1,@,SPACE(99)),LEN(@)-@i)x)z SELECT @j-=1,@t=@o+ISNULL(CHAR(10)+@t+CHAR(10)+@o,''),@o=null,@i=0IF @j>0GOTO z PRINT @t
</code>```

Ungolfed:

```<code>DECLARE @ VARCHAR(30)='TSQL'

,@o VARCHAR(max),@i INT=0,@j INT,@t VARCHAR(max)SET @j=LEN(@)
z:
WHILE @i<LEN(@)
  SELECT @o=x+ISNULL(@o+x,''),@i+=1
  FROM(SELECT LEFT(IIF((@j-@i)%2=1,@,SPACE(99)),LEN(@)-@i)x)z
SELECT @j-=1,@t=@o+ISNULL(CHAR(10)+@t+CHAR(10)+@o,''),@o=null,@i=0
IF @j>0 GOTO z

PRINT @t
</code>```

Fiddle

Title: Lemon-Limify a String

Body:
TSQL, 259 bytes

Golfed:

DECLARE @ VARCHAR(30)='TSQL'

,@o VARCHAR(max),@i INT=0,@j INT,@t VARCHAR(max)SET @j=LEN(@)z:WHILE @i<LEN(@)SELECT @o=x+ISNULL(@o+x,''),@i+=1FROM(SELECT LEFT(IIF((@j-@i)%2=1,@,SPACE(99)),LEN(@)-@i)x)z SELECT @j-=1,@t=@o+ISNULL(CHAR(10)+@t+CHAR(10)+@o,''),@o=null,@i=0IF @j>0GOTO z PRINT @t

Ungolfed:

DECLARE @ VARCHAR(30)='TSQL'

,@o VARCHAR(max),@i INT=0,@j INT,@t VARCHAR(max)SET @j=LEN(@)
z:
WHILE @i<LEN(@)
  SELECT @o=x+ISNULL(@o+x,''),@i+=1
  FROM(SELECT LEFT(IIF((@j-@i)%2=1,@,SPACE(99)),LEN(@)-@i)x)z
SELECT @j-=1,@t=@o+ISNULL(CHAR(10)+@t+CHAR(10)+@o,''),@o=null,@i=0
IF @j>0 GOTO z

PRINT @t

Fiddle


问:
Can you outgolf me? (Cops section)

Cops section

The robbers section can be found here.

Thanks to FryAmTheEggman, Peter Taylor, Nathan Merrill, xnor, Dennis, Laikoni and Mego for their contributions.

Challenge

Your task is to write 2 different programs (full programs/functions/etc.) in the same language and the same version (e.g. Python 3.5 ≠ Python 3.4, so that is not allowed), and when given n (using STDIN/function arguments/etc.), compute a(n) where a is an OEIS sequence of your choice. One of those programs is shorter than the other. You only need to submit the longer program of the two. The other one needs to be saved in case of not being cracked after 7 days. Your submission is cracked when your program has been outgolfed (whether it is by 1 byte or more).

For example, if the task you chose was to perform 2 × n, this could be a valid submission (in Python 2):

Python 2, 16 bytes, score = 15 / 16 = 0.9375

```<code>print(2*input())
</code>```

Computes A005843, (offset = 0).

If your submission has been cracked, then you need to state that in your header like so:

Python 2, 16 bytes, score = 15 / 16 = 0.9375, [cracked] + link

```<code>print(2*input())
</code>```

Computes A005843, (offset = 0).

Offset

This can be found on every OEIS page. For example, for A005843, the offset is 0,2. We only need to use the first one, which is 0. This means that the function is defined for all numbers ≥ 0.

In other words, the function OEIS(n) starts with n = 0. Your program needs to work for all cases given by OEIS.

More information can be found here.

Scoring

The score you get for your submission is equal to the following formula:

Score = Length (in bytes) of secret code ÷ Length (in bytes) of public code

The example above has the score 15 ÷ 16 = 0.9375.

The submission with the lowest score wins. Only submissions that have posted their solution will be eligible for winning.

Rules

The task you need to do is an OEIS sequence of your choice.

Given n, output OEIS(n). Deviation is not allowed, so you need to produce the exact same sequence (when given n, you need to output OEIS(n)).

Submissions that are not cracked within a period of 7 days are considered safe after the solution has been posted (submissions older than 7 days that do not have their solution posted are still vulnerable in being cracked).

In your submission, you need to post the following things: language name, byte count, full code, so no pastebin links etc. (to prevent answers like Unary), OEIS sequence, score with lengths of both programs and additionally, the encoding that is used.

Note: the same sequence cannot be posted twice in the same language. (For example, if the sequence A005843 has been done in Pyth, you cannot use Pyth again for that same sequence.)

Input and output are both in decimal (base 10)

Leaderboard

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

Uncracked submissions

 Language	 Score	 User

Sort by: score creation

Safe submissions

 Language	 Score	 User

```

Note

This challenge is finished. The final winner is feersum with his Seed answer. Congratulations! :).

You can still submit new cops, but be aware that they are no longer competing.

Title: Can you outgolf me? (Cops section)

Body:
J, 20 bytes, score = 0.75 (15/20) (cracked)

[:*/0 1(]{:,+/)^:[~]

Computes A001654.

My solution for 15 bytes was

*&(+/@:!&i.-)>:


Title: Wave-Particle Duality Laterally Programmatically

Body:
Write a program or function that takes in a nonempty single-line string. The string will either be zero or more spaces followed by one period (a particle), such as . or          ., or the string will be a sequence of one or more alternating forward and back slashes (a wave) that could start with either one, such as \ or /\/ or \/\/\/\/\/\/.

In either case, propagate the particle/wave to the right by one unit.

Specifically, in the particle case, insert a space before the ., moving it one place to the right, then output the resulting string. For example:

. →  .

 . →   .

  . →    .

   . →     .

    . →      .

     . →       .

      . →        .

       . →         .

In the wave case, append either / or \ appropriately so the wave keeps alternating and it's length increases by one, then output the resulting string. For example:

/ → /\

\ → \/

/\ → /\/

\/ → \/\

/\/ → /\/\

\/\ → \/\/

/\/\ → /\/\/

\/\/ → \/\/\

In either case, the output may not have trailing spaces but an optional trailing newline is allowed.

The shortest code in bytes wins.

Body:
JavaScript, <s>79</s> <s>70</s> <s>65</s> 58 bytes

(a,b="/\\/",i=b.indexOf(a[a.length-1]))=>i<0?" "+a:a+b[i+1]


答:
GolfScript, 21 bytes

```<code>2/-1%{)2%{0`=@@if}*}/
</code>```

This outputs 0 or 1. Input is assumed to have a single trailing newline. Using ~ (which evaluates strings) would save a byte:

```<code>2/-1%{)2%{~!@@if}*}/
</code>```

This is based on http://golf.shinh.org/reveal.rb?The+B+Programming+Language/tails_1462638030&gs .

Body:
GolfScript, 21 bytes

2/-1%{)2%{0`=@@if}*}/

This outputs 0 or 1. Input is assumed to have a single trailing newline. Using ~ (which evaluates strings) would save a byte:

2/-1%{)2%{~!@@if}*}/

This is based on http://golf.shinh.org/reveal.rb?The+B+Programming+Language/tails_1462638030&gs .


答:
Haskell, <s>106 101 100 90</s> 83  bytes

This heavily relies on pattern Haskell's pattern matching capabilities. First of all, we reverse the string such that we can just seach for the first occurence of b:a?x (which would normally read as x?a:b) and replace it with it's value. This automatically provides the right associativity. Here we make use of x:xs pattern. This is what the function f is doing. Then we basically apply f to it's output over and over again, until we have a single number (0 or 1) left.

Thanks @Lynn for 12 bytes!

```<code>f(b:':':a:'?':x:l)|x>'0'=a:l|1>0=b:l
f(x:l)=x:f l
f x=x
until((<2).length)f.reverse
</code>```

Body:
Haskell, <s>106 101 100 90</s> 83  bytes

This heavily relies on pattern Haskell's pattern matching capabilities. First of all, we reverse the string such that we can just seach for the first occurence of b:a?x (which would normally read as x?a:b) and replace it with it's value. This automatically provides the right associativity. Here we make use of x:xs pattern. This is what the function f is doing. Then we basically apply f to it's output over and over again, until we have a single number (0 or 1) left.

Thanks @Lynn for 12 bytes!

f(b:':':a:'?':x:l)|x>'0'=a:l|1>0=b:l
f(x:l)=x:f l
f x=x
until((<2).length)f.reverse


问:
Ode-cay Olf-gay
Write a program which accepts a sentence into stdin, and writes that sentence to stdout in pig latin.

Here are some test cases which your program should handle:

```<code>Input:
    Read your script
Output:
    ead-Ray our-yay ipt-scray
</code>```

Hyphenation is mandatory. Note that multiple consonants at the start of the word must all be moved to the end. Capitalization of the output does not matter; Ead-ray or ead-ray are also valid translations of Read

```<code>Input:
    An utterance is allowed an opening vowel
Output:
    An-way utterance-way is-way allowed-way an-way opening-way owel-vay
</code>```

Words starting with vowels have -way appended in their pig latin form (don't forget to handle capital opening vowels)

```<code>Input:
    sky
    -skyay
</code>```

Words consisting entirely of consonants should have a hyphen prepended, and ay appended

Punctuation is undefined; I don't care if leading or trailing punctuation ends up inside the pig latin word.

This is code golf; the shortest program by character count wins. I've written a solution myself which handles all these cases which I shall post as a response.

答:
Perl, 41 excluding switches

A simple modification of Timwi's answer. Runs with perl -p. Does not meet the spec for 'sky', but the original doesn't either.

```<code>s/(\S*?)([aeiou]\S*)/"$2-".($1||w).ay/ige
</code>```

Title: Ode-cay Olf-gay

Body:
Perl, 41 excluding switches

A simple modification of Timwi's answer. Runs with perl -p. Does not meet the spec for 'sky', but the original doesn't either.

s/(\S*?)([aeiou]\S*)/"$2-".($1||w).ay/ige


答:
05AB1E, 12 bytes

```<code>X$ÍF‚D`ŠŠO}P
</code>```

Explanation

```<code>X$           # push 1, 1, input
  ÍF      }  # input-2 times do:
    ‚D       # pair top 2 elments and duplicate
      `ŠŠ    # flatten one pair and move the remaining pair to the top of the stack
         O   # sum the pair
           P # product of stack
             # implicitly print
</code>```

Try it online

Title: Fibonacci-orial

Body:
Definition

Fibonacci sequence F(n), on the positive integers, are defined as such:

```<code>1. F(1) = 1
2. F(2) = 1
3. F(n) = F(n-1) + F(n-2), where n is an integer and n > 2
</code>```

The Fibonacci-orial of a positive integer is the product of [F(1), F(2), ..., F(n)].

Task

Given positive integer n, find the Fibonacci-orial of n.

Specs

The fibonacci-orial of 100 must compute in under 5 seconds on a reasonable computer.

Testcases

```<code>n   Fibonacci-orial of n
1   1
2   1
3   2
4   6
5   30
6   240
7   3120
8   65520
9   2227680
10  122522400
11  10904493600
12  1570247078400
13  365867569267200
14  137932073613734400
15  84138564904377984000
16  83044763560621070208000
17  132622487406311849122176000
18  342696507457909818131702784000
19  1432814097681520949608649339904000
20  9692987370815489224102512784450560000
100 3371601853146468125386964065447576689828006172937411310662486977801540671138589868616500834190029067583665182291701553172011082574587431382310099030394306877775647395167143332483560925112960024644459715300507481235056111434293619038347456390454209587101225261757371666449068625033999573552165524529725467628060170886602001077137613803027158648329335507728698605769992818756765633305318529965186184043999696650407246193257877568825245646129366994079739720698147440310773871269639752334356493678913424390564535389212240038895626811627949132978086070255082668392290037141141291484839596694182152062726390364094447642643912371532491388089634845995941928089653751672688740718152064107169357399466473375804972260594768969952507346694189050233823596316467570584434128052398891223730335019092974935617029638919358286124350711360361279157416837428904150054292406756317837582840596331363581207781793070936765786629772999832857257349696094416616259974304208756997835360702840912518532683324936435856348020736000000000000000000000000
</code>```

References

Obligatory OEIS A003266

OEIS A000045 - Fibonacci sequence

Body:
05AB1E, 12 bytes

X$ÍF‚D`ŠŠO}P

Explanation

X$           # push 1, 1, input
  ÍF      }  # input-2 times do:
    ‚D       # pair top 2 elments and duplicate
      `ŠŠ    # flatten one pair and move the remaining pair to the top of the stack
         O   # sum the pair
           P # product of stack
             # implicitly print

Try it online


答:
Fourier, 34 bytes

Basically, just a small tweak of the Fibonacci sequence program on Fourier's esolangs page.

```<code>1~F~x~yI~k(x*F~Fy+x~gy~xg~yi^~i)Fo
</code>```

If you want to try this program online, I would suggest using Dennis' site, http://fourier.tryitonline.net, because on http://labs.turbo.run/beta/fourier an input of 100 leads to an output of infinity.

Try it online!

Title: Fibonacci-orial

Body:
Fourier, 34 bytes

Basically, just a small tweak of the Fibonacci sequence program on Fourier's esolangs page.

1~F~x~yI~k(x*F~Fy+x~gy~xg~yi^~i)Fo

If you want to try this program online, I would suggest using Dennis' site, http://fourier.tryitonline.net, because on http://labs.turbo.run/beta/fourier an input of 100 leads to an output of infinity.

Try it online!


答:
Perl, 32 + 1 (-p flag) = 33 bytes

Full credit to  @Mitch Swartch, as his solution was 14 bytes shorter than mine!

Thanks also to @Neil who suggested a solution 1 byte longer than Mitch.

s/.*\K(0\?..|1\?(.)..)/\2/&&redo
```
<p>Needs <code>-p</code> flag, as well as <code>-M5.010</code> or <code>-E</code> to run. For instance :</p>
```perl -pE 's/.*\K(0\?..|1\?(.)..)/\2/&&redo' <<< "0
0?0:1
0?1?0:1:1
1?0:1?0?1:1?1:0:1?1?1:1:1?0:1
0?0?1?0?0:1:0?0:0:0?0?1:1:1?0:1:0?0?0?1:0:0?1:1:1?1?0:1:1"
```

Explanations : It basically reduces the blocks of a?b:c (starting from the end to be sure no ? follows) into b or c depending on the truthness of a, over and over until the string only contains 1 or 0.

Body:
Perl, 32 + 1 (-p flag) = 33 bytes

Full credit to  @Mitch Swartch, as his solution was 14 bytes shorter than mine!

Thanks also to @Neil who suggested a solution 1 byte longer than Mitch.

s/.*\K(0\?..|1\?(.)..)/\2/&&redo

Needs -p flag, as well as -M5.010 or -E to run. For instance :

perl -pE 's/.*\K(0\?..|1\?(.)..)/\2/&&redo' <<< "0
0?0:1
0?1?0:1:1
1?0:1?0?1:1?1:0:1?1?1:1:1?0:1
0?0?1?0?0:1:0?0:0:0?0?1:1:1?0:1:0?0?0?1:0:0?1:1:1?1?0:1:1"

Explanations : It basically reduces the blocks of a?b:c (starting from the end to be sure no ? follows) into b or c depending on the truthness of a, over and over until the string only contains 1 or 0.


答:
Grime, <s>34</s> 31 bytes

```<code>E=d|d\?E.E
e`\1|\1\?_.E|\0\?E._
</code>```

Prints 1 for truthy inputs and 0 for falsy ones.
Try it online!
The last test case unfortunately runs out of memory on TIO.

Explanation

The right-associativity essentially means that in a?b:c, a is always either 0 or 1, never a longer expression.
I'll just recursively define a pattern that matches a truthy expression like that, and check the input against it.
It's also unnecessary to check that every : is really a :, if the ?s are all checked: there is an equal number of ?s and :s in the input, and if some ? is incorrectly classified as a :, the corresponding : will fail to match, and Grime's matching engine will backtrack.

```<code>E=d|d\?E.E
E=                      Define nonterminal E (for "expression") as
  d|                     a digit, OR
    d                    a digit,
     \?                  a literal ?,
       E                 a match of E,
        .                any character (will match a :), and
         E               another match of E.
e`\1|\1\?_.E|\0\?E._
e`                      Match entire input against this pattern (truthy expression):
  \1|                    a literal 1, OR
     \1\?                a literal 1?,
         _               a recursive match of truthy expression,
          .              any character (will match a :), and
           E|            any expression, OR
             \0\?E._     the same, but with 0 in front, and _ and E swapped.
</code>```

Body:
Grime, <s>34</s> 31 bytes

E=d|d\?E.E
e`\1|\1\?_.E|\0\?E._

Prints 1 for truthy inputs and 0 for falsy ones.
Try it online!
The last test case unfortunately runs out of memory on TIO.

Explanation

The right-associativity essentially means that in a?b:c, a is always either 0 or 1, never a longer expression.
I'll just recursively define a pattern that matches a truthy expression like that, and check the input against it.
It's also unnecessary to check that every : is really a :, if the ?s are all checked: there is an equal number of ?s and :s in the input, and if some ? is incorrectly classified as a :, the corresponding : will fail to match, and Grime's matching engine will backtrack.

E=d|d\?E.E
E=                      Define nonterminal E (for "expression") as
  d|                     a digit, OR
    d                    a digit,
     \?                  a literal ?,
       E                 a match of E,
        .                any character (will match a :), and
         E               another match of E.
e`\1|\1\?_.E|\0\?E._
e`                      Match entire input against this pattern (truthy expression):
  \1|                    a literal 1, OR
     \1\?                a literal 1?,
         _               a recursive match of truthy expression,
          .              any character (will match a :), and
           E|            any expression, OR
             \0\?E._     the same, but with 0 in front, and _ and E swapped.


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

```<code>a=`id`
for c in input()[::-1]:a=(c+a,a[ord(c)*7%9]+a[4:])[a>'?']
print a
</code>```

With input as string literal to avoid raw_.

The output is 0 or 1 followed by <built-in function id>.

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

a=`id`
for c in input()[::-1]:a=(c+a,a[ord(c)*7%9]+a[4:])[a>'?']
print a

With input as string literal to avoid raw_.

The output is 0 or 1 followed by <built-in function id>.


答:
Clojure, 62 bytes

```<code>(loop[i 65](if(or(> i 89)(neg?(rand)))(char i)(recur(inc i))))
</code>```

This is somewhat stupid shortcut. The probability of exact zero double - the only (rand) to not break on condition (pos? x) - is around 1/(2^62) [source].

So chance for letter char(65+N) is around (1/(2^62))^N, slightly higher for Z (because it is last).

With (rand-int 2) - 6 more bytes - it becomes testable.

Title: Random Golf of the Day #7: A distinctly random character

Body:
About the Series

This is a guest entry for the Random Golf of the Day series.

First off, you may treat this like any other code golf challenge, and answer it without worrying about the series at all. However, there is a leaderboard across all challenges. You can find the leaderboard along with some more information about the series in the first post.

Input

No input is taken.

Output

A single letter of the alphabet (case irrelevant), with an optional trailing newline. Each letter must have non-zero probability of being chosen, and all 26 probabilities must be distinct. To remove all ambiguity: Distinct means that there must not be two probabilities that are equal to each other.

Scoring

This is code golf. Shortest code in bytes wins.

A valid entry is a full program or function that has zero probability of not terminating.

Alphabet

To avoid confusion, the particular alphabet to be used is the Latin alphabet:

Either

```<code>ABCDEFGHIJKLMNOPQRSTUVWXYZ
</code>```

or

```<code>abcdefghijklmnopqrstuvwxyz
</code>```

You may choose to output upper case or lower case. Alternatively, you may choose to output different cases on different runs if that helps. The probability for a given letter is the probability of that letter appearing in either case (upper or lower).

Explanation

As it won't be at all obvious from the output, please include a clear explanation of how you achieved the 26 distinct probabilities.

Leaderboard

(from here)

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

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

```
</div>
</div>
</p>

<p><strong>The first post of the series also generates an overall leaderboard.</strong></p>

<p>To make sure that your answers show up, please start every answer with a headline, using the following Markdown template:</p>

```## Language Name, N bytes
```

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

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

(The language is not currently shown, but the snippet does require and parse it, and I may add a by-language leaderboard in the future.)

Body:
Clojure, 62 bytes

(loop[i 65](if(or(> i 89)(neg?(rand)))(char i)(recur(inc i))))

This is somewhat stupid shortcut. The probability of exact zero double - the only (rand) to not break on condition (pos? x) - is around 1/(2^62) [source].

So chance for letter char(65+N) is around (1/(2^62))^N, slightly higher for Z (because it is last).

With (rand-int 2) - 6 more bytes - it becomes testable.


答:
><>, 47 bytes

```<code>i:0(?\
*=?$r\~:1[:"./ \/"{=?@r=?$r~~]:48
l?!;o>
</code>```

Try it online!

The first line is a standard ><> input loop. The second line chooses the appropriate character from / \ to append to the string, based on the last input character. In addition, if the last input character was a ., the top two elements are switched. Finally, the stack contents are printed in reverse.

Body:
><>, 47 bytes

i:0(?\
*=?$r\~:1[:"./ \/"{=?@r=?$r~~]:48
l?!;o>

Try it online!

The first line is a standard ><> input loop. The second line chooses the appropriate character from / \ to append to the string, based on the last input character. In addition, if the last input character was a ., the top two elements are switched. Finally, the stack contents are printed in reverse.


答:
ForceLang, 140 bytes

```<code>def s set
s a 0
s b s p 1
s k io.readnum()
if k=1
goto b
label a
s c a+b
s a b
s b c
s p p.mult c
s k k+-1
if k+-1
goto a
label b
io.write p
</code>```

Title: Fibonacci-orial

Body:
ForceLang, 140 bytes

def s set
s a 0
s b s p 1
s k io.readnum()
if k=1
goto b
label a
s c a+b
s a b
s b c
s p p.mult c
s k k+-1
if k+-1
goto a
label b
io.write p


问:
Power modulo golf.
Write a function f(a,b,c) that calculates a^b (mod c) in less than 10 seconds.

a, b < 10^100

c < 10000.

examples:

```<code>f(10^50, 10^50, 54123) = 46555
f(5^99, 10^99, 777) = 1
</code>```

答:
Python 80 Characters</p>

```<code>def f(a,b,c):
 x=1;y=a
 while b:
  if b%2:x=(x*y)%c
  y=(y*y)%c;b/=2
 return x%c
</code>```

ContentLicense: CC BY-SA 2.5

Title: Power modulo golf.

Body:
Python 80 Characters

def f(a,b,c):
 x=1;y=a
 while b:
  if b%2:x=(x*y)%c
  y=(y*y)%c;b/=2
 return x%c


问:
Match up to 10 in an array

Challenge

Given an array of single digit number, work out if any 2 of them add up to 10 and print them out

Example

Input

(1,2,3,4,5,5,6,7)

This returns ((4,6),(5,5),(3,7))

Input

(1,2,3,4,5)

This returns (). as there is only one 5

Input

(5,5,5,5,5)

This returns ((5,5),(5,5)) as there is odd number of 5s and each 5 can be used only once

Rules

Here are the rules!

Assume input will only be an unsorted array of positive single digit integers

Each number will be pair up only once, which means if there are three 5s it only form 1 pair (5,5). If there are (3,3,7) it will only form 1 pair (3,7)

For the input: You can use any type of parentheses(or lack of) as long as readers can tell that the input is a single array of numbers.

For the output: It must look like an array of pairs. Where the array is the same form as your input.(If you did not use any parenheses in your input, you have to use some kind of symbols so that any readers can tell they are pairs in an array)

Test Cases

```<code>(1,2,3,4,5,5,6,7) =((4,6),(5,5),(3,7))
(1,2,3,4,5) = ()
(5,5,5,5,5) = ((5,5),(5,5))
(1,2,3,3,4,5,6,7)=((3,7),(4,6))
(9,8,7,6,4,4,3,1)=((9,1),(7,3),(6,4))
</code>```

Good luck!

The shorter an answer is, the better!

Edit 1: update the rules and Testcases from comments

Edit 2: update rules to define format of input.

Edit 3: update rules to define format of output. trying to be as accommodating as possible.

答:
PostScript (46)

This uses hand-coded binary tokens, therefore, here is a hexdump:

```<code>00000000  7b 7b 92 1a 92 3f 7b 32  92 19 92 01 31 30 92 3d  |{{...?{2....10.=|
00000010  7b 32 92 09 92 0b 3d 3d  5b 92 40 7d 69 66 92 1a  |{2....==[.@}if..|
00000020  31 92 87 7d 92 83 92 75  7d 92 65 7d 92 a3        |1..}...u}.e}..|
0000002e
</code>```

I uploaded the binary file if you want to try it out.

This expects the numbers to be on the stack. They can be prepended to the code or be supplied on the command line, e.g. when using Ghostscript like so:

```<code>gsnd -c 2 8 5 5 @ 10_golfed.ps
</code>```

If you insist on array syntax for input, then this requires two more tokens (aload pop) right at the beginning. In binary tokens, this is four more bytes.

Un-golfed and commented:

```<code>{ % stopped                   % we use stopped because we want to catch a
                              % stackunderflow when all numbers have been used up
  { % loop                    % repeat until all numbers have been popped off the stack
    % Test for all numbers on the stack whether they add up to 10 with the topmost number
    count{                    % ... nextNumber number currentTestNumber
      exch                    % ... nextNumber currentTestNumber number
      2 copy add 10 eq{       % ... nextNumber currentTestNumber number
        2 array astore ==     % ... nextNumber
        % We push "[" on the stack because we want to pop the topmost object after each iteration.
        % As [ is a one byte self delimiting token, this is nice for golfing.
        [ exit                % ... nextNumber [
      }if                     % ... nextNumber currentTestNumber number
      count 1 roll            % number ... nextNumber currentTestNumber
    }repeat                   % number ... nextNumber currentTestNumber
    pop                       % number ... nextNumber
  }loop
}stopped
</code>```

Title: Match up to 10 in an array

Body:
PostScript (46)

This uses hand-coded binary tokens, therefore, here is a hexdump:

00000000  7b 7b 92 1a 92 3f 7b 32  92 19 92 01 31 30 92 3d  |{{...?{2....10.=|
00000010  7b 32 92 09 92 0b 3d 3d  5b 92 40 7d 69 66 92 1a  |{2....==[.@}if..|
00000020  31 92 87 7d 92 83 92 75  7d 92 65 7d 92 a3        |1..}...u}.e}..|
0000002e

I uploaded the binary file if you want to try it out.

This expects the numbers to be on the stack. They can be prepended to the code or be supplied on the command line, e.g. when using Ghostscript like so:

gsnd -c 2 8 5 5 @ 10_golfed.ps

If you insist on array syntax for input, then this requires two more tokens (aload pop) right at the beginning. In binary tokens, this is four more bytes.

Un-golfed and commented:

{ % stopped                   % we use stopped because we want to catch a
                              % stackunderflow when all numbers have been used up
  { % loop                    % repeat until all numbers have been popped off the stack
    % Test for all numbers on the stack whether they add up to 10 with the topmost number
    count{                    % ... nextNumber number currentTestNumber
      exch                    % ... nextNumber currentTestNumber number
      2 copy add 10 eq{       % ... nextNumber currentTestNumber number
        2 array astore ==     % ... nextNumber
        % We push "[" on the stack because we want to pop the topmost object after each iteration.
        % As [ is a one byte self delimiting token, this is nice for golfing.
        [ exit                % ... nextNumber [
      }if                     % ... nextNumber currentTestNumber number
      count 1 roll            % number ... nextNumber currentTestNumber
    }repeat                   % number ... nextNumber currentTestNumber
    pop                       % number ... nextNumber
  }loop
}stopped


答:
Python 3, <s>93</s> 69 bytes

```<code>def f(s):z=s.pop;r=z(0);return s and':'<z(0)and(f(s),f(s))[r<'1']or r
</code>```

Input is the string as a list of characters, output is either "0" or "1"

```<code>>>>f(list("0?0:1"))
<<<"1"
</code>```

Ungolfed version:

```<code>def parse(s):
    predicate = s.pop(0)
    if s and s.pop(0) == '?':
        left, right = parse(s), parse(s)
        if predicate == '0':
            return right
        return left
    return predicate
</code>```

Another try, but with considerably more bytes:

```<code>i=input()[::-1]
a=[i[0]]
for o,z in zip(i[1::2],i[2::2]):a+=[z]if o<'?' else[[a.pop(),a.pop()][z>'0']]
print(a[0])
</code>```

Body:
Consider a grammar over the alphabet {0, 1, ?, :} defined by the production rule

s → 0 ┃ 1 ┃ 0 ? s : s ┃ 1 ? s : s

Given a string generated from s, parse it as an expression where ?: is right-associative (for example, a?B?X:Y:c?d:e?f:g means a?(B?X:Y):(c?d:(e?f:g))) and evaluate it with the following semantics:

```<code>eval(0) = 0
eval(1) = 1
eval(0?a:b) = eval(b)
eval(1?a:b) = eval(a)
</code>```

If the result is 0, output some fixed value; if the output is 1, output a different fixed value. Specify your chosen output values (e.g. 0/1, or False/True) in your answer.

Test cases

```<code>0 -> 0
1 -> 1
0?0:1 -> 1
0?1:0 -> 0
1?0:1 -> 0
1?1:0 -> 1
0?1?0:1:1 -> 1
1?0?1:1:1 -> 1
1?0:1?0:1?1:1 -> 0
1?1?1:0?1?0:0:0:0 -> 1
1?0:1?0?1:1?1:0:1?1?1:1:1?0:1 -> 0
1?1?1:0?0?1:1:0?1:0:1?1?0?0:0:1?1:0:0?1?0:1:1?0:1 -> 1
0?0?1?0?0:1:0?0:0:0?0?1:1:1?0:1:0?0?0?1:0:0?1:1:1?1?0:1:1 -> 0
</code>```

Rules

You may not use language built-ins that interpret strings as code in some programming language and run it (such as JavaScript/Perl/Ruby/Python’s eval).

That said, your code doesn’t actually have to parse and then evaluate the input string. You can take any approach the achieves equivalent results and doesn’t violate the previous rule.

Your program will be checked against perl -le 'print eval<>'.

The shortest code (in bytes) wins.

Body:
Python 3, <s>93</s> 69 bytes

def f(s):z=s.pop;r=z(0);return s and':'<z(0)and(f(s),f(s))[r<'1']or r

Input is the string as a list of characters, output is either "0" or "1"

>>>f(list("0?0:1"))
<<<"1"

Ungolfed version:

def parse(s):
    predicate = s.pop(0)
    if s and s.pop(0) == '?':
        left, right = parse(s), parse(s)
        if predicate == '0':
            return right
        return left
    return predicate

Another try, but with considerably more bytes:

i=input()[::-1]
a=[i[0]]
for o,z in zip(i[1::2],i[2::2]):a+=[z]if o<'?' else[[a.pop(),a.pop()][z>'0']]
print(a[0])


问:
Percent-Encode a String

Introduction

As some of you may know, URLs actually have a list of characters that do special things. For example, the / character separates parts of the URL, and the ?, &, and = characters are used to pass query parameters to the server. In fact, there is a bunch of characters with special functions: $&+,/:;=?@. When you need to use these characters in the URL for any other reason besides the special functions, you have to do something called percent-encoding.

Percent encoding is when you take a character's hexadecimal value and prepend a % character to the beginning of it. For example, the character ? would be encoded as %3F, and the character & would be encoded as %26. In a URL specifically, this allows you to send these characters as data via the URL without causing parsing problems. Your challenge will be to take a string, and percent-encode all of the characters that need to be encoded.

The Challenge

You shall write a program or function that takes in a single string consisting of characters with codepoints 00-FF (ASCII and Extended ASCII characters). You will then have to output or return the same string with each character percent-encoded if necessary. Built-ins that accomplish this task are not allowed, nor are standard loopholes. For reference, here is a list of every character that needs to be percent encoded:

Control characters (Codepoints 00-1F and 7F)

Extended ASCII characters (Codepoints 80-FF)

Reserved characters ($&+,/:;=?@, i.e. codepoints 24, 26, 2B, 2C, 2F, 3A, 3B, 3D, 3F, 40)

Unsafe characters (" <>#%{}|\^~[]`, i.e. codepoints 20, 22, 3C, 3E, 23, 25, 7B, 7D, 7C, 5C, 5E, 7E, 5B, 5D, 60)

Here is a the same list, but instead as a list of decimal codepoints:

```<code>0-31, 32, 34, 35, 36, 37, 38, 43, 44, 47, 58, 59, 60, 62, 61, 63, 64, 91, 92, 93, 94, 96, 123, 124, 125, 126, 127, 128-255
</code>```

This is code golf, so shortest code in bytes (or approved alternative scoring method) wins!

Test Cases

```<code>http://codegolf.stackexchange.com/  =>  http%3A%2F%2Fcodegolf.stackexchange.com%2F
[@=>]{#}  =>  %5B%40%3D%3E%5D%7B%23%7D
Test String  =>  Test%20String
ÑÉÐÔ®  =>  %D1%C9%D0%D4%AE
  =>  %0F%16%7F (Control characters 0F, 16, and 7F)
 ¡¢£¤¥¦§¨©ª«¬®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ  =>  %80%81%82%83%84%85%86%87%88%89%8A%8B%8C%8D%8E%8F%90%91%92%93%94%95%96%97%98%99%9A%9B%9C%9D%9E%9F%A0%A1%A2%A3%A4%A5%A6%A7%A8%A9%AA%AB%AC%AD%AE%AF%B0%B1%B2%B3%B4%B5%B6%B7%B8%B9%BA%BB%BC%BD%BE%BF%C0%C1%C2%C3%C4%C5%C6%C7%C8%C9%CA%CB%CC%CD%CE%CF%D0%D1%D2%D3%D4%D5%D6%D7%D8%D9%DA%DB%DC%DD%DE%DF%E0%E1%E2%E3%E4%E5%E6%E7%E8%E9%EA%EB%EC%ED%EE%EF%F0%F1%F2%F3%F4%F5%F6%F7%F8%F9%FA%FB%FC%FD%FE%FF (Extended ASCII characters 80-FF)
 !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~  =>  %20!%22%23%24%25%26'()*%2B%2C-.%2F0123456789%3A%3B%3C%3D%3E%3F%40ABCDEFGHIJKLMNOPQRSTUVWXYZ%5B%5C%5D%5E_%60abcdefghijklmnopqrstuvwxyz%7B%7C%7D%7E
</code>```

答:
PowerShell v2+, 146 bytes

```<code>param($n)37,38+0..36+43,44,47+58..64+91,93+96+123..255-ne33|%{$n=$n-replace"[$([char]$_)]",("%{0:x2}"-f$_)};$n-replace'\\','%5c'-replace'\^','%5e'
</code>```

Long because I wanted to show a different approach rather than just copy-pasting the same regex string that every else is using.

Instead here, we loop through every code point that must be percent-encoded, and do a literal -replace on the input string $n each iteration (re-saving back into $n). Then we need to account for the two special characters that need escaping, \ and ^, so those are in separate -replace elements at the end. Since we didn't re-save that final string, it's left on the pipeline and printing is implicit.

Title: Percent-Encode a String

Body:
PowerShell v2+, 146 bytes

param($n)37,38+0..36+43,44,47+58..64+91,93+96+123..255-ne33|%{$n=$n-replace"[$([char]$_)]",("%{0:x2}"-f$_)};$n-replace'\\','%5c'-replace'\^','%5e'

Long because I wanted to show a different approach rather than just copy-pasting the same regex string that every else is using.

Instead here, we loop through every code point that must be percent-encoded, and do a literal -replace on the input string $n each iteration (re-saving back into $n). Then we need to account for the two special characters that need escaping, \ and ^, so those are in separate -replace elements at the end. Since we didn't re-save that final string, it's left on the pipeline and printing is implicit.


答:
PowerShell v2+, <s>59</s> <s>58</s> <s>52</s> 51 bytes

```<code>param($n)(" $n","$n/","$n\")['.\/'.IndexOf($n[-1])]
</code>```

Takes input $n, dumps it an array index operation. We select the element of the array based on the index ['.\/'.IndexOf($n[-1]) -- i.e., based on the last character of the input $n, this will result in 0, 1, or 2. That corresponds to the appropriate string of the array. In any case, the resulting string is left on the pipeline and printing is implicit.

Test cases

```<code>PS C:\Tools\Scripts\golfing> 0..7|%{' '*$_+'.'}|%{"$_ => "+(.\wave-particle-duality.ps1 "$_")}
. =>  .
 . =>   .
  . =>    .
   . =>     .
    . =>      .
     . =>       .
      . =>        .
       . =>         .

PS C:\Tools\Scripts\golfing> '/,\,/\,\/,/\/,\/\,/\/\,\/\/'-split','|%{"$_ => "+(.\wave-particle-duality.ps1 "$_")}
/ => /\
\ => \/
/\ => /\/
\/ => \/\
/\/ => /\/\
\/\ => \/\/
/\/\ => /\/\/
\/\/ => \/\/\
</code>```

Body:
Write a program or function that takes in a nonempty single-line string. The string will either be zero or more spaces followed by one period (a particle), such as . or          ., or the string will be a sequence of one or more alternating forward and back slashes (a wave) that could start with either one, such as \ or /\/ or \/\/\/\/\/\/.

In either case, propagate the particle/wave to the right by one unit.

Specifically, in the particle case, insert a space before the ., moving it one place to the right, then output the resulting string. For example:

. →  .

 . →   .

  . →    .

   . →     .

    . →      .

     . →       .

      . →        .

       . →         .

In the wave case, append either / or \ appropriately so the wave keeps alternating and it's length increases by one, then output the resulting string. For example:

/ → /\

\ → \/

/\ → /\/

\/ → \/\

/\/ → /\/\

\/\ → \/\/

/\/\ → /\/\/

\/\/ → \/\/\

In either case, the output may not have trailing spaces but an optional trailing newline is allowed.

The shortest code in bytes wins.

Body:
PowerShell v2+, <s>59</s> <s>58</s> <s>52</s> 51 bytes

param($n)(" $n","$n/","$n\")['.\/'.IndexOf($n[-1])]

Takes input $n, dumps it an array index operation. We select the element of the array based on the index ['.\/'.IndexOf($n[-1]) -- i.e., based on the last character of the input $n, this will result in 0, 1, or 2. That corresponds to the appropriate string of the array. In any case, the resulting string is left on the pipeline and printing is implicit.

Test cases

PS C:\Tools\Scripts\golfing> 0..7|%{' '*$_+'.'}|%{"$_ => "+(.\wave-particle-duality.ps1 "$_")}
. =>  .
 . =>   .
  . =>    .
   . =>     .
    . =>      .
     . =>       .
      . =>        .
       . =>         .

PS C:\Tools\Scripts\golfing> '/,\,/\,\/,/\/,\/\,/\/\,\/\/'-split','|%{"$_ => "+(.\wave-particle-duality.ps1 "$_")}
/ => /\
\ => \/
/\ => /\/
\/ => \/\
/\/ => /\/\
\/\ => \/\/
/\/\ => /\/\/
\/\/ => \/\/\


答:
Haskell, <s>79 71 70 62 60</s> 56 bytes

Edit: Thanks to @Zgarb for 3 bytes and to @nimi for 4 bytes!

```<code>e(x:'?':r)|a:_:s<-e r=last$e s:[a:tail(e s)|x>'0']
e x=x
</code>```

This a recursive approach <s>that somewhat abuses the "some fixed value"-output rule</s>. Edit: Getting rid of the tuples doesn't only save 8 bytes, it also yields a nicer output: "0" or "1".

Ungolfed version:

```<code>eval (x:'?':r1) = if x=='1' then (a, r3) else (b, r3)
    where (a,':':r2) = eval r1
          (b, r3)    = eval r2
eval (x:r) = (x,r)
</code>```

How does it work?

The eval function traverses the implicit tree of the expressions

```<code>eval 1?0?0:1:0?1:0 -> eval 1?          :
                             eval 0?0:1 eval 0?1:0
</code>```

and returns a tuple of the form (result, rest).

The first pattern (x:'?':r1) matches x to '1' and r1 to "0?0:1:0?1:0". Recursively applying eval to r1 evaluates the sub-expression 0?0:1 and returns (0,":0?1:0"). Matching this to the pattern (a,':':r2) yields a=0 and r2=0?1:0. This sub-formula is also recursively evaluated so that b='0' and r3="". Check if x is '1' or '0' and return either (a, r3) or (b, r3).

Body:
Haskell, <s>79 71 70 62 60</s> 56 bytes

Edit: Thanks to @Zgarb for 3 bytes and to @nimi for 4 bytes!

e(x:'?':r)|a:_:s<-e r=last$e s:[a:tail(e s)|x>'0']
e x=x

This a recursive approach <s>that somewhat abuses the "some fixed value"-output rule</s>. Edit: Getting rid of the tuples doesn't only save 8 bytes, it also yields a nicer output: "0" or "1".

Ungolfed version:

eval (x:'?':r1) = if x=='1' then (a, r3) else (b, r3)
    where (a,':':r2) = eval r1
          (b, r3)    = eval r2
eval (x:r) = (x,r)

How does it work?

The eval function traverses the implicit tree of the expressions

eval 1?0?0:1:0?1:0 -> eval 1?          :
                             eval 0?0:1 eval 0?1:0

and returns a tuple of the form (result, rest).

The first pattern (x:'?':r1) matches x to '1' and r1 to "0?0:1:0?1:0". Recursively applying eval to r1 evaluates the sub-expression 0?0:1 and returns (0,":0?1:0"). Matching this to the pattern (a,':':r2) yields a=0 and r2=0?1:0. This sub-formula is also recursively evaluated so that b='0' and r3="". Check if x is '1' or '0' and return either (a, r3) or (b, r3).