问:
Call a method without calling it
Inspired by a now deleted StackOverflow question. Can you come up with a way to get a particular method executed, without explicitly calling it? The more indirect it is, the better.

Here's what I mean, exactly (C used just for exemplification, all languages accepted):

// Call this.
void the_function(void)
{
    printf("Hi there!\n");
}

int main(int argc, char** argv)
{
    the_function(); // NO! Bad! This is a direct call.
    return 0;
}
```

Original question:

答:
Ruby

Prints But who was call?.

begin
  exit

  def my_method
    $>.puts "But who was call?"
  end

rescue \
  class << $!
    self
  end

  DATA.instance_eval do
    system gets
    send eval read << (read if seek $? >> 8)
  end
end

__END__
exit 13
begin
```

<p>Alternatively...</p>

<pre class="lang-ruby prettyprint-override"><code>include Enumerable

def each
  puts "But who was call?"
end

[*self]
</code>```

Title: Call a method without calling it

Body:
Ruby

Prints But who was call?.

begin
  exit

  def my_method
    $>.puts "But who was call?"
  end

rescue \
  class << $!
    self
  end

  DATA.instance_eval do
    system gets
    send eval read << (read if seek $? >> 8)
  end
end

__END__
exit 13
begin

Alternatively...

include Enumerable

def each
  puts "But who was call?"
end

[*self]


问:
Print a 10 by 10 grid of asterisks

Background

This is a standard textbook example to demonstrate for loops.

This is one of the first programs I learnt when I started learning programming ~10 years ago.

Task

You are to print this exact text:

```<code>**********
**********
**********
**********
**********
**********
**********
**********
**********
**********
</code>```

Specs

You may have extra trailing newlines.

You may have extra trailing spaces (U+0020) at the end of each line, including the extra trailing newlines.

Scoring

This is code-golf. Shortest answer in bytes wins.

答:
S.I.L.O.S, 41 bytes

Never used S.I.L.O.S before, <s>can probably be golfed more.</s>

EDIT: Looks like there was already a S.I.L.O.S answer, but it didn't show up on the leaderboard. But I'll keep this answer because it's shorter.

```<code>a=10
lblb
printLine **********
a-1
if a b
</code>```

Try it online!

ContentLicense: CC BY-SA 3.0

Title: Print a 10 by 10 grid of asterisks

Body:
S.I.L.O.S, 41 bytes

Never used S.I.L.O.S before, <s>can probably be golfed more.</s>

EDIT: Looks like there was already a S.I.L.O.S answer, but it didn't show up on the leaderboard. But I'll keep this answer because it's shorter.

a=10
lblb
printLine **********
a-1
if a b

Try it online!


答:
PHP

```<code>$print=function(){print('Hello World!');}
$print('Goodbye.');
</code>```

in shrinked code, it is quite easy to miss the $ before the print.

and without the variable name in the code, let´s obfuscate a bit:

```<code>for($cc=64;++$cc<91;)${chr($cc);}=chr($cc);$p=$pr;$i=$in;
${"$p$i$t"}=function(){print('Hello World!');}
$print('Goodbye.');
</code>```

Title: Call a method without calling it

Body:
Inspired by a now deleted StackOverflow question. Can you come up with a way to get a particular method executed, without explicitly calling it? The more indirect it is, the better.

Here's what I mean, exactly (C used just for exemplification, all languages accepted):

// Call this.
void the_function(void)
{
    printf("Hi there!\n");
}

int main(int argc, char** argv)
{
    the_function(); // NO! Bad! This is a direct call.
    return 0;
}
```

Original question:

Body:
PHP

$print=function(){print('Hello World!');}
$print('Goodbye.');

in shrinked code, it is quite easy to miss the $ before the print.

and without the variable name in the code, let´s obfuscate a bit:

for($cc=64;++$cc<91;)${chr($cc);}=chr($cc);$p=$pr;$i=$in;
${"$p$i$t"}=function(){print('Hello World!');}
$print('Goodbye.');


问:
Exploded view of a string
Don't you love those exploded-view diagrams  in which a machine or object is taken apart into its smallest pieces?

Let's do that to a string!

The challenge

Write a program or function that

inputs a string containing only printable ASCII characters;

dissects the string into groups of non-space equal characters (the "pieces" of the string);

outputs those groups in any convenient format, with some separator between groups.

For example, given the string

```<code>Ah, abracadabra!
</code>```

the output would be the following groups:

```
!
,
A
aaaaa
bb
c
d
h
rr
```

Each group in the output contains equal characters, with spaces removed. A newline has been used as separator between groups. More about allowed formats below.

Rules

The input should be a string or an array of chars. It will only contain printable ASCII chars (the inclusive range from space to tilde). If your language does not support that, you can take the input in the form of numbers representing ASCII codes.

You can assume that the input contains at least one non-space character.

The output should consist of characters (even if the input is by means of ASCII codes). There has to be an unambiguous separator between groups, different than any non-space character that may appear in the input.

If the output is via function return, it may also be an array or strings, or an array of arrays of chars, or similar structure. In that case the structure provides the necessary separation.

A separator between characters of each group is optional. If there is one, the same rule applies: it can't be a non-space character that may appear in the input. Also, it can't be the same separator as used between groups.

Other than that, the format is flexible. Here are some examples:

The groups may be strings separated by newlines, as shown above.

The groups may be separated by any non-ASCII character, such as  ¬. The output for the above input would be the string:

```<code>!¬,¬A¬aaaaa¬bb¬c¬d¬h¬rr
</code>```

The groups may be separated by n>1 spaces (even if n is variable), with chars between each group separated by a single space:

```<code>!  ,    A   a a a a a    b b  c       d   h  r r
</code>```

The output may also be an array or list of strings returned by a function:

```<code>['!', 'A', 'aaaaa', 'bb', 'c', 'd', 'h', 'rr']
</code>```

Or an array of char arrays:

```<code>[['!'], ['A'], ['a', 'a', 'a', 'a', 'a'], ['b', 'b'], ['c'], ['d'], ['h'], ['r', 'r']]
</code>```

Examples of formats that are not allowed, according to the rules:

A comma can't be used as separator (!,,,A,a,a,a,a,a,b,b,c,d,h,r,r), because the input may contain commas.

It's not accepted to drop the separator between groups (!,Aaaaaabbcdhrr) or to use the same separator between groups and within groups (! , A a a a a a b b c d h r r).

The groups may appear in any order in the output. For example: alphabetical order (as in the examples above), order of first appearance in the string, ... The order need not be consistent or even deterministic.

Note that the input cannot contain newline characters, and A and a are different characters (grouping is case-sentitive).

Shortest code in bytes wins.

Test cases

In each test case, first line is input, and the remaining lines are the output, with each group in a different line.

Test case 1:

```
Ah, abracadabra!
!
,
A
aaaaa
bb
c
d
h
rr
```

Test case 2:

```
\o/\o/\o/
///
\\\
ooo
```

Test case 3:

```
A man, a plan, a canal: Panama!
!
,,
:
A
P
aaaaaaaaa
c
ll
mm
nnnn
p
```

Test case 4:

```
"Show me how you do that trick, the one that makes me scream" she said
""
,
S
aaaaa
cc
dd
eeeeeee
hhhhhh
ii
kk
mmmm
n
ooooo
rr
ssss
tttttt
u
ww
y
```

答:
C, 178

```<code>#define F for
#define i8 char
#define R return
z(i8*r,i8*e,i8*a){i8*b,c;F(;*a;++a)if(!isspace(c=*a)){F(b=a;*b;++b)if(r>=e)R-1;else if(*b==c)*b=' ',*r++=c;*r++='\n';}*r=0;R 0;}
</code>```

z(outputArray,LastPointerOkinOutputarray,inputArray) return -1 on error 0 ok
Note:Modify its input array too...

```<code>#define P printf
main(){char a[]="A, 12aa99dd333aA,,<<", b[256]; z(b,b+255,a);P("r=%s\n", b);}

/*
 178
 r=AA
 ,,,
 1
 2
 aaa
 99
 dd
 333
 <<
 */
</code>```

Title: Exploded view of a string

Body:
C, 178

#define F for
#define i8 char
#define R return
z(i8*r,i8*e,i8*a){i8*b,c;F(;*a;++a)if(!isspace(c=*a)){F(b=a;*b;++b)if(r>=e)R-1;else if(*b==c)*b=' ',*r++=c;*r++='\n';}*r=0;R 0;}

z(outputArray,LastPointerOkinOutputarray,inputArray) return -1 on error 0 ok
Note:Modify its input array too...

#define P printf
main(){char a[]="A, 12aa99dd333aA,,<<", b[256]; z(b,b+255,a);P("r=%s\n", b);}

/*
 178
 r=AA
 ,,,
 1
 2
 aaa
 99
 dd
 333
 <<
 */


问:
Hate/love conundrum

Challenge description

In this challenge, we only consider love and hate as feelings. If we want to utter a feeling expression of order N, we alternate between these two (starting with hate):

```<code>order | expression

1       I hate it.
2       I hate that I love it.
3       I hate that I love that I hate it.
4       I hate that I love that I hate that I love it.
</code>```

The pattern follows for every positive integer N. Given N, output the correspoinding feeling expression of order N.

Notes

Full stop (.) at the end of the expression is mandatory,

Trailing and leading whitespaces (including newlines) are permitted,

Output for a non-positive or non-integer N is undefined,

This is a code-golf challenge, so make your code as short as possible!

答:
><> (Fish), 82 Bytes

```<code>' I'oov.2coo<;oooo' it.'<
'ahv'v>'et'
oop26<^ooooo^o' that I '^!?:-1oo
'ol^'^>'ev'
</code>```

Doubt it's very efficient, but it seems to more or less work. Input is via the starting stack, which makes the score 85 Bytes if you include the size of the -v argument required to do so.

Try it online!

Title: Hate/love conundrum

Body:
><> (Fish), 82 Bytes

' I'oov.2coo<;oooo' it.'<
'ahv'v>'et'
oop26<^ooooo^o' that I '^!?:-1oo
'ol^'^>'ev'

Doubt it's very efficient, but it seems to more or less work. Input is via the starting stack, which makes the score 85 Bytes if you include the size of the -v argument required to do so.

Try it online!


问:
Subtract the next numbers

Description

Subtract the next P numbers from a N number. The next number of N is N + 1.

Look at the examples to get what I mean.

Examples:

```<code>Input: N=2,P=3
Calculate: n - (n+1) - (n+2) - (n+3)     //Ending with 3, because P=3
Calculate: 2 -  2+1  -  2+2  - 2+3       //Replacing N with 2 from Input
Calculate: 2 -  3    -  4    - 5
Output: -10

Input: N=100,P=5
Calculate: n - (n+1) - (n+2) - (n+3) - (n+4) - (n+5)
Calculate: 100-  101 -  102  -  103  -  104  - 105
Output: -415

Input: N=42,P=0
Calculate: n
Calculate: 42
Output: 42

Input: N=0,P=3
Calculate: n - (n+1) - (n+2) - (n+3)
Calculate: 0 -  1    -  2    -  3
Output: -6

Input: N=0,P=0
Calulate: n
Calculate: 0
Output: 0
</code>```

Input:

N: Integer, positive, negative or 0

P: Integer, positive or 0, not negative

Output:

Integer or String, leading 0 allowed, trailing newline allowed

Rules:

No loopholes

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

Input and Output must be as described

答:
Forth, 36 bytes

Simple computation of n - (p*n + (p^2+p) / 2)

```<code>: f 2dup dup dup * + 2/ -rot * + - ;
</code>```

Try it online

Title: Subtract the next numbers

Body:
Forth, 36 bytes

Simple computation of n - (p*n + (p^2+p) / 2)

: f 2dup dup dup * + 2/ -rot * + - ;

Try it online


问:
Sheffle tho vawols ureund!
Given an input string, output that string with all vowels a, e, i, o and u swapped at random between each other.

For example, in the string this is a test, there are 4 vowels: [i, i, a, e]. A valid shuffling of those vowels could be [a, i, e, i] therefore yielding the output thas is e tist.

About shuffling

All shuffles shall be equally likely if we consider equal vowels to be distinct. For the example above, those 24 shuffles are possible:

```
[i<sub>1</sub>, i<sub>2</sub>, a, e]    [i<sub>1</sub>, i<sub>2</sub>, e, a]    [i<sub>1</sub>, a, i<sub>2</sub>, e]    [i<sub>1</sub>, a, e, i<sub>2</sub>]
[i<sub>1</sub>, e, i<sub>2</sub>, a]    [i<sub>1</sub>, e, a, i<sub>2</sub>]    [i<sub>2</sub>, i<sub>1</sub>, a, e]    [i<sub>2</sub>, i<sub>1</sub>, e, a]
[i<sub>2</sub>, a, i<sub>1</sub>, e]    [i<sub>2</sub>, a, e, i<sub>1</sub>]    [i<sub>2</sub>, e, i<sub>1</sub>, a]    [i<sub>2</sub>, e, a, i<sub>1</sub>]
[a, i<sub>1</sub>, i<sub>2</sub>, e]    [a, i<sub>1</sub>, e, i<sub>2</sub>]    [a, i<sub>2</sub>, i<sub>1</sub>, e]    [a, i<sub>2</sub>, e, i<sub>1</sub>]
[a, e, i<sub>1</sub>, i<sub>2</sub>]    [a, e, i<sub>2</sub>, i<sub>1</sub>]    [e, i<sub>1</sub>, i<sub>2</sub>, a]    [e, i<sub>1</sub>, a, i<sub>2</sub>]
[e, i<sub>2</sub>, i<sub>1</sub>, a]    [e, i<sub>2</sub>, a, i<sub>1</sub>]    [e, a, i<sub>1</sub>, i<sub>2</sub>]    [e, a, i<sub>2</sub>, i<sub>1</sub>]
```

Each one should be equally as likely.

You may not try random shuffles of the entire string until finding one where all vowels are in the right place. In short, your code's running time shall be constant if the input is constant.

Inputs and outputs

You may assume that all letters in the input will be lowercase or uppercase. You may also support mixed casing, though this won't give you any bonus.

The input will always consist of printable ASCII characters. All characters that are in the input shall be in the output, only the vowels must be shuffled around and nothing else.

The input can be empty. There is no guarantee that the input will contain at least one vowel or at least one non-vowel.

You may take the input from STDIN, as a function parameter, or anything similar.

You may print the output to STDOUT, return it from a function, or anything similar.

Test cases

The first line is the given input. The second line is one of the possible outputs.

```<code><empty string>
<empty string>

a
a

cwm
cwm

the quick brown fox jumps over the lazy dog.
tho qeuck brewn fax jumps ovir the lozy dog.

abcdefghijklmnopqrstuvwxyz
abcdefghujklmnipqrstovwxyz

programming puzzles & code golf
pregromming pezzlos & coda gulf

fatalize
fitaleza

martin ender
mirten ander
</code>```

Scoring

This is code-golf, sa tho shirtist enswer en bytes wons.

答:
Python 3, 106 bytes

Lowercase only.

```<code>import re,random
def f(s):s=re.split('([aeiou])',s);v=s[1::2];random.shuffle(v);s[1::2]=v;return''.join(s)
</code>```

Title: Sheffle tho vawols ureund!

Body:
Python 3, 106 bytes

Lowercase only.

import re,random
def f(s):s=re.split('([aeiou])',s);v=s[1::2];random.shuffle(v);s[1::2]=v;return''.join(s)


问:
Stock Exchange KoTH
The stock market is all about the speed of knowledge. Unlike previous challenges, the current stock price is not random: it is determined by those playing the game.  If you can identify an under-priced stock before anybody else, then you've written yourself a money-making program.

Price refers to the how much people are trading the stock for, while Value refers to the amount the stock is worth at the end of the game.

Each player starts with 1000 of each stock, and 0 relative net worth.  Each stock has a secret value, and your score at the end of the game is (stockValue for each ownedStock) + netWorth.  Your net worth can be negative.  In an N-player game, there are N stocks.

Steps:

The game follows the following steps:

You are given the secret value of a single stock.

You make an offer to sell X of Y stock for $Z

All players are given the offers, and each may choose one to accept

All players are informed of accepted offers

Go back to step 2

Each of the steps are given in detail below:

void secretValue(int stockType, int value):

The value you learn is not revealed to any other player.

The value is between 0 and 1000

Low values are more like to occur than high values (squared uniform distribution)

Offer makeOffer(List<Stock> currentStock)

You can return null to make no offer.

Offer acceptOffer(List<Offer> offers)

You can return null to accept none of them

If there are no available offers, this will not be called

If you accept, your net worth goes down by $Z (can go negative) and receive X of Y stock.  The opposite occurs with the seller.

If you accept an offer, the exchange will occur immediately, and the offer will be removed so additional players cannot accept it.

void acceptedOffers(List<Offer> offers)

Includes your accepted offers as well

Static variables or writing to files is not allowed.  (No persistent data from game to game)  Non-serious contenders are allowed.

Interfaces:

```<code>public final class Stock {
    public Stock(int stockType, int amount);
    public int getType();
    public int getAmount();
    public Stock minus(Stock other);
    public Stock plus(Stock other);
    public Stock minus(int amount);
    public Stock plus(int amount);
    public Stock setAmount(int amount);
}
public class Offer {
    public Offer(Stock offer, int payment);
    public Stock getOffer();
    public int getPayment();
}
</code>```

Non-Java submissions:

All calls consist of two lines: The first line is the function being called: SecretValue, MakeOffer, AcceptOffer, AcceptedOffers, SetRandom, and the second line containing the actual data.

Stocks are formatted with a : delimiter: stockType:stockAmount.

Offers are formatted with a @ delimiter: offer@price

Lists are formatted with a ; delimiter

SecretValue is formatted with a : delimiter: stockType:value

RandomSeed is used to make your submission deterministic.  If your submission uses randomness, please use the integer value passed as the seed!

All function calls need a response.  If the response is null or void, return an empty string.

Please include a command.txt that gives the command line arguments to run your submission

Scoring

Games consisting of 1000 turns will be run multiple times.  Players will be scored according to the ELO system, and paired with players of similar skill levels.  The player with the highest final ELO score wins!  (I've modified the system so that each game, ELO scores are updated for each player pairing)

The controller includes an autodownloader, so please start your submission with a header: Name, Language.  If your submission is not in Java, each code block should start with the name of the file.  (excluding the command file, which should be the first block in your post)

Running

There are 2 ways to run this project:

Download the source code, compile and run.  You can find the source on Github.  Run git clone --recursive https://github.com/nathanmerrill/StockExchange.git

Download the JAR executable.  Submissions should be placed in your current working directory in the /submissions folder.  You can download just the JAR, just the submissions, or both

Pass in run to run the project (default option), or pass in download to download all submissions so far from this question.

Scoreboard

```<code>1.  1308.1220497323848  Cheater
2.  1242.0333695640356  InsideTrader
3.  1158.3662658295411  UncleScrooge
4.  1113.8344000358493  BlackMarket
5.  1051.8370015258993  DartMonkey
6.  983.0545446731494   WarGamer
7.  939.457423938002    Spammer
8.  901.4372529538886   DumbBot
9.  859.0519326039137   ShutUpAndTakeMyMoney
10. 852.9448222849587   VincentKasuga
11. 718.2112067329083   Profiteer
</code>```

答:
NotQuiteABanksBestFriend, Python 3

Command.txt:

```<code>python3 NotQuiteABanksBestFriend.py
</code>```

NotQuiteABanksBestFriend.py
import random
from functools import total_ordering
from io import StringIO

log = StringIO()
log.write("\n\n~~~NEW GAME~~~\n\n")

LIST_DELIMITER = ';'
STOCK_DELIMITER = ':'
OFFER_DELIMITER = '@'

JAVA_MAX_INT = 2147483647

@total_ordering
class Stock:
    @staticmethod
    def parse(string: str):
        return Stock(*map(int, string.split(STOCK_DELIMITER)))

    def __init__(self, stock_type: int, amount: int):
        self.type = stock_type
        self.amount = max(amount, 0)

    def __str__(self):
        return "T%sx%s"%(self.type, self.amount)

    def __repr__(self):
        return str(self.type)+STOCK_DELIMITER+str(int(self.amount))

    def __bool__(self):
        return bool(self.amount)

    def __eq__(self, other):
        return self.amount == other.amount

    def __lt__(self, other):
        return self.amount < other.amount

    def update(self, amount) -> 'Stock':
        return Stock(self.type, amount)

    def __mul__(self, other: int) -> 'Stock':
        return self.update(self.amount*other)

    def __floordiv__(self, other: int) -> 'Stock':
        return self.update(self.amount//other)

    def __add__(self, other: int) -> 'Stock':
        return self.update(self.amount+other)

    def __sub__(self, other: int) -> 'Stock':
        return self.update(self.amount-other)

class Offer:
    @staticmethod
    def parse(string: str) -> 'Offer':
        try:
            stock, price = string.split(OFFER_DELIMITER)
        except ValueError:
            raise Exception("Cannot unpack "+string)
        return Offer(Stock.parse(stock), int(price.strip()))

    def __init__(self, stock: Stock, price: int):
        self.stock = stock
        self.price = price
        try:
            self.price_per_unit = self.price/self.stock.amount
        except ZeroDivisionError:
            self.price_per_unit = float('inf')

    def __str__(self):
        return "%s$%s"%(self.stock, self.price)

    def __repr__(self):
        return repr(self.stock)+OFFER_DELIMITER+str(int(self.price))

def read_stock_value(value: str):
    global hidden_price, hidden_stock
    stock, price = value.split(STOCK_DELIMITER)
    hidden_price = float(price)
    hidden_stock = int(stock)
    log.write("Hidden StockID: %s\nHidden Price: %s\n"%(hidden_stock, hidden_price))

def process_input():
    handlers = {
        "SecretValue": read_stock_value,
        "RandomSeed": read_seed,
        "MakeOffer": make_offer,
        "AcceptOffer": accept_offer,
        "AcceptedOffers": accepted_offers,
    }
    method = input().strip()
    data = input().strip()
    output = handlers[method](data)
    if output is not None:
        print(repr(output))
    else:
        print()

def read_seed(seed: str):
    random.seed(int(seed))

def start():
    while True:
        process_input()

hidden_stock = None
hidden_price = None

def filter_offers(offer):
    if offer.stock.amount == 0:
        return False
    if offer.price_per_unit > 1000:
        return False
    return True

def certain_profit(offer):
    stock = offer.stock
    if stock.type == hidden_stock and offer.price_per_unit < hidden_price:
        log.write("Offer, %s is certainly profitable.\n"%offer)
        return True
    return False

def make_offer(current_stock: str):
    current_stock = list(map(Stock.parse, current_stock.split(LIST_DELIMITER)))
    own_stock = [stock for stock in current_stock if stock.type == hidden_stock]
    if own_stock and own_stock[0]:
        own_stock = own_stock[0]
        amount_sold = min(random.randrange(1,50), own_stock.amount)
        price = hidden_price+random.randrange(10,50)
        return Offer(Stock(hidden_stock, amount_sold), price*amount_sold)
    sell_stock = random.choice(current_stock)
    amount_sold = min(random.randrange(1,50), sell_stock.amount)
    price = random.randrange(1000, JAVA_MAX_INT//(amount_sold or 1))
    return Offer(Stock(sell_stock.type, amount_sold), price*(amount_sold or 1))

def accept_offer(available_offers: str):
    available_offers = list(map(Offer.parse, available_offers.split(LIST_DELIMITER)))
    filtered_offers = list(filter(filter_offers, available_offers))
    profitable = list(filter(certain_profit, filtered_offers))
    rtn_list = filtered_offers
    if profitable:
        log.write("Profitable: %s\n"%profitable)
        rtn_list = profitable
    if not rtn_list:
        return None
    accepted_offer = min(rtn_list, key=lambda offer: offer.price_per_unit)
    log.write("Bidded for %s\n"%accepted_offer)
    return accepted_offer

def accepted_offers(offers: str):
    pass

if __name__ == "__main__":
    try:
        start()
    finally:
        log.close()
```

Always tries to sell hidden stock for more than it's worth.

Title: Stock Exchange KoTH

Body:
NotQuiteABanksBestFriend, Python 3

Command.txt:

python3 NotQuiteABanksBestFriend.py

NotQuiteABanksBestFriend.py
import random
from functools import total_ordering
from io import StringIO

log = StringIO()
log.write("\n\n~~~NEW GAME~~~\n\n")

LIST_DELIMITER = ';'
STOCK_DELIMITER = ':'
OFFER_DELIMITER = '@'

JAVA_MAX_INT = 2147483647

@total_ordering
class Stock:
    @staticmethod
    def parse(string: str):
        return Stock(*map(int, string.split(STOCK_DELIMITER)))

    def __init__(self, stock_type: int, amount: int):
        self.type = stock_type
        self.amount = max(amount, 0)

    def __str__(self):
        return "T%sx%s"%(self.type, self.amount)

    def __repr__(self):
        return str(self.type)+STOCK_DELIMITER+str(int(self.amount))

    def __bool__(self):
        return bool(self.amount)

    def __eq__(self, other):
        return self.amount == other.amount

    def __lt__(self, other):
        return self.amount < other.amount

    def update(self, amount) -> 'Stock':
        return Stock(self.type, amount)

    def __mul__(self, other: int) -> 'Stock':
        return self.update(self.amount*other)

    def __floordiv__(self, other: int) -> 'Stock':
        return self.update(self.amount//other)

    def __add__(self, other: int) -> 'Stock':
        return self.update(self.amount+other)

    def __sub__(self, other: int) -> 'Stock':
        return self.update(self.amount-other)

class Offer:
    @staticmethod
    def parse(string: str) -> 'Offer':
        try:
            stock, price = string.split(OFFER_DELIMITER)
        except ValueError:
            raise Exception("Cannot unpack "+string)
        return Offer(Stock.parse(stock), int(price.strip()))

    def __init__(self, stock: Stock, price: int):
        self.stock = stock
        self.price = price
        try:
            self.price_per_unit = self.price/self.stock.amount
        except ZeroDivisionError:
            self.price_per_unit = float('inf')

    def __str__(self):
        return "%s$%s"%(self.stock, self.price)

    def __repr__(self):
        return repr(self.stock)+OFFER_DELIMITER+str(int(self.price))

def read_stock_value(value: str):
    global hidden_price, hidden_stock
    stock, price = value.split(STOCK_DELIMITER)
    hidden_price = float(price)
    hidden_stock = int(stock)
    log.write("Hidden StockID: %s\nHidden Price: %s\n"%(hidden_stock, hidden_price))

def process_input():
    handlers = {
        "SecretValue": read_stock_value,
        "RandomSeed": read_seed,
        "MakeOffer": make_offer,
        "AcceptOffer": accept_offer,
        "AcceptedOffers": accepted_offers,
    }
    method = input().strip()
    data = input().strip()
    output = handlers[method](data)
    if output is not None:
        print(repr(output))
    else:
        print()

def read_seed(seed: str):
    random.seed(int(seed))

def start():
    while True:
        process_input()

hidden_stock = None
hidden_price = None

def filter_offers(offer):
    if offer.stock.amount == 0:
        return False
    if offer.price_per_unit > 1000:
        return False
    return True

def certain_profit(offer):
    stock = offer.stock
    if stock.type == hidden_stock and offer.price_per_unit < hidden_price:
        log.write("Offer, %s is certainly profitable.\n"%offer)
        return True
    return False

def make_offer(current_stock: str):
    current_stock = list(map(Stock.parse, current_stock.split(LIST_DELIMITER)))
    own_stock = [stock for stock in current_stock if stock.type == hidden_stock]
    if own_stock and own_stock[0]:
        own_stock = own_stock[0]
        amount_sold = min(random.randrange(1,50), own_stock.amount)
        price = hidden_price+random.randrange(10,50)
        return Offer(Stock(hidden_stock, amount_sold), price*amount_sold)
    sell_stock = random.choice(current_stock)
    amount_sold = min(random.randrange(1,50), sell_stock.amount)
    price = random.randrange(1000, JAVA_MAX_INT//(amount_sold or 1))
    return Offer(Stock(sell_stock.type, amount_sold), price*(amount_sold or 1))

def accept_offer(available_offers: str):
    available_offers = list(map(Offer.parse, available_offers.split(LIST_DELIMITER)))
    filtered_offers = list(filter(filter_offers, available_offers))
    profitable = list(filter(certain_profit, filtered_offers))
    rtn_list = filtered_offers
    if profitable:
        log.write("Profitable: %s\n"%profitable)
        rtn_list = profitable
    if not rtn_list:
        return None
    accepted_offer = min(rtn_list, key=lambda offer: offer.price_per_unit)
    log.write("Bidded for %s\n"%accepted_offer)
    return accepted_offer

def accepted_offers(offers: str):
    pass

if __name__ == "__main__":
    try:
        start()
    finally:
        log.close()

Always tries to sell hidden stock for more than it's worth.


问:
Count from 1 to 100... in Roman Numerals
Write a program that count from 1 to 100 in Roman Numerals and print these numbers by standard output. Each one of the numbers must be separated by spaces.

You cannot use any built in function to transform to roman numerals nor external application or library to do so.

The desired result is

```<code>I II III IV V VI VII VIII IX X XI XII XIII XIV XV XVI XVII XVIII XIX XX XXI XXII XXIII XXIV XXV XXVI XXVII XXVIII XXIX XXX XXXI XXXII XXXIII XXXIV XXXV XXXVI XXXVII XXXVIII XXXIX XL XLI XLII XLIII XLIV XLV XLVI XLVII XLVIII XLIX L LI LII LIII LIV LV LVI LVII LVIII LIX LX LXI LXII LXIII LXIV LXV LXVI LXVII LXVIII LXIX LXX LXXI LXXII LXXIII LXXIV LXXV LXXVI LXXVII LXXVIII LXXIX LXXX LXXXI LXXXII LXXXIII LXXXIV LXXXV LXXXVI LXXXVII LXXXVIII LXXXIX XC XCI XCII XCIII XCIV XCV XCVI XCVII XCVIII XCIX C
</code>```

As it is a code golf challenge, shortest code wins.

Body:
perl 205

@r = split //, "IVXLC";
@n = (1, 5, 10, 50, 100);

for $num (1..100) {
  for($i=@r-1; $i>=0; $i--) {
    $d = int($num / $n[$i]);
    next if not $d;
    $_ .= $r[$i] x $d;
    $num -= $d * $n[$i];
  }
  $_ .= " ";
}
s/LXXXX/XC/g;
s/XXXX/XL/g;
s/VIIII/IX/g;
s/IIII/IV/g;
print;

Golfed:

@r=split//,"IVXLC";@n=(1,5,10,50,100);for$num(1..100){for($i=@r-1;$i>=0;$i--){$d=int($num/$n[$i]);next if!$d;$_.=$r[$i]x$d;$num-=$d*$n[$i];}$_.=" ";}s/LXXXX/XC/g;s/XXXX/XL/g;s/VIIII/IX/g;s/IIII/IV/g;print;


问:
The world is like a Mirror: smile and it'll sɯıןǝ qɐɔʞ
Input:

A string only containing the following characters:

abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.?! (space at the end) and two special characters (_ and |)

Output:

Mirror the text based on the position(s) of the _ and |.

_ mirrors horizontally and | mirrors vertically.

Mirroring process

The first _ indicates the start of the mirroring of that substring, the second _ the end.

If just one _ is present, you can continue on until the end of the string.

If more then two _ are present, the same process repeats.

There can only be one | in the string, and this reversed the first substring and removes the second substring.

abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.?! (space at the end) will be converted to ɐqɔpǝɟɓɥıɾʞlɯuodbɹsʇnʌʍxʎz∀ƆᗡƎℲ⅁HIſ⋊⅂WNOԀΌᴚS⊥∩ΛMX⅄Z0⇂ᘔƐ߈ϛ9ㄥ86˙¿¡ (space at the end) when it is mirrored by _ (click the link for the unicode values - requires unicode v8.0+).

Example input 1: _Will I be mirrored?!

Output 1: Mıll I qǝ ɯıɹɹoɹǝp¿¡

Example input 2: Wi_ll I be mi_rrored?!

Output 2: Will I qǝ ɯırrored?!

When it is mirrored by | we simply reverse the substring from 0 to index-of-|.

Example input 1: Will I be mirror|ed?!

Output 1: Will I be mirrorrorrim eb I lliW

Both mirrors (_ and |) can be present in the string.

General rules:

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

Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.

Standard rules apply for your answer, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters, full programs. Your call.

Default Loopholes are forbidden.

If possible, please add a link with a test for your code.

Also, please add an explanation if necessary.

Test cases:

```<code>_Will I be mirrored?!                          ->   Mıll I qǝ ɯıɹɹoɹǝp¿¡
Wi_ll I be mi_rrored?!                         ->   Will I qǝ ɯırrored?!
Will I be mirror|ed?!                          ->   Will I be mirrorrorrim eb I lliW
This_ is a test_ cont_aining bo|t_h mirrors.   ->   This ıs ɐ ʇǝsʇ contɐıuıuɓ qooq ɓuıuıɐtnoc ʇsǝʇ ɐ sı sihT
0_1_2_3_4_5|_6_7_8_9                           ->   0⇂2Ɛ4ϛϛ4Ɛ2⇂0
</code>```

答:
R, 362 362 342 339 bytes

Edit 1: I found a bug in my original (failed if there were no _ in input), fixed it, golfed some more, and I'm back at 362 where I started!

Edit 2: Golfed away 20 byes by replacing "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.?! " with paste(c(letters,LETTERS,0:9,".?! "),collapse="")

Edit 3: Removing some extra whitespace shaves off another 3 bytes.

```<code>p=strsplit
l=length
i=p(readline(),"_")[[1]]
if(l(i)-1)i[v]=chartr(paste(c(letters,LETTERS,0:9,".?! "),collapse=""),"ɐqɔpǝɟɓɥıɾʞlɯuodbɹsʇnʌʍxʎz∀ƆᗡƎℲ⅁HIſ⋊⅂WNOԀΌᴚS⊥∩ΛMX⅄Z0⇂ᘔƐ߈ϛ9ㄥ86˙¿¡ ",i[v<-seq(2,l(i),2)])
i=unlist(p(i,""))
if(l(b<-which(i=="|")-1))i[1:b+b]=rev(i[1:b])
cat(i,sep="")
</code>```

Explained:

```<code>p=strsplit               # Aliases for common functions
l=length
i=p(readline(),"_")[[1]] # Read input, split by _s. Now every even-indexed substring is one that we must
                         # mirror vertically. (R indexes from 1.)
if(l(i)-1)               # If there are any _s,
  i[v]=chartr("paste(c(letters,LETTERS,0:9,".?! "),collapse=""),
  "ɐqɔpǝɟɓɥıɾʞlɯuodbɹsʇnʌʍxʎz∀ƆᗡƎℲ⅁HIſ⋊⅂WNOԀΌᴚS⊥∩ΛMX⅄Z0⇂ᘔƐ߈ϛ9ㄥ86˙¿¡ ",
  i[v<-seq(2, l(i), 2)]
)                 # Flip the characters in the vertically-mirrored substrings
i=unlist(p(i,"")) # Split each substring into a single character object
if(l(b<-which(i=="|")-1)) # If there is a |,
  i[1:b+b]=rev(i[1:b])    # insert the reversed characters at the end of the list
cat(i,sep="")             # Print output
</code>```

Body:
R, 362 362 342 339 bytes

Edit 1: I found a bug in my original (failed if there were no _ in input), fixed it, golfed some more, and I'm back at 362 where I started!

Edit 2: Golfed away 20 byes by replacing "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.?! " with paste(c(letters,LETTERS,0:9,".?! "),collapse="")

Edit 3: Removing some extra whitespace shaves off another 3 bytes.

p=strsplit
l=length
i=p(readline(),"_")[[1]]
if(l(i)-1)i[v]=chartr(paste(c(letters,LETTERS,0:9,".?! "),collapse=""),"ɐqɔpǝɟɓɥıɾʞlɯuodbɹsʇnʌʍxʎz∀ƆᗡƎℲ⅁HIſ⋊⅂WNOԀΌᴚS⊥∩ΛMX⅄Z0⇂ᘔƐ߈ϛ9ㄥ86˙¿¡ ",i[v<-seq(2,l(i),2)])
i=unlist(p(i,""))
if(l(b<-which(i=="|")-1))i[1:b+b]=rev(i[1:b])
cat(i,sep="")

Explained:

p=strsplit               # Aliases for common functions
l=length
i=p(readline(),"_")[[1]] # Read input, split by _s. Now every even-indexed substring is one that we must
                         # mirror vertically. (R indexes from 1.)
if(l(i)-1)               # If there are any _s,
  i[v]=chartr("paste(c(letters,LETTERS,0:9,".?! "),collapse=""),
  "ɐqɔpǝɟɓɥıɾʞlɯuodbɹsʇnʌʍxʎz∀ƆᗡƎℲ⅁HIſ⋊⅂WNOԀΌᴚS⊥∩ΛMX⅄Z0⇂ᘔƐ߈ϛ9ㄥ86˙¿¡ ",
  i[v<-seq(2, l(i), 2)]
)                 # Flip the characters in the vertically-mirrored substrings
i=unlist(p(i,"")) # Split each substring into a single character object
if(l(b<-which(i=="|")-1)) # If there is a |,
  i[1:b+b]=rev(i[1:b])    # insert the reversed characters at the end of the list
cat(i,sep="")             # Print output


问:
Count the Bytes!

Challenge

Write a program which takes the URL of a PPCG answer as input and outputs the length of the answer's first code block in bytes.

Code Blocks

There are three different ways of formatting code blocks:

Four spaces before the code (- represents a space, here)

```<code>----Code goes here
</code>```

Surrounding the code in ```</code> tags:</strong></p>

<pre class="lang-html prettyprint-override"><code>```Code goes here```
</code>```

or:

```
Code goes here
```
```

<p><strong>Surrounding the code in <code>``` tags (in that order):

```<code>Code goes here</code>```
```

<h2>Rules</h2>

<p>You should only use the first code block in answer. Assume that the supplied answer will always have a code block.</p>

<p>You must find the length of the answer in <em>bytes</em>, not any other metric such as characters.</p>

<p>Solutions using the Stack Exchange Data Explorer or the Stack Exchange API are allowed. URL shorteners are disallowed.</p>

<p>Assume all programs use UTF-8 encoding.</p>

<h2>Examples</h2>

```Input:  https://codegolf.stackexchange.com/a/91904/30525
Output: 34
```

<p><strong>Link</strong></p>

<hr>

```Input:  https://codegolf.stackexchange.com/a/91693/30525
Output: 195
```

<p><strong>Link</strong></p>

<hr>

```Input:  https://codegolf.stackexchange.com/a/80691/30525
Output: 61
```

Link

Note: Despite what the answer may say, due to APL using a different encoding, 33 bytes isn't its UTF-8 byte count

Winning

The shortest code in bytes wins.

答:
jQuery JavaScript, 97 Bytes

```<code>console.log((new Blob([$("#answer-"+location.hash.substr(1)+" code").eq(0).text().trim()])).size)
</code>```

old version 151 Bytes

```<code>s=$('#answer-'+location.hash.substr(1)+' code').eq(0).text().trim();c=0;for(i=s.length;i--;)d=s.charCodeAt(i),c=d<128?c+1:d<2048?c+2:c+3;console.log(c)
</code>```

old version 163 Bytes

```<code>s=$('#answer-'+location.hash.substr(1)+' code').first().text().trim();c=0;for(i=0;i<s.length;i++){d=s.charCodeAt(i);c=(d<128)?c+1:(d<2048)?c+2:c+3;}console.log(c);
</code>```

input ist location and jQuery is active on the site

ContentLicense: CC BY-SA 4.0

Title: Count the Bytes!

Body:
jQuery JavaScript, 97 Bytes

console.log((new Blob([$("#answer-"+location.hash.substr(1)+" code").eq(0).text().trim()])).size)

old version 151 Bytes

s=$('#answer-'+location.hash.substr(1)+' code').eq(0).text().trim();c=0;for(i=s.length;i--;)d=s.charCodeAt(i),c=d<128?c+1:d<2048?c+2:c+3;console.log(c)

old version 163 Bytes

s=$('#answer-'+location.hash.substr(1)+' code').first().text().trim();c=0;for(i=0;i<s.length;i++){d=s.charCodeAt(i);c=(d<128)?c+1:(d<2048)?c+2:c+3;}console.log(c);

input ist location and jQuery is active on the site


问:
Roll the Alphabet into a Spiral
Write a program or function that, when given n, will print a spiral n characters long made up of the Latin alphabet ABCDEFGHIJKLMNOPQRSTUVWXYZ repeated as needed. This spiral should run through the alphabet only forwards.

Related to Alphabet Spiral, though the spiral runs through the alphabet forwards and backwards, and the spiral is constant.

Test cases

```<code>4   AB
    DC

40   UVWXYZ
     TGHIJA
    NSFABKB
    MREDCLC
    LQPONMD
    KJIHGFE

0

10  GHIJ
    FAB
    EDC

1000    UVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ
        TGHIJKLMNOPQRSTUVWXYZABCDEFGHIJA
        SFABCDEFGHIJKLMNOPQRSTUVWXYZABKB
        REZCDEFGHIJKLMNOPQRSTUVWXYZABCLC
        QDYBMNOPQRSTUVWXYZABCDEFGHIJCDMD
        PCXALEFGHIJKLMNOPQRSTUVWXYZKDENE
        OBWZKDEFGHIJKLMNOPQRSTUVWXALEFOF
        NAVYJCDMNOPQRSTUVWXYZABCDYBMFGPG
        MZUXIBCLCDEFGHIJKLMNOPQREZCNGHQH
        LYTWHABKBABCDEFGHIJKLMNSFADOHIRI
        KXSVGZAJAZGHIJKLMNOPQROTGBEPIJSJ
        JWRUFYZIZYFUVWXYZABCDSPUHCFQJKTK
        IVQTEXYHYXETQRSTUVWXETQVIDGRKLUL
        HUPSDWXGXWDSPUVWXYZYFURWJEHSLMVM
        GTORCVWFWVCROTGHIJAZGVSXKFITMNWN
        FSNQBUVEVUBQNSFABKBAHWTYLGJUNOXO
        ERMPATUDUTAPMREDCLCBIXUZMHKVOPYP
        DQLOZSTCTSZOLQPONMDCJYVANILWPQZQ
        CPKNYRSBSRYNKJIHGFEDKZWBOJMXQRAR
        BOJMXQRARQXMLKJIHGFELAXCPKNYRSBS
        ANILWPQZQPWVUTSRQPONMBYDQLOZSTCT
        ZMHKVOPYPONMLKJIHGFEDCZERMPATUDU
        YLGJUNOXONMLKJIHGFEDCBAFSNQBUVEV
        XKFITMNWVUTSRQPONMLKJIHGTORCVWFW
        WJEHSLMLKJIHGFEDCBAZYXWVUPSDWXGX
        VIDGRKJIHGFEDCBAZYXWVUTSRQTEXYHY
        UHCFQPONMLKJIHGFEDCBAZYXWVUFYZIZ
        TGBEDCBAZYXWVUTSRQPONMLKJIHGZAJA
        SFAZYXWVUTSRQPONMLKJIHGFEDCBABKB
        REDCBAZYXWVUTSRQPONMLKJIHGFEDCLC
        QPONMLKJIHGFEDCBAZYXWVUTSRQPONMD
                                LKJIHGFE
</code>```

Rules

Your input will be a non-negative integer 0 <= n <= 1000, but your code should theoretically handle any non-negative integer.

Your output format may be in any sane format, with delimiters if necessary.

Rotations and reflections are equivalent.

Your alphabet may be uppercase or lowercase.

The empty spaces in your spiral may be filled in with whatever non-alphabetic nulls you see fit.

The spiral itself may be in any shape you see fit. Rectangular spirals work best with ASCII solutions, but graphical solutions may be shorter with circular spirals.

Leading and trailing spaces and newlines are allowed.

This is code golf. The shortest answer in bytes (or equivalent) wins.

As always, if anything is unclear or incorrect, please let me know in the comments. Good luck and good golfing!

答:
Pyth, 32 bytes

```<code>JS@Q2ju+.t_G)Hc<*GQQ.u+NY.iJJZ]Y
</code>```

A program that prints a rectangular lower-case ASCII spiral. Depending on the input, one row or column of leading or trailing whitespace may be present.

Try it online

How it works

```<code>JS@Q2ju+.t_G)Hc<*GQQ.u+NY.iJJZ]Y  Program. Input: Q
  @Q2                             Yield sqrt(Q)
JS                                Unary range, J=[1, 2, 3, ..., floor(sqrt(q))]
                         .iJJ     Interleave J with itself, yielding [1, 1, 2, 2, 3, 3, ...
                                  floor(sqrt(Q)), floor(sqrt(Q))]
                    .u+NY    Z    Cumulatively reduce by addition with base case 0,
                                  yielding [0, 1, 2, 4, 6, 9, 12, 16, 20...]
                *GQ               Repeat the lower-case alphabet Q times
               <   Q              Truncate to legth Q
              c                   Split the above at the indices in the above list
      u                       ]Y  Reduce the above, with base case [[]]:
          _G                       Reverse
        .t  )                      Transpose
       +     H                     Add the next arm of the spiral
     j                            Join on newlines and implicitly print
</code>```

Title: Roll the Alphabet into a Spiral

Body:
Pyth, 32 bytes

JS@Q2ju+.t_G)Hc<*GQQ.u+NY.iJJZ]Y

A program that prints a rectangular lower-case ASCII spiral. Depending on the input, one row or column of leading or trailing whitespace may be present.

Try it online

How it works

JS@Q2ju+.t_G)Hc<*GQQ.u+NY.iJJZ]Y  Program. Input: Q
  @Q2                             Yield sqrt(Q)
JS                                Unary range, J=[1, 2, 3, ..., floor(sqrt(q))]
                         .iJJ     Interleave J with itself, yielding [1, 1, 2, 2, 3, 3, ...
                                  floor(sqrt(Q)), floor(sqrt(Q))]
                    .u+NY    Z    Cumulatively reduce by addition with base case 0,
                                  yielding [0, 1, 2, 4, 6, 9, 12, 16, 20...]
                *GQ               Repeat the lower-case alphabet Q times
               <   Q              Truncate to legth Q
              c                   Split the above at the indices in the above list
      u                       ]Y  Reduce the above, with base case [[]]:
          _G                       Reverse
        .t  )                      Transpose
       +     H                     Add the next arm of the spiral
     j                            Join on newlines and implicitly print


问:
Lucas Vs. The Garage Door Remote

Disclaimer

While I know there is this particular related question, my question uses two garage doors, a randomizing component, and I'm also basing this on real life events, seeing my son accidentally lowered one of said garage doors whilst I was walking out of the garage last week... Nothing like a blow to the head to get the creative juices flowing! ;)

The Background

Lucas (my 15 month old son) likes to play with the garage remote. There are two buttons on this remote, one for the left garage door, and one for the right garage door. Both buttons work in the same manner; press once to get the door to start opening, press again to stop, press again to start closing, press again to stop again, and so on.

Lucas loves this remote, he'll randomly press one of the buttons, or both, or none at all. If both are pressed, no signal is sent, but a press of one button will send out a signal.

So, the code-golf challenge is divided on two parts:

Part One

Generate a 60 character long string representing Lucas random button presses over a minute. "Random" in this case means "with an equal chance of each input at each tick". The characters are as follows:

0: Lucas has either pressed no button, or has pressed both buttons. Either way, no signal has been sent.

1: The button for the left garage door has been pressed by Lucas

2: The button for the right garage door has been pressed by Lucas

Part Two

Using the string generated in Part One, simulate the opening and closing of the two-car garage using the numbers as triggers for opening, stopping and closing these doors.

My garage doors are pretty quick (see Disclaimer above as to why).  Once you press the button it takes four seconds to be fully open or closed.

So, if closed:

0 sec: 0% open (closed); when button is pressed, door starts opening

1 sec: 25% open

2 sec: 50% open

3 sec: 75% open

4 sec: 100% open, door stops

And therefore, if open:

0 sec: 100% open; when button is pressed, door starts closing

1 sec: 75% open

2 sec: 50% open

3 sec: 25% open

4 sec: 0% open (closed), door stops

If a particular door is in motion, a signal to that same door will stop it. The next signal sent to that same door after that will send it moving in the opposite direction. If a door is stopped when it has previously been in motion and is now fully open or fully closed when the "stop" signal is received, the door will register as "stopped" in the fully-open or fully-closed state, ready to move in the opposite direction when it receives a new signal.

With this simulation, both garage doors will be initially in the closed position. So, let's look at a 10 second list of commands and see what happens if Lucas was to perform them on the remote:

```<code>2120221120
2: (L:0% stopped, R:0% opening)
1: (L:0% opening, R:25% opening)
2: (L:25% opening, R:50% stopped)
0: (L:50% opening, R:50% stopped)
2: (L:75% opening, R:50% closing)
2: (L:100% stopped, R:25% stopped)
1: (L:100% closing, R:25% stopped)
1: (L:75% stopped, R:25% stopped)
2: (L:75% stopped, R:25% opening)
0: (L:75% stopped, R:50% opening)
</code>```

Output

The first part of the output requires the display of the 60 character long string of random "0", "1" and "2" characters generated from Part One. eg.
212022112021202211202120221120212022112021202211202120221120

Below this string, is the processing of these "signals" according to the rules mentioned above of how the garage doors will behave with each respective character (on a second by second basis). You should end up with 60 lines as a result below the initial display string.

Each of these processed lines will be in the form of:
N: (L:X% XXXXXXX, R:Y% YYYYYYY) where:

N is the nth character from the respective random string, which will be in the form of a 0, 1, or 2.

X% is the percentage of openness of the left door (there is no zero padding)

XXXXXXX is the status of the left door. If the door is not in motion (i.e. not opening or closing) the status "stopped" is enforced, meaning it has been stopped in motion (only possible at 25%, 50% or 75%) or stopped when fully open (100%) or fully closed (0%). Otherwise, the door will either be "opening" or "closing".

Y% is the percentage of openness of the right door (there is no zero padding)

YYYYYYY is the status of the right door. If the door is not in motion (i.e. not opening or closing) the status "stopped" is enforced, meaning it has been stopped in motion (only possible at 25%, 50% or 75%) or stopped when fully open (100%) or fully closed (0%). Otherwise, the door will either be "opening" or "closing".

Example shown below using 10 "signals" and 10 processed lines

```<code>2120221120
2: (L:0% stopped, R:0% opening)
1: (L:0% opening, R:25% opening)
2: (L:25% opening, R:50% stopped)
0: (L:50% opening, R:50% stopped)
2: (L:75% opening, R:50% closing)
2: (L:100% stopped, R:25% stopped)
1: (L:100% closing, R:25% stopped)
1: (L:75% stopped, R:25% stopped)
2: (L:75% stopped, R:25% opening)
0: (L:75% stopped, R:50% opening)
</code>```

This is code-golf, so the shortest code will be the clear winner. I've made this a little easy by using phrases like "opening", "stopped" and "closing", which are all seven letters... so you may want to work that into your strategy.

Best of luck!

答:
Java 8 lambda, 500 characters

I did my best, here is what I came up with:

```<code>()->{String r="";int i=0,l=0,m=0,n=1,o=1,p=0,q=0;for(;i++<60;)r+=(int)(Math.random()*3);for(char s:r.toCharArray()){l+=p;m+=q;if(l>99&p>0){l=100;p=25*(((n=++n%4)-1)%2);}if(l<1&p<0){l=0;p=25*(((n=++n%4)-1)%2);}if(m>99&q>0){m=100;q=25*(((o=++o%4)-1)%2);}if(m<1&q<0){m=0;q=25*(((o=++o%4)-1)%2);}if(s<49);else if(s>49)q=25*(((o=++o%4)-1)%2);else p=25*(((n=++n%4)-1)%2);r+="\n"+s+": (L:"+l+"% "+(p<0?"closing":p>0?"opening":"stopped")+", R:"+m+"% "+(q<0?"closing":q>0?"opening":"stopped")+")";}return r;}
</code>```

Ungolfed into a complete class:

```<code>public class Q91479 {

    public static String movedDoorsCombined() {
        String result = "";
        int i = 0, leftDoor = 0, rightDoor = 0, stepLeft = 1, stepRight = 1, changeLeft = 0, changeRight = 0;

        for (; i++ < 60;) {
            result += (int) (Math.random() * 3);
        }

        for (char step : result.toCharArray()) {
            // update stats
            leftDoor += changeLeft;
            rightDoor += changeRight;

            if (leftDoor > 99 & changeLeft > 0) {
                leftDoor = 100;
                changeLeft = 25 * (((stepLeft = ++stepLeft % 4) - 1) % 2);
            }
            if (leftDoor < 1 & changeLeft < 0) {
                leftDoor = 0;
                changeLeft = 25 * (((stepLeft = ++stepLeft % 4) - 1) % 2);
            }
            if (rightDoor > 99 & changeRight > 0) {
                rightDoor = 100;
                changeRight = 25 * (((stepRight = ++stepRight % 4) - 1) % 2);
            }
            if (rightDoor < 1 & changeRight < 0) {
                rightDoor = 0;
                changeRight = 25 * (((stepRight = ++stepRight % 4) - 1) % 2);
            }

            if (step < 49) {
                // 0
            }
            else if (step > 49) {
                // right
                changeRight = 25 * (((stepRight = ++stepRight % 4) - 1) % 2);
            }
            else {
                // left
                changeLeft = 25 * (((stepLeft = ++stepLeft % 4) - 1) % 2);
            }
            result += "\n" + step + ": (L:" + leftDoor + "% "
                        + (changeLeft < 0 ? "closing" : changeLeft > 0 ? "opening" : "stopped")
                        + ", R:" + rightDoor + "% "
                        + (changeRight < 0 ? "closing" : changeRight > 0 ? "opening" : "stopped")
                        + ")";
        }
        return result;
    }
}
</code>```

Pretty straight forward. The stepLeft/stepRight variables circle from 0-3. Doing some simple maths changeLeft/changeRight hold the respective relative changes per step, which will be added to leftDoor/rightDoor. Many if statements for catching when the door has to stop on it's own.

Feel free to help me shorten this, I think there's a lot to do.

Title: Lucas Vs. The Garage Door Remote

Body:
Java 8 lambda, 500 characters

I did my best, here is what I came up with:

()->{String r="";int i=0,l=0,m=0,n=1,o=1,p=0,q=0;for(;i++<60;)r+=(int)(Math.random()*3);for(char s:r.toCharArray()){l+=p;m+=q;if(l>99&p>0){l=100;p=25*(((n=++n%4)-1)%2);}if(l<1&p<0){l=0;p=25*(((n=++n%4)-1)%2);}if(m>99&q>0){m=100;q=25*(((o=++o%4)-1)%2);}if(m<1&q<0){m=0;q=25*(((o=++o%4)-1)%2);}if(s<49);else if(s>49)q=25*(((o=++o%4)-1)%2);else p=25*(((n=++n%4)-1)%2);r+="\n"+s+": (L:"+l+"% "+(p<0?"closing":p>0?"opening":"stopped")+", R:"+m+"% "+(q<0?"closing":q>0?"opening":"stopped")+")";}return r;}

Ungolfed into a complete class:

public class Q91479 {

    public static String movedDoorsCombined() {
        String result = "";
        int i = 0, leftDoor = 0, rightDoor = 0, stepLeft = 1, stepRight = 1, changeLeft = 0, changeRight = 0;

        for (; i++ < 60;) {
            result += (int) (Math.random() * 3);
        }

        for (char step : result.toCharArray()) {
            // update stats
            leftDoor += changeLeft;
            rightDoor += changeRight;

            if (leftDoor > 99 & changeLeft > 0) {
                leftDoor = 100;
                changeLeft = 25 * (((stepLeft = ++stepLeft % 4) - 1) % 2);
            }
            if (leftDoor < 1 & changeLeft < 0) {
                leftDoor = 0;
                changeLeft = 25 * (((stepLeft = ++stepLeft % 4) - 1) % 2);
            }
            if (rightDoor > 99 & changeRight > 0) {
                rightDoor = 100;
                changeRight = 25 * (((stepRight = ++stepRight % 4) - 1) % 2);
            }
            if (rightDoor < 1 & changeRight < 0) {
                rightDoor = 0;
                changeRight = 25 * (((stepRight = ++stepRight % 4) - 1) % 2);
            }

            if (step < 49) {
                // 0
            }
            else if (step > 49) {
                // right
                changeRight = 25 * (((stepRight = ++stepRight % 4) - 1) % 2);
            }
            else {
                // left
                changeLeft = 25 * (((stepLeft = ++stepLeft % 4) - 1) % 2);
            }
            result += "\n" + step + ": (L:" + leftDoor + "% "
                        + (changeLeft < 0 ? "closing" : changeLeft > 0 ? "opening" : "stopped")
                        + ", R:" + rightDoor + "% "
                        + (changeRight < 0 ? "closing" : changeRight > 0 ? "opening" : "stopped")
                        + ")";
        }
        return result;
    }
}

Pretty straight forward. The stepLeft/stepRight variables circle from 0-3. Doing some simple maths changeLeft/changeRight hold the respective relative changes per step, which will be added to leftDoor/rightDoor. Many if statements for catching when the door has to stop on it's own.

Feel free to help me shorten this, I think there's a lot to do.


答:
C#, <s>249</s> 270 bytes

```<code>u=>{var c=new System.Net.Http.HttpClient().GetStringAsync(u).Result;var i=c.IndexOf("de>",c.IndexOf('"'+u.Split('/')[4]))+3;return System.Text.Encoding.UTF8.GetByteCount(c.Substring(i,c.IndexOf("<",i)-i-1).Replace(">",">").Replace("<","<").Replace("&","&"));};
</code>```

I've made some assumptions based on observations of the HTML of pages. Hopefully they hold true for all answer posts.

+21 bytes to unencode & to &. My answer failed to count it's own bytes. ;P

Ungolfed:

```<code>/*Func<string, int> Lambda =*/ u =>
{
    // Download HTML of the page.
    // Although new System.New.WebClient().DownloadString(u) looks shorter, it doesn't
    // preserve the UTF8 encoding.
    var c = new System.Net.Http.HttpClient().GetStringAsync(u).Result;

    // Using the answer id from the URL, find the index of the start of the code block.
    // Empirical observation has found that all code blocks are in <code> tags,
    // there are no other HTML tags that end with "de>",
    // and that '>' and '<' are encoded to '>'/'<' so no jerk can put "de>"
    // before the first code block.
    var i = c.IndexOf("de>", c.IndexOf('"' + u.Split('/')[4])) + 3;

    // Get the substring of the code block text, unencode '>'/'<'/'&' and get the byte count.
    // Again, empirical observation shows the closing </code> tag is always on a new
    // line, so always remove 1 character when getting the substring.
    return System.Text.Encoding.UTF8.GetByteCount(c.Substring(i, c.IndexOf("<", i) - i - 1).Replace(">", ">").Replace("<", "<")..Replace("&", "&"));
};
</code>```

Results:

```<code>Input:  http://codegolf.stackexchange.com/a/91904/30525
Output: 34

Input:  http://codegolf.stackexchange.com/a/91693/30525
Output: 195 (at the time of this answer the first post has 196, but I can't find the 196th
byte, even counting by hand, so assuming 195 is correct)

Input:  http://codegolf.stackexchange.com/a/80691/30525
Output: 61

Input:  http://codegolf.stackexchange.com/a/91995/58106 (this answer)
Output: 270
</code>```

Title: Count the Bytes!

Body:
Challenge

Write a program which takes the URL of a PPCG answer as input and outputs the length of the answer's first code block in bytes.

Code Blocks

There are three different ways of formatting code blocks:

Four spaces before the code (- represents a space, here)

```<code>----Code goes here
</code>```

Surrounding the code in ```</code> tags:</strong></p>

<pre class="lang-html prettyprint-override"><code>```Code goes here```
</code>```

or:

```
Code goes here
```
```

<p><strong>Surrounding the code in <code>``` tags (in that order):

```<code>Code goes here</code>```
```

<h2>Rules</h2>

<p>You should only use the first code block in answer. Assume that the supplied answer will always have a code block.</p>

<p>You must find the length of the answer in <em>bytes</em>, not any other metric such as characters.</p>

<p>Solutions using the Stack Exchange Data Explorer or the Stack Exchange API are allowed. URL shorteners are disallowed.</p>

<p>Assume all programs use UTF-8 encoding.</p>

<h2>Examples</h2>

```Input:  https://codegolf.stackexchange.com/a/91904/30525
Output: 34
```

<p><strong>Link</strong></p>

<hr>

```Input:  https://codegolf.stackexchange.com/a/91693/30525
Output: 195
```

<p><strong>Link</strong></p>

<hr>

```Input:  https://codegolf.stackexchange.com/a/80691/30525
Output: 61
```

Link

Note: Despite what the answer may say, due to APL using a different encoding, 33 bytes isn't its UTF-8 byte count

Winning

The shortest code in bytes wins.

Body:
C#, <s>249</s> 270 bytes

u=>{var c=new System.Net.Http.HttpClient().GetStringAsync(u).Result;var i=c.IndexOf("de>",c.IndexOf('"'+u.Split('/')[4]))+3;return System.Text.Encoding.UTF8.GetByteCount(c.Substring(i,c.IndexOf("<",i)-i-1).Replace("&gt;",">").Replace("&lt;","<").Replace("&amp;","&"));};

I've made some assumptions based on observations of the HTML of pages. Hopefully they hold true for all answer posts.

+21 bytes to unencode &amp; to &. My answer failed to count it's own bytes. ;P

Ungolfed:

/*Func<string, int> Lambda =*/ u =>
{
    // Download HTML of the page.
    // Although new System.New.WebClient().DownloadString(u) looks shorter, it doesn't
    // preserve the UTF8 encoding.
    var c = new System.Net.Http.HttpClient().GetStringAsync(u).Result;

    // Using the answer id from the URL, find the index of the start of the code block.
    // Empirical observation has found that all code blocks are in <code> tags,
    // there are no other HTML tags that end with "de>",
    // and that '>' and '<' are encoded to '&gt;'/'&lt;' so no jerk can put "de>"
    // before the first code block.
    var i = c.IndexOf("de>", c.IndexOf('"' + u.Split('/')[4])) + 3;

    // Get the substring of the code block text, unencode '>'/'<'/'&' and get the byte count.
    // Again, empirical observation shows the closing </code> tag is always on a new
    // line, so always remove 1 character when getting the substring.
    return System.Text.Encoding.UTF8.GetByteCount(c.Substring(i, c.IndexOf("<", i) - i - 1).Replace("&gt;", ">").Replace("&lt;", "<")..Replace("&amp;", "&"));
};

Results:

Input:  http://codegolf.stackexchange.com/a/91904/30525
Output: 34

Input:  http://codegolf.stackexchange.com/a/91693/30525
Output: 195 (at the time of this answer the first post has 196, but I can't find the 196th
byte, even counting by hand, so assuming 195 is correct)

Input:  http://codegolf.stackexchange.com/a/80691/30525
Output: 61

Input:  http://codegolf.stackexchange.com/a/91995/58106 (this answer)
Output: 270


问:
Traveling on a flat Earth
Coordinates in the flat-Earth world consist of latitude (x) and longitude (y), which are integers in the range 0...9999. Much like Gaussian integers, but they are always written using this notation:

```<code>411S 370E
</code>```

That is, with S or N appended to the latitude, and E or W appended to the longitude, with space(s) between the two components.

Goal

Write a program (not a function) that reads two coordinates, separated by whitespace, and outputs their sum. The first coordinate is a starting point, the second one is a displacement, and the output is the resulting position.

Input/Output

Since this challenge is partially about formatting, I'll try to define the input and output formats unambiguously.

The preferred input format has 1 space between the coordinate components, no leading zeros, and a newline character between the two coordinates. The program must be able to read the preferred format.

The output can contain any amount of whitespace and leading zeros. If it's different from the preferred input format, the program must be able to read this format too.

Just to make it clear, the input cannot (will not) contain any additional formatting characters. Just spaces and newlines where needed.

Scoring

This is an experiment on a new winning condition. I'll choose the winner by accepting an answer in a few weeks. If a better answer appears afterwards, I'll change the accepted answer.

The score for the program is its byte count. The winning program is one that is shorter than 400 bytes, has the fewest byte count, but is written in the most verbose programming language. To determine the winner:

Remove programs with byte count 400 or more (they can participate but cannot win)

Consider only the shortest program for each programming language

The longest program wins

Polyglots compete against programs in all languages in which they are valid (e.g. if a program is valid in both bash and sh, it competes against programs in both languages).

Test cases

In the test cases, the first two lines are the input, and the third line is the output.

```<code>0S 0E
0S 0W
0N 0E
</code>```

(the direction of zero doesn't matter, both in input and output)

```<code>0S 9999E
9999N 9999W
9999N 0E
</code>```

(maximal values)

```<code>42S 314W
42N 2718W
0N 3032W
</code>```

(the direction of zero doesn't matter in the output)

```<code>5555N 8888W
7777S 0E
2222S 8888W
</code>```

(no negative values; change the direction if you need to change the sign)

```<code>0001N        4545W
0999N        5454W
1000N        9999W
</code>```

(if the program outputs leading zeros and several spaces, it must be able to read them; it must also be able to read input that doesn't contain them)

```<code>8888N 8888W
9999N 9999W
</code>```

(invalid input - any behavior is acceptable, including crash and infinite loop)

答:
Befunge-93, 240 bytes

```<code>v
  v$      <
>&>~:" "-!|
vp01p02   <
  v$      <
>&>~:" "-!|
vp03p04   <
  v$      <
>&>~:" "-!|
vp05p06   <
  v$      <
>&>~:" "-!|
 vp07p08  <
v>30g70g40g80g-!
_-:0` v1+
\v\g04_01-*80g
v>10g50g20g60g-!
_-:0` v1+
\v\g02_01-*60g
@>.," ",.,
</code>```

Note that the interpreter has a single line input box. Pasting the preferred format replaces the newline with a space. Getting integer values with & already consumes leading spaces and zeros, so the preferred format can be read to the stack with &~&~&~&~ alone. Adding steps to put the values in a blank line so that one can retrieve and compare the vectors one coordinate at a time, the following 136 byte program (excluding  notes right of line) can be used:

```<code>v                      | blank line to store data
> &10p~20p&30p~40pv    | read and store first vector
 vp08~p07&p06~p05&<    | (backwards) read and store second vector
v>30g70g40g80g-!       | load E/W coordinates
_-:0` v1+              | subtract or add (based on direction)
\v\g04_01-*80g         | change directions if negative
v>10g50g20g60g-!       | load N/S coordinates
_-:0` v1+              | subtract or add (based on direction)
\v\g02_01-*60g         | change directions if negative
@>.," ",.,             | output
</code>```

The Catch: The output forces an additional space after integers, so it is impossible to output in the preferred format. For example, output will appears as 1000 N 9999 W instead of 1000N 9999W. To check for and ignore spaces before each coordinate's direction on input, four additional loops (one for each coordinate) are needed. A single loop is shown below:

```<code>  v$      <            | throw out " " and repeat
>&>~:" "-!|            | (start read number) get and check character
vp01p02   <            | store
</code>```

The resulting program can have multiple spaces anywhere in the input (except between digits).

Example Input: 0001   N   4545   W   0999   N   5454   W

Title: Traveling on a flat Earth

Body:
Befunge-93, 240 bytes

v
  v$      <
>&>~:" "-!|
vp01p02   <
  v$      <
>&>~:" "-!|
vp03p04   <
  v$      <
>&>~:" "-!|
vp05p06   <
  v$      <
>&>~:" "-!|
 vp07p08  <
v>30g70g40g80g-!
_-:0` v1+
\v\g04_01-*80g
v>10g50g20g60g-!
_-:0` v1+
\v\g02_01-*60g
@>.," ",.,

Note that the interpreter has a single line input box. Pasting the preferred format replaces the newline with a space. Getting integer values with & already consumes leading spaces and zeros, so the preferred format can be read to the stack with &~&~&~&~ alone. Adding steps to put the values in a blank line so that one can retrieve and compare the vectors one coordinate at a time, the following 136 byte program (excluding  notes right of line) can be used:

v                      | blank line to store data
> &10p~20p&30p~40pv    | read and store first vector
 vp08~p07&p06~p05&<    | (backwards) read and store second vector
v>30g70g40g80g-!       | load E/W coordinates
_-:0` v1+              | subtract or add (based on direction)
\v\g04_01-*80g         | change directions if negative
v>10g50g20g60g-!       | load N/S coordinates
_-:0` v1+              | subtract or add (based on direction)
\v\g02_01-*60g         | change directions if negative
@>.," ",.,             | output

The Catch: The output forces an additional space after integers, so it is impossible to output in the preferred format. For example, output will appears as 1000 N 9999 W instead of 1000N 9999W. To check for and ignore spaces before each coordinate's direction on input, four additional loops (one for each coordinate) are needed. A single loop is shown below:

  v$      <            | throw out " " and repeat
>&>~:" "-!|            | (start read number) get and check character
vp01p02   <            | store

The resulting program can have multiple spaces anywhere in the input (except between digits).

Example Input: 0001   N   4545   W   0999   N   5454   W


问:
The longest period iterating quine
As we know, a quine is a program that outputs its own source code. However, it's also possible to write a program that outputs another, different program, that outputs the first program again. For example, the Python 2 program

```<code>x = '''x = {}
print 'print '+'"'*3+x.format("'"*3+x+"'"*3)+'"'*3'''
print 'print '+'"'*3+x.format("'"*3+x+"'"*3)+'"'*3
</code>```

will, when run, output the following text:

```<code>print """x = '''x = {}
print 'print '+'"'*3+x.format("'"*3+x+"'"*3)+'"'*3'''
print 'print '+'"'*3+x.format("'"*3+x+"'"*3)+'"'*3"""
</code>```

When run as a Python program, this will output the original code again. This is called an iterating quine. Because you have to run it twice to get the original code back, we say it has period 2. But of course, much higher periods are possible.

Your challenge is to write an iterating quine with as long a period as you can, in 100 bytes or less, in the language of your choice. (Note that my example above doesn't fit this spec, as it's 119 bytes, including the trailing newline.)

Please note the following rules and clarifications:

The usual quine rules apply, i.e. your program can't use language features that would let it access its own source code directly.

The iterated outputs have to eventually loop back to exactly your original code, and you have to include a demonstration or proof that it will.

You must also include an explanation of why the cycle is as long as you say it is. This doesn't have to be at the level of a mathematical proof, but it should be convincing to someone familiar with your language. (This rule is here because I expect some of the answers to involve very, very large numbers.)

It's fine to say something like "at least 1,000,000 iterations" rather than giving the exact number, as long as you can prove that it is at least that long. In this case, your score would be 1,000,000. Otherwise, your score is the period of your quine.

The 100 byte limit only applies to your initial program - the programs it outputs can be longer, though of course they'll eventually have to get back down to 100 bytes in order to output your original code.

You can assume your machine has infinite RAM and infinite runtime, but you can't assume unlimited precision data types (such as integers) if your language doesn't have them. You can assume there is no limit to the length of input your parser can handle.

The highest score wins.

Please note: there is an existing challenge called Quit Whining; Start Quining that also involves iterating quines. However, aside from being based on the same concept, these are completely different types of challenge. The other one is straight up code golf, whereas this one is (intentionally!) really a busy beaver problem in disguise. The techniques needed to produce a good answer to this question are likely to be very different from what's needed to answer the other question, and this is very much by design.

Title: The longest period iterating quine

Body:
Mathematica, period <s>E8.5678#3</s> <s>E2.1923#4</s> ~E6.2695#3#2

Print[ToString[#0, InputForm], "[", #1 - 1 /. 0 -> "Nest[#!,9,9^9^99!]", "]"] & [Nest[#!,9,9^9^99!]]

Note that the scores are described in Hyper-E notation. The iterations replace the final Nest[#!,9,9^9^99!] with the decimal expansions of Nest[#!,9,9^9^99!] - 1, Nest[#!,9,9^9^99!] - 2, Nest[#!,9,9^9^99!] - 3, ..., 3, 2, 1, and back to Nest[#!,9,9^9^99!].


问:
The Squiggly Sequence

All credits to Adnan for coming up with this challenge.

My last challenge, before I go on break.

Task

Given positive integer n, if n is odd, repeat / that many times; if n is even, repeat \ that many times.

(Seriously, the testcases would be much clearer than this description, so just look at the testcases.)

Specs

Any reasonable input/output format.

Standard loopholes apply.

Testcases

```<code>n output
1 /
2 \\
3 ///
4 \\\\
5 /////
6 \\\\\\
</code>```

答:
Lua (<s>33</s> 44 Bytes)

Never tried golfing with Lua before.

Shortest program I could come up with:

n=io.read()print(({'\\','/'})[n%2+1]:rep(n))

Title: The Squiggly Sequence


问:
ROT-13 transform standard input

Task

Read a string of characters and produce the ROT13 of it. All characters besides [a-zA-Z] should be output verbatim. Each letter in the output may be in any case you wish (you do not have to preserve it).

ROT13 is a simple substitution cipher where each letter of the alphabet is rotated by 13 places (it doesn't matter whether you do it forward or backward, since ROT13 is it's own inverse).

Examples

```<code>Input
Output

Hello, world!
Uryyb, jbeyq!

Code Golf and Coding Challenges is awesome.
Pbqr Tbys naq Pbqvat Punyyratrf vf njrfbzr.

Mod abuse!1!!1
Zbq nohfr!1!!1
</code>```

答:
Bash - 5 chars

```<code>rot13
</code>```

Title: ROT-13 transform standard input

Body:
Bash - 5 chars

rot13

ContentLicense: CC BY-SA 2.5


问:
Implement glob Matcher
Implement a function of pattern and string to be matched, return true if the pattern matches the WHOLE string, otherwise false.

Our glob pattern syntax is:

? matches any one character

+ matches one or more characters

* matches zero or more characters

\ escapes

Rules:

No eval, no converting into regular expression, no calling a system glob function.

I/O are not required: you can just write a function

Shortest wins

Examples:

```<code>glob('abc', 'abc') => true
glob('abc', 'abcdef') => false IMPORTANT!
glob('a??', 'aww') => true
glob('a*b', 'ab') => true
glob('a*b', 'agwijgwbgioeb') => true
glob('a*?', 'a') => false
glob('?*', 'def') => true
glob('5+', '5ggggg') => true
glob('+', '') => false
glob('a\*b', 'a*b') => true
</code>```

Here is a tip to get started: http://en.wikipedia.org/wiki/Backtracking

答:
Golfscript - 82 chars

```<code>{1,\@n+:|;{:<;{:I)I|="\\+*?"[<]+?[{|=<={I))}*}I~{I\C}{}.{;}]=~}:C%}/{|>'*'-n=},}:g
</code>```

Assumes that there are no newlines in the strings. Returns an empty array for false, and a non-empty array for true (consistent with golfscript definition of true/false).

This is a non-recursive solution (except for consecutive *s), which maintains a list of the positions in the pattern string i such that pattern[0..i] matches string[0..cur].

This has the potential to run for a very long time. You can add .& after :C% to prevent this.

Title: Implement glob Matcher

Body:
Golfscript - 82 chars

{1,\@n+:|;{:<;{:I)I|="\\+*?"[<]+?[{|=<={I))}*}I~{I\C}{}.{;}]=~}:C%}/{|>'*'-n=},}:g

Assumes that there are no newlines in the strings. Returns an empty array for false, and a non-empty array for true (consistent with golfscript definition of true/false).

This is a non-recursive solution (except for consecutive *s), which maintains a list of the positions in the pattern string i such that pattern[0..i] matches string[0..cur].

This has the potential to run for a very long time. You can add .& after :C% to prevent this.


答:
Python, 168

```<code>r=lambda n,l,v:(r(n,l[1:],v[1:])if n<v[0]else l[0]+r(n-v[0],l,v))if n else''
for i in range(1,101):print r(i,'C XC L XL X IX V IV I'.split(),[100,90,50,40,10,9,5,4,1]),
</code>```

Explanation

Using these values, take the largest value not greater than n and subtract it from n.  Repeat until n is 0.

```<code>'C'  = 100
'XC' = 90
'L'  = 50
'XL' = 40
'X'  = 10
'IX' = 9
'V'  = 5
'IV' = 4
'I'  = 1
</code>```

Title: Count from 1 to 100... in Roman Numerals

Body:
Write a program that count from 1 to 100 in Roman Numerals and print these numbers by standard output. Each one of the numbers must be separated by spaces.

You cannot use any built in function to transform to roman numerals nor external application or library to do so.

The desired result is

```<code>I II III IV V VI VII VIII IX X XI XII XIII XIV XV XVI XVII XVIII XIX XX XXI XXII XXIII XXIV XXV XXVI XXVII XXVIII XXIX XXX XXXI XXXII XXXIII XXXIV XXXV XXXVI XXXVII XXXVIII XXXIX XL XLI XLII XLIII XLIV XLV XLVI XLVII XLVIII XLIX L LI LII LIII LIV LV LVI LVII LVIII LIX LX LXI LXII LXIII LXIV LXV LXVI LXVII LXVIII LXIX LXX LXXI LXXII LXXIII LXXIV LXXV LXXVI LXXVII LXXVIII LXXIX LXXX LXXXI LXXXII LXXXIII LXXXIV LXXXV LXXXVI LXXXVII LXXXVIII LXXXIX XC XCI XCII XCIII XCIV XCV XCVI XCVII XCVIII XCIX C
</code>```

As it is a code golf challenge, shortest code wins.

Body:
Python, 168

r=lambda n,l,v:(r(n,l[1:],v[1:])if n<v[0]else l[0]+r(n-v[0],l,v))if n else''
for i in range(1,101):print r(i,'C XC L XL X IX V IV I'.split(),[100,90,50,40,10,9,5,4,1]),

Explanation

Using these values, take the largest value not greater than n and subtract it from n.  Repeat until n is 0.

'C'  = 100
'XC' = 90
'L'  = 50
'XL' = 40
'X'  = 10
'IX' = 9
'V'  = 5
'IV' = 4
'I'  = 1


答:
Java 7, <s>504</s> 502 bytes

```<code>import java.util.*;String c(String s){Map m=new HashMap();int i=0,j;while(i<67)m.put("abcdefghijklmnopqrstuvwxyzABBCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.?! ".charAt(i),"ɐqɔpǝɟɓɥıɾʞlɯuodbɹsʇnʌʍxʎz∀ƆᗡƎℲ⅁HIſ⋊⅂WNOԀΌᴚS⊥∩ΛMX⅄Z0⇂ᘔƐ߈ϛ9ㄥ86˙¿¡ ".charAt(i++));String q=s.split("\\|")[0],z[]=(q+(s.equals(q)?"":new StringBuffer(q).reverse()+"")).split("_"),r="";for(i=-1;++i<z.length;){q="";for(char c:z[i].toCharArray())q+=m.get(c);r+=i%2<1?z[i]:q;}return r;}
</code>```

Of course I'll have to answer my own challenge again. And.. it's long.. xD

Ungolfed & test cases:

Try it here.

```<code>import java.util.*;
class M{
  static String c(String s){
    Map m = new HashMap();
    int i = 0,
        j;
    while(i < 67){
      m.put("abcdefghijklmnopqrstuvwxyzABBCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.?! ".charAt(i),
          "ɐqɔpǝɟɓɥıɾʞlɯuodbɹsʇnʌʍxʎz∀ƆᗡƎℲ⅁HIſ⋊⅂WNOԀΌᴚS⊥∩ΛMX⅄Z0⇂ᘔƐ߈ϛ9ㄥ86˙¿¡ ".charAt(i++));
    }
    String q = s.split("\\|")[0],
           z[] = (q + (s.equals(q)
                        ? ""
                        : new StringBuffer(q).reverse() + "")
                 ).split("_"),
           r = "";
    for(i = -1; ++i < z.length;){
      q = "";
      for(char c : z[i].toCharArray()){
        q += m.get(c);
      }
      r += i%2 < 1
            ? z[i]
            : q;
    }
    return r;
  }

  public static void main(String[] a){
    System.out.println(c("_Will I be mirrored?!"));
    System.out.println(c("Wi_ll I be mi_rrored?!"));
    System.out.println(c("Will I be mirror|ed?!"));
    System.out.println(c("This_ is a test_ cont_aining bo|t_h mirrors."));
    System.out.println(c("0_1_2_3_4_5|_6_7_8_9"));
  }
}
</code>```

Output:

```<code>Mıll I qǝ ɯıɹɹoɹǝp¿¡
Will I qǝ ɯırrored?!
Will I be mirrorrorrim eb I lliW
This ıs ɐ ʇǝsʇ contɐıuıuɓ qooq ɓuıuıɐtnoc ʇsǝʇ ɐ sı sihT
0⇂2Ɛ4ϛϛ4Ɛ2⇂0
</code>```

Title: The world is like a Mirror: smile and it'll sɯıןǝ qɐɔʞ

Body:
Input:

A string only containing the following characters:

abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.?! (space at the end) and two special characters (_ and |)

Output:

Mirror the text based on the position(s) of the _ and |.

_ mirrors horizontally and | mirrors vertically.

Mirroring process

The first _ indicates the start of the mirroring of that substring, the second _ the end.

If just one _ is present, you can continue on until the end of the string.

If more then two _ are present, the same process repeats.

There can only be one | in the string, and this reversed the first substring and removes the second substring.

abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.?! (space at the end) will be converted to ɐqɔpǝɟɓɥıɾʞlɯuodbɹsʇnʌʍxʎz∀ƆᗡƎℲ⅁HIſ⋊⅂WNOԀΌᴚS⊥∩ΛMX⅄Z0⇂ᘔƐ߈ϛ9ㄥ86˙¿¡ (space at the end) when it is mirrored by _ (click the link for the unicode values - requires unicode v8.0+).

Example input 1: _Will I be mirrored?!

Output 1: Mıll I qǝ ɯıɹɹoɹǝp¿¡

Example input 2: Wi_ll I be mi_rrored?!

Output 2: Will I qǝ ɯırrored?!

When it is mirrored by | we simply reverse the substring from 0 to index-of-|.

Example input 1: Will I be mirror|ed?!

Output 1: Will I be mirrorrorrim eb I lliW

Both mirrors (_ and |) can be present in the string.

General rules:

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

Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.

Standard rules apply for your answer, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters, full programs. Your call.

Default Loopholes are forbidden.

If possible, please add a link with a test for your code.

Also, please add an explanation if necessary.

Test cases:

```<code>_Will I be mirrored?!                          ->   Mıll I qǝ ɯıɹɹoɹǝp¿¡
Wi_ll I be mi_rrored?!                         ->   Will I qǝ ɯırrored?!
Will I be mirror|ed?!                          ->   Will I be mirrorrorrim eb I lliW
This_ is a test_ cont_aining bo|t_h mirrors.   ->   This ıs ɐ ʇǝsʇ contɐıuıuɓ qooq ɓuıuıɐtnoc ʇsǝʇ ɐ sı sihT
0_1_2_3_4_5|_6_7_8_9                           ->   0⇂2Ɛ4ϛϛ4Ɛ2⇂0
</code>```

Body:
Java 7, <s>504</s> 502 bytes

import java.util.*;String c(String s){Map m=new HashMap();int i=0,j;while(i<67)m.put("abcdefghijklmnopqrstuvwxyzABBCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.?! ".charAt(i),"ɐqɔpǝɟɓɥıɾʞlɯuodbɹsʇnʌʍxʎz∀ƆᗡƎℲ⅁HIſ⋊⅂WNOԀΌᴚS⊥∩ΛMX⅄Z0⇂ᘔƐ߈ϛ9ㄥ86˙¿¡ ".charAt(i++));String q=s.split("\\|")[0],z[]=(q+(s.equals(q)?"":new StringBuffer(q).reverse()+"")).split("_"),r="";for(i=-1;++i<z.length;){q="";for(char c:z[i].toCharArray())q+=m.get(c);r+=i%2<1?z[i]:q;}return r;}

Of course I'll have to answer my own challenge again. And.. it's long.. xD

Ungolfed & test cases:

Try it here.

import java.util.*;
class M{
  static String c(String s){
    Map m = new HashMap();
    int i = 0,
        j;
    while(i < 67){
      m.put("abcdefghijklmnopqrstuvwxyzABBCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.?! ".charAt(i),
          "ɐqɔpǝɟɓɥıɾʞlɯuodbɹsʇnʌʍxʎz∀ƆᗡƎℲ⅁HIſ⋊⅂WNOԀΌᴚS⊥∩ΛMX⅄Z0⇂ᘔƐ߈ϛ9ㄥ86˙¿¡ ".charAt(i++));
    }
    String q = s.split("\\|")[0],
           z[] = (q + (s.equals(q)
                        ? ""
                        : new StringBuffer(q).reverse() + "")
                 ).split("_"),
           r = "";
    for(i = -1; ++i < z.length;){
      q = "";
      for(char c : z[i].toCharArray()){
        q += m.get(c);
      }
      r += i%2 < 1
            ? z[i]
            : q;
    }
    return r;
  }

  public static void main(String[] a){
    System.out.println(c("_Will I be mirrored?!"));
    System.out.println(c("Wi_ll I be mi_rrored?!"));
    System.out.println(c("Will I be mirror|ed?!"));
    System.out.println(c("This_ is a test_ cont_aining bo|t_h mirrors."));
    System.out.println(c("0_1_2_3_4_5|_6_7_8_9"));
  }
}

Output:

Mıll I qǝ ɯıɹɹoɹǝp¿¡
Will I qǝ ɯırrored?!
Will I be mirrorrorrim eb I lliW
This ıs ɐ ʇǝsʇ contɐıuıuɓ qooq ɓuıuıɐtnoc ʇsǝʇ ɐ sı sihT
0⇂2Ɛ4ϛϛ4Ɛ2⇂0


答:
Retina, 176 bytes

```<code>\|.+
:$`
O$^`:|(?!^)\G.

:

T`w.?!`_0⇂ᘔƐ߈ϛ9ㄥ86∀:ƆᗡƎℲ⅁\HIſ⋊⅂WN\OԀΌᴚS⊥∩ΛMX⅄Zɐqɔ\pǝɟɓɥıɾʞ\lɯu\o\dbɹsʇnʌʍxʎz˙¿¡`_[^_]*_?
:

</code>```

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

Body:
Retina, 176 bytes

\|.+
:$`
O$^`:|(?!^)\G.

:

T`w.?!`_0⇂ᘔƐ߈ϛ9ㄥ86∀:ƆᗡƎℲ⅁\HIſ⋊⅂WN\OԀΌᴚS⊥∩ΛMX⅄Zɐqɔ\pǝɟɓɥıɾʞ\lɯu\o\dbɹsʇnʌʍxʎz˙¿¡`_[^_]*_?
:

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


问:
Shortest infinite loop producing no output
Your task is to create the shortest infinite loop!

The point of this challenge is to create an infinite loop producing no output, unlike its possible duplicate. The reason to this is because the code might be shorter if no output is given.

Rules

Each submission must be a full program.

You must create the shortest infinite loop.

Even if your program runs out of memory eventually, it is still accepted as long as it is running the whole time from the start to when it runs out of memory. Also when it runs out of memory, it should still not print anything to STDERR.

The program must take no input (however, reading from a file is allowed), and should not print anything to STDOUT. Output to a file is also forbidden.

The program must not write anything to STDERR.

Feel free to use a language (or language version) even if it's newer than this challenge.
-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. :D

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 infinite loop program. This is about finding the shortest infinite loop program in every language. Therefore, I will not accept an answer.

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 Brainf**k-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.

There should be a website such as Wikipedia, Esolangs, or GitHub for the language. For example, if the language is CJam, then one could link to the site in the header like #[CJam](http://sourceforge.net/p/cjam/wiki/Home/), X bytes.

Standard loopholes are not allowed.

(I have taken some of these rules from Martin Büttner's "Hello World" challenge)

Please feel free to post in the comments to tell me how this challenge could be  improved.

Catalogue

This is a Stack Snippet which generates both an alphabetical catalogue of the used languages, and an overall leaderboard. To make sure your answer shows up, please start it with this Markdown header:

```<code># Language name, X bytes
</code>```

Obviously replacing Language name and X bytes with the proper items. If you want to link to the languages' website, use this template, as posted above:

```<code>#[Language name](http://link.to/the/language), X bytes
</code>```

Now, finally, here's the snippet: (Try pressing "Full page" for a better view.)

var QUESTION_ID=59347;var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";var COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk";var OVERRIDE_USER=41805;var answers=[],answers_hash,answer_ids,answer_page=1,more_answers=true,comment_page;function answersUrl(index){return"//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"//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}#answer-list{padding:10px;width:500px;float:left}#language-list{padding:10px;padding-right:40px;width:500px;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">

Shortest Solution by Language

Language	User	Score

Leaderboard

	Author	Language	Size

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

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

```

答:
Logicode, 24 bytes

```<code>circ r(a)->r(a)
out r(1)
</code>```

Logicode is a new language that I made recently. It only consists of the basic logic gates AND, OR and NOT.

It also contains some nifty stuff like conditionals, make-your-own circuits, and output.

Basically, the first line declares a new circuit, r, with an argument a, and declares the output of the circuit to be r(a). This basically results in an infinite loop.

out r(1) outputs r(1).

Body:
Logicode, 24 bytes

circ r(a)->r(a)
out r(1)

Logicode is a new language that I made recently. It only consists of the basic logic gates AND, OR and NOT.

It also contains some nifty stuff like conditionals, make-your-own circuits, and output.

Basically, the first line declares a new circuit, r, with an argument a, and declares the output of the circuit to be r(a). This basically results in an infinite loop.

out r(1) outputs r(1).


答:
Java 7, <s>314</s> 313 bytes

```<code>int c(String u)throws Exception{String x="utf8",s=new java.util.Scanner(new java.net.URL(u).openStream(),x).useDelimiter("\\A").next();int j=s.indexOf("de>",s.indexOf('"'+u.split("/")[4]))+3;return s.substring(j,s.indexOf("<",j)-1).replace(">",">").replace("<","<").replace("&","&").getBytes(x).length;}
</code>```

Shamelessly stolen from @milk's C# answer and ported to Java 7.

NOTE: This assumes all code is in  blocks. Currently it won't work with just ```</code> tags (but who uses those anyway?.. ;p).</p>
<p><strong>Ungolfed & test cases:</strong></p>
```class M{
  static int c(String u) throws Exception{
    String x = "utf8",
           s = new java.util.Scanner(new java.net.URL(u).openStream(), x).useDelimiter("\\A").next();
    int j = s.indexOf("de>", s.indexOf('"'+u.split("/")[4])) + 3;
    return s.substring(j, s.indexOf("<", j) - 1).replace(">", ">").replace("<", "<").replace("&", "&")
        .getBytes(x).length;
  }

  public static void main(String[] a) throws Exception{
    System.out.println(c("https://codegolf.stackexchange.com/a/91904/30525"));
    System.out.println(c("https://codegolf.stackexchange.com/a/91693/30525"));
    System.out.println(c("https://codegolf.stackexchange.com/a/80691/30525"));
    System.out.println(c("https://codegolf.stackexchange.com/a/91995/58106"));
  }
}
```
<p><strong>Output:</strong></p>
```34
195
61
270
```

Title: Count the Bytes!

Body:
Java 7, <s>314</s> 313 bytes

int c(String u)throws Exception{String x="utf8",s=new java.util.Scanner(new java.net.URL(u).openStream(),x).useDelimiter("\\A").next();int j=s.indexOf("de>",s.indexOf('"'+u.split("/")[4]))+3;return s.substring(j,s.indexOf("<",j)-1).replace("&gt;",">").replace("&lt;","<").replace("&amp;","&").getBytes(x).length;}

Shamelessly stolen from @milk's C# answer and ported to Java 7.

NOTE: This assumes all code is in <code> blocks. Currently it won't work with just <pre> tags (but who uses those anyway?.. ;p).

Ungolfed & test cases:

class M{
  static int c(String u) throws Exception{
    String x = "utf8",
           s = new java.util.Scanner(new java.net.URL(u).openStream(), x).useDelimiter("\\A").next();
    int j = s.indexOf("de>", s.indexOf('"'+u.split("/")[4])) + 3;
    return s.substring(j, s.indexOf("<", j) - 1).replace("&gt;", ">").replace("&lt;", "<").replace("&amp;", "&")
        .getBytes(x).length;
  }

  public static void main(String[] a) throws Exception{
    System.out.println(c("https://codegolf.stackexchange.com/a/91904/30525"));
    System.out.println(c("https://codegolf.stackexchange.com/a/91693/30525"));
    System.out.println(c("https://codegolf.stackexchange.com/a/80691/30525"));
    System.out.println(c("https://codegolf.stackexchange.com/a/91995/58106"));
  }
}

Output:

34
195
61
270


问:
Golf all the 16 logic gates with 2 inputs and 1 output!
For example, the gate A and B is a logic gate with 2 inputs and 1 output.

There are exactly 16 of them, because:

each logic gate takes two inputs, which can be truthy or falsey, giving us 4 possible inputs

of the 4 possible inputs, each can have an output of truthy and falsey

therefore, there are 2^4 possible logic gates, which is 16.

Your task is to write 16 programs/functions which implement all of them separately.

Your functions/programs must be independent.

They are valid as long as they output truthy/falsey values, meaning that you can implement A or B in Python as lambda a,b:a+b, even if 2 is produced for A=True and B=True.

Score is total bytes used for each function/program.

List of logic gates

0,0,0,0 (false)

0,0,0,1 (and)

0,0,1,0 (A and not B)

0,0,1,1 (A)

0,1,0,0 (not A and B)

0,1,0,1 (B)

0,1,1,0 (xor)

0,1,1,1 (or)

1,0,0,0 (nor)

1,0,0,1 (xnor)

1,0,1,0 (not B)

1,0,1,1 (B implies A)

1,1,0,0 (not A)

1,1,0,1 (A implies B)

1,1,1,0 (nand)

1,1,1,1 (true)

Where the first number is the output for A=false, B=false,
the second number is the output for A=false, B=true,
the third number is the output for A=true, B=false,
the fourth number is the output for A=true, B=true.

Leaderboard

var QUESTION_ID=82938,OVERRIDE_USER=48934;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+(?:\.\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

```

答:
Logicode, 282 bytes

All logic gates in order:

```<code>out 0
circ g(a,b)->a&b
circ g(a,b)->a&(!b)
circ g(a)->a
circ g(a,b)->(!a)&b
circ g(a,b)->b
circ g(a,b)->(!(a&b))&(a|b)
circ g(a,b)->a|b
circ g(a,b)->!(a|b)
circ g(a,b)->!((!(a&b))&(a|b))
circ g(a,b)->!b
circ g(a,b)->(!a)|b
circ g(a)->!a
circ g(a,b)->a|(!b)
circ g(a,b)->!(a,b)
out 1
</code>```

Logicode is basically a code version of Logisim.

Check the Github repo (in the link) for more information.

Body:
Logicode, 282 bytes

All logic gates in order:

out 0
circ g(a,b)->a&b
circ g(a,b)->a&(!b)
circ g(a)->a
circ g(a,b)->(!a)&b
circ g(a,b)->b
circ g(a,b)->(!(a&b))&(a|b)
circ g(a,b)->a|b
circ g(a,b)->!(a|b)
circ g(a,b)->!((!(a&b))&(a|b))
circ g(a,b)->!b
circ g(a,b)->(!a)|b
circ g(a)->!a
circ g(a,b)->a|(!b)
circ g(a,b)->!(a,b)
out 1

Logicode is basically a code version of Logisim.

Check the Github repo (in the link) for more information.