问:
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>```

答:
BlackMarket, Java

Not much to say about this one, seeing as these transactions will be... off the charts, you might say.

```<code>import java.util.List;
import com.ppcg.stockexchange.*;

public class BlackMarket extends Player {
    private boolean approvedBySEC = false;
    private int ammoLeft = 30;
    public String taxView = "We want higher tax rates";
    public String excuse = "I never saw that in my life";

    public void secretValue(int drugType, int warrantForMyArrest) {
        super.secretValue(drugType, warrantForMyArrest);
        if (warrantForMyArrest != 0 || drugType == 420) {
            ammoLeft += 10;
        }
    }

    public Offer acceptOffer(List<Offer> offers) {
        for (Offer offer : offers) {
            if (this.approvedBySEC || offer.getPayment() < 9)
                return offer;
        }
        return null;
    }

    public Offer makeOffer(List<Stock> currentStock) {
        return new Offer(new Stock(0,1),420);
    }
}
</code>```

Title: Stock Exchange KoTH

Body:
BlackMarket, Java

Not much to say about this one, seeing as these transactions will be... off the charts, you might say.

import java.util.List;
import com.ppcg.stockexchange.*;

public class BlackMarket extends Player {
    private boolean approvedBySEC = false;
    private int ammoLeft = 30;
    public String taxView = "We want higher tax rates";
    public String excuse = "I never saw that in my life";

    public void secretValue(int drugType, int warrantForMyArrest) {
        super.secretValue(drugType, warrantForMyArrest);
        if (warrantForMyArrest != 0 || drugType == 420) {
            ammoLeft += 10;
        }
    }

    public Offer acceptOffer(List<Offer> offers) {
        for (Offer offer : offers) {
            if (this.approvedBySEC || offer.getPayment() < 9)
                return offer;
        }
        return null;
    }

    public Offer makeOffer(List<Stock> currentStock) {
        return new Offer(new Stock(0,1),420);
    }
}


问:
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!

答:
Python 3.5, <s>180</s> <s>157</s> <s>152</s> <s>147</s> 141 bytes

-6 due to Sherlock9

```<code>r=[[]]
for x in range(int(input())):
 r=len(r[-1])<len(r[0])and r or[*zip(*r[::-1]),[]];r[-1]+=[chr(x%26+65)]
print(*map(''.join,r),sep='\n')
</code>```

-5 due to Kap.

```<code>R=range
def g(n):
 r=[[]]
 for x in R(n):
  if len(r[-1])==len(r[0]):r=[*zip(*r[::-1]),[]]
  r[-1]+=[chr(x%26+65)]
 print(*map(''.join,r),sep='\n')
</code>```

Revised Solution, python 3.x:

```<code>R=range
def g(n):
 r=[[]]
 for x in R(n):
  if len(r[-1])==len(r[0]):r=list(zip(*r[::-1]))+[[]]
  r[-1]+=[chr(x%26+65)]
 print(*map(''.join,r),sep='\n')
</code>```

Previous Solution:

```<code>R=range
def g(n):
 r=[]
 for x,f in zip(R(n),(j<1for i in R(n)for j in R(i//2+1))):
  if f:r=list(zip(*r[::-1]))+[[]]
  r[-1].append(chr(x%26+65))
 print(*map(''.join,r),sep='\n')
</code>```

Explanation

r is a list of lists that holds the spiral.  The basic idea is that new letters are added to the bottom row of the spiral (r[-1].append(chr(x%26+65))).  When the bottom row is filled up, the spiral is rotated 90 clockwise and a new empty row is added to the bottom (r = list(zip(*r[::-1]))+[[]]).

The trick is to figure out when to rotate the spiral.  In the first solution, the generator (j<1for i in R(n)for j in R(i//2+1)) produces a sequence of True/False values that tell when to rotate the spiral.  In the revised solution, I changed the way r is initialized.  Now when the length of the bottom row equals the length of the top row, the spiral needs to be rotated.

ContentLicense: CC BY-SA 3.0

Title: Roll the Alphabet into a Spiral

Body:
Python 3.5, <s>180</s> <s>157</s> <s>152</s> <s>147</s> 141 bytes

-6 due to Sherlock9

r=[[]]
for x in range(int(input())):
 r=len(r[-1])<len(r[0])and r or[*zip(*r[::-1]),[]];r[-1]+=[chr(x%26+65)]
print(*map(''.join,r),sep='\n')

-5 due to Kap.

R=range
def g(n):
 r=[[]]
 for x in R(n):
  if len(r[-1])==len(r[0]):r=[*zip(*r[::-1]),[]]
  r[-1]+=[chr(x%26+65)]
 print(*map(''.join,r),sep='\n')

Revised Solution, python 3.x:

R=range
def g(n):
 r=[[]]
 for x in R(n):
  if len(r[-1])==len(r[0]):r=list(zip(*r[::-1]))+[[]]
  r[-1]+=[chr(x%26+65)]
 print(*map(''.join,r),sep='\n')

Previous Solution:

R=range
def g(n):
 r=[]
 for x,f in zip(R(n),(j<1for i in R(n)for j in R(i//2+1))):
  if f:r=list(zip(*r[::-1]))+[[]]
  r[-1].append(chr(x%26+65))
 print(*map(''.join,r),sep='\n')

Explanation

r is a list of lists that holds the spiral.  The basic idea is that new letters are added to the bottom row of the spiral (r[-1].append(chr(x%26+65))).  When the bottom row is filled up, the spiral is rotated 90 clockwise and a new empty row is added to the bottom (r = list(zip(*r[::-1]))+[[]]).

The trick is to figure out when to rotate the spiral.  In the first solution, the generator (j<1for i in R(n)for j in R(i//2+1)) produces a sequence of True/False values that tell when to rotate the spiral.  In the revised solution, I changed the way r is initialized.  Now when the length of the bottom row equals the length of the top row, the spiral needs to be rotated.


问:
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.

答:
Ruby 45 + 1 = 46 bytes

+1 byte for -p flag

```<code>a=$_.scan(e=/[aeiou]/).shuffle
gsub(e){a.pop}
</code>```

Title: Sheffle tho vawols ureund!

Body:
Ruby 45 + 1 = 46 bytes

+1 byte for -p flag

a=$_.scan(e=/[aeiou]/).shuffle
gsub(e){a.pop}


问:
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

```

答:
Nim, 16 bytes

```<code>while on:discard
</code>```

on is an alias for true. Nim disallows expressions that aren't explicitly discarded, so we just discard nothing.

Body:
Nim, 16 bytes

while on:discard

on is an alias for true. Nim disallows expressions that aren't explicitly discarded, so we just discard nothing.


问:
The Final Number

Challenge

Write a program that takes an array of 4 integers (which represents a sequence of numbers generated by a certain algorithm)  and returns the next integer that would follow.

We will only be using simple addition, subtraction, multiplication and division algorithms with a constant (i.e non-variable) variation.

For division we will use the floor integer values: 133/4 = 33 and 33/4 = 8

You can assume that there will always be one single valid return value

Test cases

[14,24,34,44] should return 54 (addition Algorithm)

[105,45,-15,-75] should return -135 (subtraction algorithm)

[5,25,125,625] should return 3125 (multiplicative algorithm)

[256,64,16,4] should return 1 (division algorithm)

General rules

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

Standard loopholes are forbidden

答:
Pyth, 18 Bytes

```<code>?-+vzJEyQ/^E2J-yEJ
</code>```

Accepts input as a newline-separated list of values.

Try it online!

Explanation:

```<code>?                         If
 -                          the following are not equal:
  +vzJE                      the sum of first and third values (and call the third value J)
       yQ                    and the second value * 2;
                            (i.e. if it is not an additive or subtractive formula)
          ^E2             Then: square the fourth value
         /   J              and divide by the third
?                         Else:
               yE           double the fourth value
              -  J          and subtract the third
</code>```

Title: The Final Number

Body:
Pyth, 18 Bytes

?-+vzJEyQ/^E2J-yEJ

Accepts input as a newline-separated list of values.

Try it online!

Explanation:

?                         If
 -                          the following are not equal:
  +vzJE                      the sum of first and third values (and call the third value J)
       yQ                    and the second value * 2;
                            (i.e. if it is not an additive or subtractive formula)
          ^E2             Then: square the fourth value
         /   J              and divide by the third
?                         Else:
               yE           double the fourth value
              -  J          and subtract the third


问:
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!

答:
Perl, <s>62</s> <s>54</s> 50 bytes

```<code>$_="I xe tx "x$_;s/tx $/it./;s/x/++$.%4?hat:lov/ge
</code>```

(credit to @Ton Hospel)

Demo: http://ideone.com/zrM27p

Previous solutions:

```<code>$_="I xe that "x$_;s/x/$@++&1?lov:hat/ge;s/\w+.$/it./
</code>```

(credit to @Dada)

Run with perl -pE '$_="I xe that "x$_;s/x/$@++&1?lov:hat/ge;s/\w+.$/it./'

First solution (only this was mine)

```<code>for$x(1..<>){$_.=' I '.($x%2?hat:lov).'e that'}s/\w+$/it./;say
</code>```

In parts:

```<code>for $x (1..<>) {
   $_ .= ' I '.($x % 2 ? hat : lov).'e that'
}
s/\w+$/it./;
say
</code>```

Demo: http://ideone.com/mosnVz

Title: Hate/love conundrum

Body:
Perl, <s>62</s> <s>54</s> 50 bytes

$_="I xe tx "x$_;s/tx $/it./;s/x/++$.%4?hat:lov/ge

(credit to @Ton Hospel)

Demo: http://ideone.com/zrM27p

Previous solutions:

$_="I xe that "x$_;s/x/$@++&1?lov:hat/ge;s/\w+.$/it./

(credit to @Dada)

Run with perl -pE '$_="I xe that "x$_;s/x/$@++&1?lov:hat/ge;s/\w+.$/it./'

First solution (only this was mine)

for$x(1..<>){$_.=' I '.($x%2?hat:lov).'e that'}s/\w+$/it./;say

In parts:

for $x (1..<>) {
   $_ .= ' I '.($x % 2 ? hat : lov).'e that'
}
s/\w+$/it./;
say

Demo: http://ideone.com/mosnVz


问:
Prune connections
John is writing a program that finds the best route from A to B using public transport. For a given pair of origin and destination the program calculates a set of routes with departure time and arrival time, such as this:

```<code>10:12 11:45
10:15 11:50
10:22 12:05
10:25 12:00
</code>```

As you see, the output may include a few routes that are superfluous in the sense that there is another route that starts later and ends earlier. Such routes are certainly never wanted by the user since he cat get out later to arrive sooner.

Your task, if you choose to accept it, is to write a program that prunes a set of routes such that all superfluous rules are eliminated.

Input

The input is a list of newline separated pairs of whitespace separated departure and arrival time in military format (hh:mm). Such a pair is called a route.

You may assume that all times are in the same day and that the arrival time is always later than the departure time. You may also assume that the list is orderer by departure times.

Output

The output is the same list as the input without redundant routes. A redundant route is a route for which another route exists in the list that has a later departure and an earlier arrival time. There must exist an order to remove all redundant routes such that in each step you can show the route that makes the removed route redundant. You don't have to output that order.

Extra credit

Prove or disprove that for each list of input routes there exists exactly one set of output routes.

Restriction

Usual codegolf rules apply

Scoring

To score, apply the function that gives an upper bound to your solutions complexity with your solution's total number of characters. Normalize your bounding function such that a solution length of two character yields a score of two.

For example, if your solution has 24 characters and a complexity of O(2n), your score is 4194304. If your solution has 123 characters and a complexity of O(n2) your score is 7564. If your solution has 200 characters and a complexity of O(n*logn), your score is 734.

I use this scoring method in order to encourage people to implement efficient solutions.

答:
Python 82 • O(n) = 82

New to code golfing. Dunno if I am breaking any rules.

```<code>i=-1
while len(a)>-i:
 if a[i][6:]<a[i-1][6:]:a.pop(i-1)
 else:i-=1
print ''.join(a)
</code>```

The algorithm is to iterate from the back of the list, removing the previous line if it has a later arrival time or moving the pointer to the previous line otherwise.

Note: The definition of redundant routes given by the OP is taken to the word, so neither of the two routes which have the same arrival times but different departure times are removed.

Title: Prune connections

Body:
Python 82 • O(n) = 82

New to code golfing. Dunno if I am breaking any rules.

i=-1
while len(a)>-i:
 if a[i][6:]<a[i-1][6:]:a.pop(i-1)
 else:i-=1
print ''.join(a)

The algorithm is to iterate from the back of the list, removing the previous line if it has a later arrival time or moving the pointer to the previous line otherwise.

Note: The definition of redundant routes given by the OP is taken to the word, so neither of the two routes which have the same arrival times but different departure times are removed.


问:
End the tabs versus space war

End the tabs versus space war

So, there has been a great deal of debate of whether to use tabs or spaces to indent/format code. Can you help the university settle the dispute, by going to an incredibly <s>crazy</s> unique method of formatting.

Your job is to write a full program or function which expands all tabs into four spaces. And then replaces a run of n leading spaces with "/(n - two stars here)/". You will receive input over multiple lines in any reasonable format (single string array of strings for each new line. Columnar array etc.)

Sample input shamelessly stolen. Note that since tabs get automagically expanded to four spaces on SE I represent it as the "^" character, but you must handle tabs (codepoint 0x09) as well. All "^" characters represent a tabulation.

```<code>Calculate the value 256 and test if it's zero
If the interpreter errors on overflow this is where it'll happen
++++++++[>++++++++<-]>[<++++>-]
+<[>-<
    Not zero so multiply by 256 again to get 65536
    [>++++<-]>[<++++++++>-]<[>++++++++<-]
    +>[>
        # Print "32"
        ++++++++++[>+++++<-]>+.-.[-]<
    <[-]<->] <[>>
        # Print "16"
        +++++++[>+++++++<-]>.+++++.[-]<
<<-]] >[>
    # Print "8"
    ++++++++[>+++++++<-]>.[-]<
<-]<
# Print " bit cells\n"
+++++++++++[>+++>+++++++++>+++++++++>+<<<<-]>-.>-.+++++++.+++++++++++.<.
>>.++.+++++++..<-.>>-
Clean up used cells.
[[-]<]l
^this is preceded by a tab
^^two tabs
^^^three tabs etcetera!
</code>```

Sample output

```<code>Calculate the value 256 and test if it's zero
If the interpreter errors on overflow this is where it'll happen
++++++++[>++++++++<-]>[<++++>-]
+<[>-<
/**/Not zero so multiply by 256 again to get 65536
/**/[>++++<-]>[<++++++++>-]<[>++++++++<-]
/**/+>[>
/******/# Print "32"
/******/++++++++++[>+++++<-]>+.-.[-]<
/**/<[-]<->] <[>>
/******/# Print "16"
/******/+++++++[>+++++++<-]>.+++++.[-]<
<<-]] >[>
/**/# Print "8"
/**/++++++++[>+++++++<-]>.[-]<
<-]<
# Print " bit cells\n"
+++++++++++[>+++>+++++++++>+++++++++>+<<<<-]>-.>-.+++++++.+++++++++++.<.
>>.++.+++++++..<-.>>-
Clean up used cells.
[[-]<]l
/**/this is preceded by a tab
/******/two tabs
/**********/three tabs etcetera!
</code>```

Because the university needs space to download both Vim and Emacs, you are allowed very little storage for your code. Therefore this is code-golf and the shortest code wins. You may assume that input is well formed and lines with less than four spaces (after replacement of tabs) may result in undefined behavior.

Disclaimer

This "excellent" formatting strategy came courtesy of Geobits, and is reproduced with his permission. No programmers were harmed during the production of this challenge.

答:
Java  <s>210</s> 207 bytes

This is the reference solution which implements it naively.

```<code>void a(String[]a){for(String s:a){s=s.replaceAll("\t", "    ");String x,y="";int j,i=s.length()-(x=s.replaceAll("^\\s+", "")).length();if(i>3){y="/";for(j=0;j++<i-1;)y+="*";y+="/";}System.out.println(y+x);}}
</code>```

Title: End the tabs versus space war

Body:
Java  <s>210</s> 207 bytes

This is the reference solution which implements it naively.

void a(String[]a){for(String s:a){s=s.replaceAll("\t", "    ");String x,y="";int j,i=s.length()-(x=s.replaceAll("^\\s+", "")).length();if(i>3){y="/";for(j=0;j++<i-1;)y+="*";y+="/";}System.out.println(y+x);}}


答:
JavaScript ES6, 75 bytes

```<code>s=>s.replace(/\t/g,"    ").replace(/^ +/gm,k=>`/${"*".repeat(k.length-2)}/`)
</code>```

Replace \t with a literal tab in your code.

Title: End the tabs versus space war

Body:
End the tabs versus space war

So, there has been a great deal of debate of whether to use tabs or spaces to indent/format code. Can you help the university settle the dispute, by going to an incredibly <s>crazy</s> unique method of formatting.

Your job is to write a full program or function which expands all tabs into four spaces. And then replaces a run of n leading spaces with "/(n - two stars here)/". You will receive input over multiple lines in any reasonable format (single string array of strings for each new line. Columnar array etc.)

Sample input shamelessly stolen. Note that since tabs get automagically expanded to four spaces on SE I represent it as the "^" character, but you must handle tabs (codepoint 0x09) as well. All "^" characters represent a tabulation.

```<code>Calculate the value 256 and test if it's zero
If the interpreter errors on overflow this is where it'll happen
++++++++[>++++++++<-]>[<++++>-]
+<[>-<
    Not zero so multiply by 256 again to get 65536
    [>++++<-]>[<++++++++>-]<[>++++++++<-]
    +>[>
        # Print "32"
        ++++++++++[>+++++<-]>+.-.[-]<
    <[-]<->] <[>>
        # Print "16"
        +++++++[>+++++++<-]>.+++++.[-]<
<<-]] >[>
    # Print "8"
    ++++++++[>+++++++<-]>.[-]<
<-]<
# Print " bit cells\n"
+++++++++++[>+++>+++++++++>+++++++++>+<<<<-]>-.>-.+++++++.+++++++++++.<.
>>.++.+++++++..<-.>>-
Clean up used cells.
[[-]<]l
^this is preceded by a tab
^^two tabs
^^^three tabs etcetera!
</code>```

Sample output

```<code>Calculate the value 256 and test if it's zero
If the interpreter errors on overflow this is where it'll happen
++++++++[>++++++++<-]>[<++++>-]
+<[>-<
/**/Not zero so multiply by 256 again to get 65536
/**/[>++++<-]>[<++++++++>-]<[>++++++++<-]
/**/+>[>
/******/# Print "32"
/******/++++++++++[>+++++<-]>+.-.[-]<
/**/<[-]<->] <[>>
/******/# Print "16"
/******/+++++++[>+++++++<-]>.+++++.[-]<
<<-]] >[>
/**/# Print "8"
/**/++++++++[>+++++++<-]>.[-]<
<-]<
# Print " bit cells\n"
+++++++++++[>+++>+++++++++>+++++++++>+<<<<-]>-.>-.+++++++.+++++++++++.<.
>>.++.+++++++..<-.>>-
Clean up used cells.
[[-]<]l
/**/this is preceded by a tab
/******/two tabs
/**********/three tabs etcetera!
</code>```

Because the university needs space to download both Vim and Emacs, you are allowed very little storage for your code. Therefore this is code-golf and the shortest code wins. You may assume that input is well formed and lines with less than four spaces (after replacement of tabs) may result in undefined behavior.

Disclaimer

This "excellent" formatting strategy came courtesy of Geobits, and is reproduced with his permission. No programmers were harmed during the production of this challenge.

Body:
JavaScript ES6, 75 bytes

s=>s.replace(/\t/g,"    ").replace(/^ +/gm,k=>`/${"*".repeat(k.length-2)}/`)

Replace \t with a literal tab in your code.


答:
Vim, <s>37, 34, 33,</s> 32 bytes

```<code>:%s/\t/    /g|%norm ^hr/hv0r*r/
</code>```

Try it online!

Note that this requires a trailing carriage return (enter) in vim, although not in the online interpreter.

This uses the V interpreter because it's backwards compatible. A very straightforward solution.

Here's a gif that lets you see the solution happen in real time. This uses a slightly older version, and I added some extra keystrokes to make it run slower so you can see what happens:

And here is the explanation of how it works:

```<code>:%s/\t/    /g           "Replace every tab with 4 spaces
|                       "AND
%norm                   "On every line:
      ^                 "  Move to the first non-whitespace char
       h                "  Move one character to the left. If there is none, the command will end here.
         r/             "  Replace it with a slash
           h            "  Move to the left
            v0          "  Visually select everything until the first column
              r*        "  Replace this selection with asterisks
                r/      "  Replace the first character with a slash
</code>```

Title: End the tabs versus space war

Body:
Vim, <s>37, 34, 33,</s> 32 bytes

:%s/\t/    /g|%norm ^hr/hv0r*r/

<a href="http://v.tryitonline.net/#code=OiVzL1x0LyAgICAvZ3wlbm9ybSBeaHIvaHYwcipyLwo&input=U2FtcGxlIGlucHV0IHNoYW1lbGVzc2x5IHN0b2xlbi4gTm90ZSB0aGF0IHRhYnMgZ2V0IGF1dG9tYWdpY2FsbHkgZXhwYW5kZWQgdG8gZm91ciBzcGFjZXMgb24gU0UsIGJ1dCB5b3UgbXVzdCBoYW5kbGUgdGFicyBhcyB3ZWxsLgpDYWxjdWxhdGUgdGhlIHZhbHVlIDI1NiBhbmQgdGVzdCBpZiBpdCdzIHplcm8KSWYgdGhlIGludGVycHJldGVyIGVycm9ycyBvbiBvdmVyZmxvdyB0aGlzIGlzIHdoZXJlIGl0J2xsIGhhcHBlbgorKysrKysrK1s-KysrKysrKys8LV0-WzwrKysrPi1dCis8Wz4tPAoJTm90IHplcm8gc28gbXVsdGlwbHkgYnkgMjU2IGFnYWluIHRvIGdldCA2NTUzNgoJWz4rKysrPC1dPls8KysrKysrKys-LV08Wz4rKysrKysrKzwtXQoJKz5bPgoJCSMgUHJpbnQgIjMyIgoJCSsrKysrKysrKytbPisrKysrPC1dPisuLS5bLV08Cgk8Wy1dPC0-XSA8Wz4-CgkJIyBQcmludCAiMTYiCgkJKysrKysrK1s-KysrKysrKzwtXT4uKysrKysuWy1dPAo8PC1dXSA-Wz4KCSMgUHJpbnQgIjgiCgkrKysrKysrK1s-KysrKysrKzwtXT4uWy1dPAo8LV08CiMgUHJpbnQgIiBiaXQgY2VsbHNcbiIKKysrKysrKysrKytbPisrKz4rKysrKysrKys-KysrKysrKysrPis8PDw8LV0-LS4-LS4rKysrKysrLisrKysrKysrKysrLjwuCj4-LisrLisrKysrKysuLjwtLj4-LQpDbGVhbiB1cCB1c2VkIGNlbGxzLgpbWy1dPF1sCgl0aGlzIGlzIHByZWNlZGVkIGJ5IGEgdGFiCgkJdHdvIHRhYnMKCQkJdGhyZWUgdGFicyBldGNldGVyYSE" rel="nofollow noreferrer">Try it online!

Note that this requires a trailing carriage return (enter) in vim, although not in the online interpreter.

This uses the V interpreter because it's backwards compatible. A very straightforward solution.

Here's a gif that lets you see the solution happen in real time. This uses a slightly older version, and I added some extra keystrokes to make it run slower so you can see what happens:

And here is the explanation of how it works:

:%s/\t/    /g           "Replace every tab with 4 spaces
|                       "AND
%norm                   "On every line:
      ^                 "  Move to the first non-whitespace char
       h                "  Move one character to the left. If there is none, the command will end here.
         r/             "  Replace it with a slash
           h            "  Move to the left
            v0          "  Visually select everything until the first column
              r*        "  Replace this selection with asterisks
                r/      "  Replace the first character with a slash


问:
Fibonacci reversed!

Introduction

We all know and love our Fibonacci sequence and have seen a myriad of challenge on it here already. However, we're still lacking a very simple case which this answer is going to provide: Reversed fibonacci! So given F_n your job is to find n.

Specification

Input

Your input will be a non-negative integer, which is guaranteed to be part of the fibonacci sequence.

Output

The output must be a non-negative integer as well.

What to do?

The introduction already said: Given a fibonacci number, output its index. Fiboancci number hereby is defined as F(0)=0, F(1)=1, F(n)=F(n-1)+F(n-2) and you're given F(n) and must return n.

Potential Corner Cases

0 is a valid in- and output.

If given "1" as input you may either output "1" or "2", as you prefer.

You may always assume that your input actually is a fibonacci number.

You may assume that the input is representable as a 32-bit signed integer.

Who wins?

This is code-golf so the shortest answer in bytes wins!

Standard rules apply of course.

Test-cases

```<code>0 -> 0
2 -> 3
3 -> 4
5 -> 5
8 -> 6
13 -> 7
1836311903 -> 46
</code>```

答:
Mathematica, 30 bytes

```<code>Round@Log[5^.5/2+.5,.8+5^.5#]&
</code>```

Pure function; returns 2 if the input is 1.

Doesn't beat the other Mathematica entry, but showcases an unusual method: It's a (very cool) fact that the Nth Fibonacci number is the closest integer to [1/sqrt(5) times the Nth power of the golden ratio] ("Binet's formula").

Therefore the inverse function will be the base-[golden ratio] logarithm of [sqrt(5) times the Fibonacci number in question]. The .8+ is a hack to make sure we don't take the logarithm of 0, without screwing up the other values.

Title: Fibonacci reversed!

Body:
Mathematica, 30 bytes

Round@Log[5^.5/2+.5,.8+5^.5#]&

Pure function; returns 2 if the input is 1.

Doesn't beat the other Mathematica entry, but showcases an unusual method: It's a (very cool) fact that the Nth Fibonacci number is the closest integer to [1/sqrt(5) times the Nth power of the golden ratio] ("Binet's formula").

Therefore the inverse function will be the base-[golden ratio] logarithm of [sqrt(5) times the Fibonacci number in question]. The .8+ is a hack to make sure we don't take the logarithm of 0, without screwing up the other values.


答:
Cheddar, <s>60</s> <s>57</s> 56 bytes

Saved 3 bytes thanks to @Conor O'Brien

```<code>@.sub(/\t/g," "*4).sub(/^ +/gm,i->"/"+"*"*(i.len-2)+"/")
</code>```

I wish Cheddar had better string formatting.

Try it online!

Explanation

This is a function. @ is a represents functionized property (e.g. ruby's &:) letting you do things like: `ar.map(@.head(-1))

```<code>@                      // Input
 .sub( /\t/g, " "*4)   // Replace tabs with four spaces
 .sub(
   /^ +/gm,            // Regex matches leading spaces
   i ->                // i is the matched leading spaces
     "/"+              // The / at the beginning
     "*"*(i.len-2)+    // Repeat *s i-2 times
     "/"                // The / at the end
 )
</code>```

If you aren't familiar with regex the:

```<code>/^ +/gm
</code>```

this basically matched one or more (+) spaces () at the beginning (^) of every (g) line (m).

Title: End the tabs versus space war

Body:
Cheddar, <s>60</s> <s>57</s> 56 bytes

Saved 3 bytes thanks to @Conor O'Brien

@.sub(/\t/g," "*4).sub(/^ +/gm,i->"/"+"*"*(i.len-2)+"/")

I wish Cheddar had better string formatting.

Try it online!

Explanation

This is a function. @ is a represents functionized property (e.g. ruby's &:) letting you do things like: `ar.map(@.head(-1))

@                      // Input
 .sub( /\t/g, " "*4)   // Replace tabs with four spaces
 .sub(
   /^ +/gm,            // Regex matches leading spaces
   i ->                // i is the matched leading spaces
     "/"+              // The / at the beginning
     "*"*(i.len-2)+    // Repeat *s i-2 times
     "/"                // The / at the end
 )

If you aren't familiar with regex the:

/^ +/gm

this basically matched one or more (+) spaces () at the beginning (^) of every (g) line (m).


答:
Pyth, 26 bytes

```<code>J"[aeiou]"s.i:QJ3.Sf}TPtJQ
</code>```

A program that takes input of a quoted string and prints the shuffled string.

Try it online

How it works

```<code>J"[aeiou]"s.i:QJ3.Sf}TPtJQ  Program. Input: Q
J"[aeiou]"                  J="[aeiou]"
             :QJ3           Split Q on matches of regex J, removing vowels
                      PtJ   J[1:-1], yielding "aeiou"
                   f}T   Q  Filter Q on presence in above, yielding vowels
                 .S         Randomly shuffle vowels
           .i               Interleave non-vowel and vowel parts
          s                 Concatenate and implicitly print
</code>```

Title: Sheffle tho vawols ureund!

Body:
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.

Body:
Pyth, 26 bytes

J"[aeiou]"s.i:QJ3.Sf}TPtJQ

A program that takes input of a quoted string and prints the shuffled string.

Try it online

How it works

J"[aeiou]"s.i:QJ3.Sf}TPtJQ  Program. Input: Q
J"[aeiou]"                  J="[aeiou]"
             :QJ3           Split Q on matches of regex J, removing vowels
                      PtJ   J[1:-1], yielding "aeiou"
                   f}T   Q  Filter Q on presence in above, yielding vowels
                 .S         Randomly shuffle vowels
           .i               Interleave non-vowel and vowel parts
          s                 Concatenate and implicitly print


问:
Look-and-say sequence: roman numerals edition

Challenge description

We've had a few challenges involving the Look-and-say sequence. Quick reminder:

The sequence starts with 1,

Subsequent terms of this sequence are generated by enumerating each group of repeating digits in the previous term,

So the first few terms are:

```<code>1        "one"
11       "one one" (we look at the previous term)
21       "two ones"
1211     "one two, one one"
111221   "one one, one two, two ones"
312211   "three ones, two twos, one one"
</code>```

Now let's do the same thing, but use Roman Numerals instead. We start with I and follow the same rules (we apply the digit-counting rule to characters instead, so we read IVX as one one, one five, one ten instead of one four, one ten or some other way):

```<code>I           "one"
II          "one one"
III         "two ones" = "II" + "I"
IIII        "three ones" = "III" + "I"
IVI         "four ones" = "IV" + "I"
IIIVII      "one one, one five, one one"
IIIIIVIII   "three ones, one five, two ones" = ("III" + "I") + ("I" + "V") + ("II" + "I")
</code>```

Given a positive integer N, either:

Output first N numerals of this sequence (any reasonable separator is fine, as well as ["I", "II", "III", ...]

Output Nth term of this sequence (it may be 0-indexed).

Remember to make your code as short as possible, since this is a code-golf challenge!

EDIT: I believe that there is always one standard/preferred way of expressing integers as roman numerals, (like 95 -> XCV instead of VC). Couple of Roman numeral converters I found online corroborate my opinion. If in doubt, use an online converter, as listing all the possible edge-cases and specific rules of writing Roman numerals is not the point of this challenge.

EDIT2: @PeterTaylor and @GregMartin pointed out that only numbers less or equal to 5 appear in the sequence, so you don't have to worry about the ambiguity of Roman numerals (numbers 1 - 8 are I, II, III, IV, V, VI, VII, and VIII)

答:
Perl, 49 bytes

Includes +1 for -p

Run with the 0-based index on STDIN, e.g.

```<code>ecce.pl <<< 14
</code>```

ecce.pl:

```<code>#!/usr/bin/perl -p
s,(.)\1*,$&/$1%182 .$1,eg for($_=/$/)x$`;y;19;IV
</code>```

Magic formulas are so magic.

Normally I would use ($_=//)x$' to make the loop control one byte shorter, but scoring on this site gives that a handicap of 2 so it ends up 1 byte longer. On older perls you can drop the space before for. Some versions of perl force you to add a final ; to close the transliteration. But what is given above is the code that works on my system.

Explanation

Working backwards from solution to code:

The string transformations we need:

```<code>I     -> II
II    -> III
III   -> IIII
IIII  -> IVI
IIIII -> VI

V     -> IV
VV    -> IIV
</code>```

Each replacement ends with the repeated character. I will get a sequence of the same characters using regex /(.)\1*/, so this can be done by appending $1. The part before the -> is in $&. With that I still need:

```<code>I     -> I
II    -> II
III   -> III
IIII  -> IV
IIIII -> V

V     -> I
VV    -> II
</code>```

Write I as 1 and V as 9:

```<code>1     -> 1
11    -> 11
111   -> 111
1111  -> 19
11111 -> 9

9     -> 1
99    -> 11
</code>```

By dividing the part before -> by the repeated digit this becomes:

```<code>1     -> 1
11    -> 11
111   -> 111
1111  -> 19
11111 -> 9

1     -> 1
11    -> 11
</code>```

So now the original repeated V is not an exception anymore. So I want an expression that makes this happen:

```<code>1     -> 1
11    -> 11
111   -> 111
1111  -> 19
11111 -> 9
</code>```

And this can be done by a simple modulo 182:

```<code>1     % 182 = 1
11    % 182 = 11
111   % 182 = 111
1111  % 182 = 19
11111 % 182 = 9
</code>```

(this even gets IIIIII to VI right though it isn't needed here)

All that is left is initializing the working variable to 1 for index 0, repeat this transformation in a loop and at the end replace 1 by I and 9 by V

1, 9 and 182 is the only parameter combination for which this simple formula works.

Body:
Perl, 49 bytes

Includes +1 for -p

Run with the 0-based index on STDIN, e.g.

ecce.pl <<< 14

ecce.pl:

#!/usr/bin/perl -p
s,(.)\1*,$&/$1%182 .$1,eg for($_=/$/)x$`;y;19;IV

Magic formulas are so magic.

Normally I would use ($_=//)x$' to make the loop control one byte shorter, but scoring on this site gives that a handicap of 2 so it ends up 1 byte longer. On older perls you can drop the space before for. Some versions of perl force you to add a final ; to close the transliteration. But what is given above is the code that works on my system.

Explanation

Working backwards from solution to code:

The string transformations we need:

I     -> II
II    -> III
III   -> IIII
IIII  -> IVI
IIIII -> VI

V     -> IV
VV    -> IIV

Each replacement ends with the repeated character. I will get a sequence of the same characters using regex /(.)\1*/, so this can be done by appending $1. The part before the -> is in $&. With that I still need:

I     -> I
II    -> II
III   -> III
IIII  -> IV
IIIII -> V

V     -> I
VV    -> II

Write I as 1 and V as 9:

1     -> 1
11    -> 11
111   -> 111
1111  -> 19
11111 -> 9

9     -> 1
99    -> 11

By dividing the part before -> by the repeated digit this becomes:

1     -> 1
11    -> 11
111   -> 111
1111  -> 19
11111 -> 9

1     -> 1
11    -> 11

So now the original repeated V is not an exception anymore. So I want an expression that makes this happen:

1     -> 1
11    -> 11
111   -> 111
1111  -> 19
11111 -> 9

And this can be done by a simple modulo 182:

1     % 182 = 1
11    % 182 = 11
111   % 182 = 111
1111  % 182 = 19
11111 % 182 = 9

(this even gets IIIIII to VI right though it isn't needed here)

All that is left is initializing the working variable to 1 for index 0, repeat this transformation in a loop and at the end replace 1 by I and 9 by V

1, 9 and 182 is the only parameter combination for which this simple formula works.


答:
C#, <s>85</s> 83 bytes

```<code>string f(int n,int m=2)=>"I "+(1>m%2?"hat":"lov")+(m>n?"e it.":"e that "+f(n,m+1));
</code>```

Recursively constructs the string, using an optional parameter to keep track of which hate/love and how many to append.

-2 bytes from this tip for checking the evenness/oddness of a number.

No optional parameter solution, <s>87</s> <s>86</s> 84 bytes

```<code>string h(int n)=>"I "+(0<n?"hat":"lov")+(2>n&-2<n?"e it.":"e that "+h(0<n?~n+2:~n));
</code>```

This one does the same thing except determines which hate/love to append based on whether the parameter is positive or negative. Each iteration the parameter approaches zero, alternating sign.

Title: Hate/love conundrum

Body:
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!

Body:
C#, <s>85</s> 83 bytes

string f(int n,int m=2)=>"I "+(1>m%2?"hat":"lov")+(m>n?"e it.":"e that "+f(n,m+1));

Recursively constructs the string, using an optional parameter to keep track of which hate/love and how many to append.

-2 bytes from this tip for checking the evenness/oddness of a number.

No optional parameter solution, <s>87</s> <s>86</s> 84 bytes

string h(int n)=>"I "+(0<n?"hat":"lov")+(2>n&-2<n?"e it.":"e that "+h(0<n?~n+2:~n));

This one does the same thing except determines which hate/love to append based on whether the parameter is positive or negative. Each iteration the parameter approaches zero, alternating sign.


Title: End the tabs versus space war

Body:
Python, <s>125</s> 111 bytes

lambda s:'\n'.join(('/'+(len(L.replace('\t',' '*4))-len(L.strip())-2)*'*'+'/'+L.strip(),L)[L[0]>' ']for L in s)

https://repl.it/DGyh/2


问:
Calculate pi to 5 decimals
This comes from http://programmers.blogoverflow.com/2012/08/20-controversial-programming-opinions/

"Given that Pi can be estimated using the function 4 * (1 – 1/3 + 1/5 – 1/7 + …) with more terms giving greater accuracy, write a function that calculates Pi to an accuracy of 5 decimal places."

Note, the estimation must be done by calculating the sequence given above.

Title: Calculate pi to 5 decimals

Body:
Python (49)

print 4*sum((-1)**i/(2*i+1.)for i in range(9**6))

3.14159453527


问:
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
```

答:
PowerShell - 86

I imagine I could get this smaller, but I'll work on it later. This assumes that $d contains the string to explode.

```<code>$s="";$i=0;[Array]::Sort(($a=$d-split""));$a|%{$s+=$_;if($a[++$i]-cne$_){$s+="`n"}};$s
</code>```

Title: Exploded view of a string

Body:
PowerShell - 86

I imagine I could get this smaller, but I'll work on it later. This assumes that $d contains the string to explode.

$s="";$i=0;[Array]::Sort(($a=$d-split""));$a|%{$s+=$_;if($a[++$i]-cne$_){$s+="`n"}};$s


答:
Bash + coreutils, 106 bytes:

```<code>for i in `seq $1`;{ printf "I %s %s " `((i%2>0))&&echo hate||echo love` `((i==$1))&&echo it.||echo that`;}
</code>```

Simply creates a sequence starting at 1 up to and including the input integer using the seq built-in, and then iterates through it one by one, first outputting hate if the value of the iteration variable, i, is not divisible by 2 and love otherwise. In the same iteration, it then chooses to output that if i is not equal to the input value, and it. otherwise.

Try It Online! (Ideone)

Title: Hate/love conundrum

Body:
Bash + coreutils, 106 bytes:

for i in `seq $1`;{ printf "I %s %s " `((i%2>0))&&echo hate||echo love` `((i==$1))&&echo it.||echo that`;}

Simply creates a sequence starting at 1 up to and including the input integer using the seq built-in, and then iterates through it one by one, first outputting hate if the value of the iteration variable, i, is not divisible by 2 and love otherwise. In the same iteration, it then chooses to output that if i is not equal to the input value, and it. otherwise.

Try It Online! (Ideone)


答:
Python 3, 124 bytes

Uses good ol' regex.

import re
lambda I:re.sub('^\s*(?m)',lambda m:'/'+'*'*len(m.group()[:-2])+'/',re.sub('\t+',lambda g:' '*4*len(g.group()),I))
```

Ideone it!

Title: End the tabs versus space war

Body:
Python 3, 124 bytes

Uses good ol' regex.

import re
lambda I:re.sub('^\s*(?m)',lambda m:'/'+'*'*len(m.group()[:-2])+'/',re.sub('\t+',lambda g:' '*4*len(g.group()),I))

Ideone it!


问:
Print every printable ASCII character without using it
In a programming language of your choice, write 95 programs, each of which outputs a different one of the 95 printable ASCII characters without that character occurring anywhere in the program.

For example, if your language was Python, your program that outputs the character P might be

```<code>print(chr(80))
</code>```

because P has ASCII code 80. This program is valid because P never appears in the source code. However, for the program that outputs lowercase p, something like

```<code>print(chr(112))
</code>```

would be invalid because, while it does print p, p is present in the code. A valid program could be

```<code>exec(chr(112)+'rint(chr(112))')
</code>```

which prints p but does not contain p.

Your goal is to make each of your 95 programs as short as possible. Your score is the sum of the character lengths of all your programs.

If for any reason you are unable to write valid programs for some characters, you may mark those characters as "Did Not Program" or DNP, and omit programs for them entirely. This way syntactically strict languages will be able to compete.

The winning answer is the answer that has the lowest score of the set of answers that have the fewest DNP's.

Rules

The source code of all of your programs may only contain printable ASCII plus tabs and newlines, all of which are counted as one character. (Because in a different encoding it would be easy to omit characters that don't exist!)

Note: This rule seems necessary but there are many languages with different encodings and I'm sure it'd be cool to see the answers for them. Therefore you can break this rule, you can use whatever characters you want, but then your answer becomes non-competitive, it cannot win.

The programs must be actual, full programs, according to your language's standard conventions. Functions and REPL snippets are not allowed.

Each program's output should go to stdout or your language's accepted alternative.

Programs should not prompt for or require input. (If prompting for input is inherent to your language, that's ok.)

Programs should be deterministic, finite in run time, and independent. e.g. it shouldn't matter if one is run in a folder separate from the other programs.

A program's output should be the precise printable ASCII character it corresponds to, optionally followed by a single trailing newline, nothing more, nothing less.

Be sure to include information on all 95 (ideally) programs in your answer, as well as your score and any DNP's. You don't have to list all programs that follow a simple pattern like "print(chr(80)), print(chr(81)), print(chr(82))..." but make sure you're sure they all would work and that your score is added correctly.

For reference, here are the 95 printable ASCII your programs must output:

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

答:
Deadfish, 43 bytes, 85 DNP

```<code>o        #0
io       #1
iio      #2
iiio     #3
iiso     #4
iisio    #5
iisiio   #6
iiisddo  #7
iiisdo   #8
iiiso    #9
</code>```

Doesn't fit the definition of programming language, but this IS constant output...

Body:
Deadfish, 43 bytes, 85 DNP

o        #0
io       #1
iio      #2
iiio     #3
iiso     #4
iisio    #5
iisiio   #6
iiisddo  #7
iiisdo   #8
iiiso    #9

Doesn't fit the definition of programming language, but this IS constant output...


答:
Mathematica, 97 bytes

```<code>a=StringReplace;a[a[#,"\t"->"    "],StartOfLine~~b:" "..:>"/"<>Table["*",StringLength@b-2]<>"/"]&
</code>```

Anonymous function. Takes a string as input and returns a string as output.

Title: End the tabs versus space war

Body:
Mathematica, 97 bytes

a=StringReplace;a[a[#,"\t"->"    "],StartOfLine~~b:" "..:>"/"<>Table["*",StringLength@b-2]<>"/"]&

Anonymous function. Takes a string as input and returns a string as output.


答:
ARM Machine Code, 30 bytes

Hex Dump (little endian):

```<code>2000 f811 2b01 b14a 2a2a bf08 0040 d0f8 2a2e bf3a 3a2c 1a80 1040 e7f2 4770
</code>```

This is a function that takes in a string, and returns the accumulated result. In C, the function would be declared int sioc(int dummy, char* string) where the dummy argument is ignored. Tested on the Raspberry Pi 3. No libraries or system calls are used.

Ungolfed assembly:

```<code>.syntax unified
.text
.global sioc
.thumb_func
sioc:
    @Input: r0 - dummy argument
    @r1 - string of operations
    @Output: r0 - result of those operations
    movs r0,#0 @Initialize accumulator to 0
    loop:
        ldrb r2,[r1],#1 @r2=*r1++
        cbz r2,end @If (r2==0), goto end
    mul:
        cmp r2,#42
        it eq @if r2==42
        lsleq r0,r0,#1 @r0<<=1
        beq loop @continue
    addsub: @else
        cmp r2,#46
        itte lo @If r2<46, then r2 is either + or -
        sublo r2,r2,#44
        sublo r0,r0,r2 @Add 1 if r2 is +, subtract 1 if r0 is -
        asrhs r0,r0,#1 @else arithmatically shift right by 1
        b loop @while (true)
    end:
        bx lr
</code>```

Testing script (also assembly):

```<code>.syntax unified
.text
.global main
.thumb_func
main:
    ldr r1,[r1,#4] @r0=argv[1]
    bl sioc
    mov r1,r0
    adr r0,msg
    bl printf
    movs r7,#1
    swi #0
.balign 4
msg:
    .asciz "%d\n"
</code>```

Title: Simple integer operation calculator

Body:
Implement a simple integer operation scriptable calculator.

Concept

The accumulator starts at 0 and has operations performed on it. At the end of the program output the value of the accumulator.

Operations:

+ adds 1 to the accumulator

- subtracts 1 from the accumulator

* multiplies the accumulator by 2

/ divides the accumulator by 2

Sample script

The input ++**--/ should give the output 3.

Example implementation

```<code>def calc(s)
    i = 0
    s.chars.each do |o|
        case o
            when '+'
                i += 1
            when '-'
                i -= 1
            when '*'
                i *= 2
            when '/'
                i /= 2
        end
    end
    return i
end
</code>```

Rules

This is code-golf, so lowest answer in bytes wins, but is not selected.

Creative implementations are encouraged.

Standard loopholes are prohibited.

You get the program via stdin or arguments, and you can output the answer via return value or stdout.

Have fun.

Division truncates down because it is integer division.

The program -/ returns -1.

Test cases

```<code>*///*-*+-+
-1
/*+/*+++/*///*/+-+//*+-+-/----*-*-+++*+**+/*--///+*-/+//*//-+++--++/-**--/+--/*-/+*//*+-*-*/*+*+/+*-
-17
+++-+--/-*/---++/-+*-//+/++-*--+*+/*/*/++--++-+//++--*/***-*+++--+-*//-*/+*/+-*++**+--*/*//-*--**-/-*+**-/*-**/*+*-*/--+/+/+//-+*/---///+**////-*//+-+-/+--/**///*+//+++/+*++**++//**+**+-*/+/*/*++-/+**+--+*++++/-*-/*+--/++*/-++/-**++++/-/+/--*/-/+---**//*///-//*+-*----+//--/-/+*/-+++-+*-*+*+-/-//*-//+/*-+//+/+/*-/-/+//+**/-****/-**-//+/+-+/*-+*++*/-/++*/-//*--+*--/-+-+/+/**/-***+/-/++-++*+*-+*+*-+-//+/-++*+/*//*-+/+*/-+/-/*/-/-+*+**/*//*+/+---+*+++*+/+-**/-+-/+*---/-*+/-++*//*/-+-*+--**/-////*/--/*--//-**/*++*+/*+/-+/--**/*-+*+/+-*+*+--*///+-++/+//+*/-+/**--//*/+++/*+*////+-*-//--*+/*/-+**/*//+*+-//+--+*-+/-**-*/+//*+---*+//*/+**/*--/--+/*-*+*++--*+//+*+-++--+-*-*-+--**+/+*-/+*+-/---+-*+-+-/++/+*///*/*-+-*//-+-++/++/*/-++/**--+-////-//+/*//+**/*+-+/+/+///*+*///*-/+/*/-//-*-**//-/-+--+/-*--+-++**++//*--/*++--*-/-///-+/+//--+*//-**-/*-*/+*/-*-*//--++*//-*/++//+/-++-+-*/*-+++**-/-*++++**+-+++-+-***-+//+-/**-+/*+****-*+++*/-*-/***/-/*+/*****++*+/-/-**-+-*-*-++**/*+-/*-+*++-/+/-++*-/*-****-*
18773342
</code>```

Body:
ARM Machine Code, 30 bytes

Hex Dump (little endian):

2000 f811 2b01 b14a 2a2a bf08 0040 d0f8 2a2e bf3a 3a2c 1a80 1040 e7f2 4770

This is a function that takes in a string, and returns the accumulated result. In C, the function would be declared int sioc(int dummy, char* string) where the dummy argument is ignored. Tested on the Raspberry Pi 3. No libraries or system calls are used.

Ungolfed assembly:

.syntax unified
.text
.global sioc
.thumb_func
sioc:
    @Input: r0 - dummy argument
    @r1 - string of operations
    @Output: r0 - result of those operations
    movs r0,#0 @Initialize accumulator to 0
    loop:
        ldrb r2,[r1],#1 @r2=*r1++
        cbz r2,end @If (r2==0), goto end
    mul:
        cmp r2,#42
        it eq @if r2==42
        lsleq r0,r0,#1 @r0<<=1
        beq loop @continue
    addsub: @else
        cmp r2,#46
        itte lo @If r2<46, then r2 is either + or -
        sublo r2,r2,#44
        sublo r0,r0,r2 @Add 1 if r2 is +, subtract 1 if r0 is -
        asrhs r0,r0,#1 @else arithmatically shift right by 1
        b loop @while (true)
    end:
        bx lr

Testing script (also assembly):

.syntax unified
.text
.global main
.thumb_func
main:
    ldr r1,[r1,#4] @r0=argv[1]
    bl sioc
    mov r1,r0
    adr r0,msg
    bl printf
    movs r7,#1
    swi #0
.balign 4
msg:
    .asciz "%d\n"


答:
Perl, 41 bytes

```<code>s,␉,    ,g;s,^  ( +),/@{[$1=~y| |*|r]}/,
</code>```

Run with the -p flag, like so:

```<code>perl -pe 's,␉,    ,g;s,^  ( +),/@{[$1=~y| |*|r]}/,'
#     ↑   └───────────────────┬───────────────────┘
#     1 byte               40 bytes
</code>```

Replace ␉ by a tab (in Bash, try typing Control-V Tab.)

Title: End the tabs versus space war

Body:
End the tabs versus space war

So, there has been a great deal of debate of whether to use tabs or spaces to indent/format code. Can you help the university settle the dispute, by going to an incredibly <s>crazy</s> unique method of formatting.

Your job is to write a full program or function which expands all tabs into four spaces. And then replaces a run of n leading spaces with "/(n - two stars here)/". You will receive input over multiple lines in any reasonable format (single string array of strings for each new line. Columnar array etc.)

Sample input shamelessly stolen. Note that since tabs get automagically expanded to four spaces on SE I represent it as the "^" character, but you must handle tabs (codepoint 0x09) as well. All "^" characters represent a tabulation.

```<code>Calculate the value 256 and test if it's zero
If the interpreter errors on overflow this is where it'll happen
++++++++[>++++++++<-]>[<++++>-]
+<[>-<
    Not zero so multiply by 256 again to get 65536
    [>++++<-]>[<++++++++>-]<[>++++++++<-]
    +>[>
        # Print "32"
        ++++++++++[>+++++<-]>+.-.[-]<
    <[-]<->] <[>>
        # Print "16"
        +++++++[>+++++++<-]>.+++++.[-]<
<<-]] >[>
    # Print "8"
    ++++++++[>+++++++<-]>.[-]<
<-]<
# Print " bit cells\n"
+++++++++++[>+++>+++++++++>+++++++++>+<<<<-]>-.>-.+++++++.+++++++++++.<.
>>.++.+++++++..<-.>>-
Clean up used cells.
[[-]<]l
^this is preceded by a tab
^^two tabs
^^^three tabs etcetera!
</code>```

Sample output

```<code>Calculate the value 256 and test if it's zero
If the interpreter errors on overflow this is where it'll happen
++++++++[>++++++++<-]>[<++++>-]
+<[>-<
/**/Not zero so multiply by 256 again to get 65536
/**/[>++++<-]>[<++++++++>-]<[>++++++++<-]
/**/+>[>
/******/# Print "32"
/******/++++++++++[>+++++<-]>+.-.[-]<
/**/<[-]<->] <[>>
/******/# Print "16"
/******/+++++++[>+++++++<-]>.+++++.[-]<
<<-]] >[>
/**/# Print "8"
/**/++++++++[>+++++++<-]>.[-]<
<-]<
# Print " bit cells\n"
+++++++++++[>+++>+++++++++>+++++++++>+<<<<-]>-.>-.+++++++.+++++++++++.<.
>>.++.+++++++..<-.>>-
Clean up used cells.
[[-]<]l
/**/this is preceded by a tab
/******/two tabs
/**********/three tabs etcetera!
</code>```

Because the university needs space to download both Vim and Emacs, you are allowed very little storage for your code. Therefore this is code-golf and the shortest code wins. You may assume that input is well formed and lines with less than four spaces (after replacement of tabs) may result in undefined behavior.

Disclaimer

This "excellent" formatting strategy came courtesy of Geobits, and is reproduced with his permission. No programmers were harmed during the production of this challenge.

Body:
Perl, 41 bytes

s,␉,    ,g;s,^  ( +),/@{[$1=~y| |*|r]}/,

Run with the -p flag, like so:

perl -pe 's,␉,    ,g;s,^  ( +),/@{[$1=~y| |*|r]}/,'
#     ↑   └───────────────────┬───────────────────┘
#     1 byte               40 bytes

Replace ␉ by a tab (in Bash, try typing Control-V Tab.)


问:
As Easy as One-Two-Three
Write a program or function that takes in a positive integer. You can assume the input is valid and may take it as a string. If the number is any of

```<code>123
234
345
456
567
678
789
</code>```

then output a truthy value. Otherwise, output a falsy value. For example, the inputs

```<code>1
2
3
12
122
124
132
321
457
777
890
900
1011
1230
1234
</code>```

must all result in falsy output. (The input will not have leading zeroes so you needn't worry about things like 012.)

The shortest code in bytes wins.

答:
ARM Machine Code, 18 bytes

Hex dump (little endian):

```<code>3803 d105 6808 ebc0 2010 b280 f2a0 1001 4770
</code>```

This is a function that takes in a length, pointer pair for the string. The output is bash-style, it outputs 0 for true and a non-zero value for false. In C the function would be declared int oneTwoThree(size_t length, char* string). The instruction encoding is thumb-2, which has 2 and 4 byte instructions. Tested on a Raspberry Pi 3.

Ungolfed assembly:

```<code>.syntax unified
.text
.global oneTwoThree
.thumb_func
oneTwoThree:
    @Input: r0 - the number of characters in the string
    @r1 - A pointer to the (not necessarily NUL-terminated)
    @string representation of the number (char*)
    @Output: r1 - 0 if the number is in 123,234,...,789, else non-zero (bash-style)
    subs r0,r0,#3
    bne end @Return non-zero if r0!=3
    ldr r0,[r1] @Remember that this is little endian
    @So the first digit is the most siginificant byte
    @I.e. if the input was 123 then r0 contains 0xXY010203 where XY is garbage

    rsb r0,r0,r0,lsr #8 @r0=(r0>>8)-r0 (rsb is reverse subtract)
    uxth r0,r0 @r0&=((1<<16)-1) (mask off top half)
    @Now r0 is 0x0101 iff we have a matching number
    sub r0,r0,#0x101
    @Now r0 is 0 iff the string fit the specification

    end:
    bx lr @return
</code>```

Testing script (also assembly):

```<code>.syntax unified
.text
.global main
.thumb_func
main:
    push {r4,lr}
    ldr r4,[r1,#4] @r0=argv[1]
    mov r0,r4
    bl strlen
    @Now r0 is the length of the string argv[1]
    mov r1,r4
    bl oneTwoThree @oneTwoThree(strlen(argv[1]),argv[1])
    cmp r0,#0
    it ne
    movne r0,#1 @Output through return code, 1 if false
    pop {r4,pc}
</code>```

Title: As Easy as One-Two-Three

Body:
ARM Machine Code, 18 bytes

Hex dump (little endian):

3803 d105 6808 ebc0 2010 b280 f2a0 1001 4770

This is a function that takes in a length, pointer pair for the string. The output is bash-style, it outputs 0 for true and a non-zero value for false. In C the function would be declared int oneTwoThree(size_t length, char* string). The instruction encoding is thumb-2, which has 2 and 4 byte instructions. Tested on a Raspberry Pi 3.

Ungolfed assembly:

.syntax unified
.text
.global oneTwoThree
.thumb_func
oneTwoThree:
    @Input: r0 - the number of characters in the string
    @r1 - A pointer to the (not necessarily NUL-terminated)
    @string representation of the number (char*)
    @Output: r1 - 0 if the number is in 123,234,...,789, else non-zero (bash-style)
    subs r0,r0,#3
    bne end @Return non-zero if r0!=3
    ldr r0,[r1] @Remember that this is little endian
    @So the first digit is the most siginificant byte
    @I.e. if the input was 123 then r0 contains 0xXY010203 where XY is garbage

    rsb r0,r0,r0,lsr #8 @r0=(r0>>8)-r0 (rsb is reverse subtract)
    uxth r0,r0 @r0&=((1<<16)-1) (mask off top half)
    @Now r0 is 0x0101 iff we have a matching number
    sub r0,r0,#0x101
    @Now r0 is 0 iff the string fit the specification

    end:
    bx lr @return

Testing script (also assembly):

.syntax unified
.text
.global main
.thumb_func
main:
    push {r4,lr}
    ldr r4,[r1,#4] @r0=argv[1]
    mov r0,r4
    bl strlen
    @Now r0 is the length of the string argv[1]
    mov r1,r4
    bl oneTwoThree @oneTwoThree(strlen(argv[1]),argv[1])
    cmp r0,#0
    it ne
    movne r0,#1 @Output through return code, 1 if false
    pop {r4,pc}


问:
Simulate any 1D cellular automaton

The Challenge

You are to write a complete program that takes seven numbers from STDIN, and prints the two dimensional history of the cellular automaton (CA) to STDOUT. This is code golf.

Input Formatting
The input will be seven integers/strings separated by commas. The first number is the number of the rule according to Wolfram code (the standard name for each rule). The second is the initial starting configuration. The third and fourth describe what pattern and how many times it should be appended to the left of the starting config. as padding. The fifth and sixth do the same for the right side. The last number is the number of generations to run the simulation.

So, an example of input is 90,11,0,4,0,4,5. This should tell your program that you are running rule 90. It should also tell the program that you want the initial configuration to be 11 with the string 0 appended 4 times to both ends, so the actual starting pattern is 0000110000. It also tells your program to run this simulation for 5 generations.

Output Your program should print the entire array of cells each generation (separated by newlines), so that the output is the space-time diagram of the CA. For each generation, the state of each cell is determined by its state and the states of the cells to the immediate left and right, in accordance to the rule provided as input. The simulation should wrap around the edges. The first thing printed should be the starting array as gen. 0.

The input 90,11,0,4,0,4,5 should result in the following output as exactly as possible.

```<code>0000110000
0001111000
0011001100
0111111110
1100000011
0110000110
</code>```

Notice that the starting state is not included in the five generations. Also notice that the simulation wraps around the edges.

More Examples

input:

```<code>184,1100,01,2,01,1,4
</code>```

output:

```<code>0101110001
1011101000
0111010100
0110101010
0101010101
</code>```

input:

```<code>0,1011,1,0,0,1,2
</code>```

output:

```<code>10110
00000
00000
</code>```

More information on how 1D CA's work and how they are numbered

答:
C (487 484 418 with spaces removed)

*Dropped 66 with help from JoeFish*

```<code>C,A,r,n,j;main(){char*s,*p,*t,a[9],b[9],c[9];
    scanf("%d,%[01],%[01],%d,%[01],%d,%d",&r,b,a,&A,c,&C,&n);
    s=malloc(strlen(a)*A+strlen(b)+strlen(c)*C+3);*s=0;
    strcat(s,"0");
    for(;A--;)strcat(s,a);
    strcat(s,b);
    for(;C--;)strcat(s,c);
    strcat(s,"0");
    p=malloc((C=strlen(s)-1)+2);
    for(;n--;){
    *s=s[C-1];
    s[C]=0;
    puts(s+1);
    s[C]=s[1];
    for(j=1;s[j+1];j++)
        p[j]=(1<<(s[j-1]-48)*4+(s[j]-48)*2+s[j+1]-48)&r?49:48;
    t=p;p=s;s=t;
    }
    s[C]=0;
    puts(s+1);
}
</code>```

typescript

```
josh@Z1 ~
$ !m
make ca
cc     ca.c   -o ca
ca.c:1:1: warning: data definition has no type or storage class
ca.c: In function ‘main’:
ca.c:2:5: warning: incompatible implicit declaration of built-in function ‘scanf’
ca.c:3:7: warning: incompatible implicit declaration of built-in function ‘malloc’
ca.c:3:14: warning: incompatible implicit declaration of built-in function ‘strlen’
ca.c:4:5: warning: incompatible implicit declaration of built-in function ‘strcat’

josh@Z1 ~
$ echo 90,11,0,4,0,4,5 | ca
-bash: ca: command not found

josh@Z1 ~
$ echo 90,11,0,4,0,4,5 | ./ca
0000110000
0001111000
0011001100
0111111110
1100000011
0110000110

```

Title: Simulate any 1D cellular automaton

Body:
C (487 484 418 with spaces removed)

*Dropped 66 with help from JoeFish*

C,A,r,n,j;main(){char*s,*p,*t,a[9],b[9],c[9];
    scanf("%d,%[01],%[01],%d,%[01],%d,%d",&r,b,a,&A,c,&C,&n);
    s=malloc(strlen(a)*A+strlen(b)+strlen(c)*C+3);*s=0;
    strcat(s,"0");
    for(;A--;)strcat(s,a);
    strcat(s,b);
    for(;C--;)strcat(s,c);
    strcat(s,"0");
    p=malloc((C=strlen(s)-1)+2);
    for(;n--;){
    *s=s[C-1];
    s[C]=0;
    puts(s+1);
    s[C]=s[1];
    for(j=1;s[j+1];j++)
        p[j]=(1<<(s[j-1]-48)*4+(s[j]-48)*2+s[j+1]-48)&r?49:48;
    t=p;p=s;s=t;
    }
    s[C]=0;
    puts(s+1);
}

typescript

josh@Z1 ~
$ !m
make ca
cc     ca.c   -o ca
ca.c:1:1: warning: data definition has no type or storage class
ca.c: In function ‘main’:
ca.c:2:5: warning: incompatible implicit declaration of built-in function ‘scanf’
ca.c:3:7: warning: incompatible implicit declaration of built-in function ‘malloc’
ca.c:3:14: warning: incompatible implicit declaration of built-in function ‘strlen’
ca.c:4:5: warning: incompatible implicit declaration of built-in function ‘strcat’

josh@Z1 ~
$ echo 90,11,0,4,0,4,5 | ca
-bash: ca: command not found

josh@Z1 ~
$ echo 90,11,0,4,0,4,5 | ./ca
0000110000
0001111000
0011001100
0111111110
1100000011
0110000110


问:
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)

Title: Traveling on a flat Earth

Body:
Ruby, 186 bytes

It's too short, sorry. I did my best.

x=-1
puts gets.scan(/\d+\D/).map{|i|i.to_i*(i[-1]=~/[WS]/?-1:1)}.zip(gets.scan(/\d+\D/).map{|i|i.to_i*(i[-1]=~/[WS]/?-1:1)}).map{|a,b|a+b}.map{|s|s.abs.to_s+%w"NNS EEW"[x+=1][s<=>0]}*' '


问:
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>```

答:
><> (Fish), 30 Bytes

```<code>:2%?'/'o1-:?!;30.
30.  >'\'50p
</code>```

First time using this language, but I think I at least saved a little room by conditionally using the / as either part of the output or a mirror to redirect flow. Probably still horribly inefficient though, I feel like it could probably be cut down a little more at the very least.

Input is the initial stack, output is stdout

Try it online!

Title: The Squiggly Sequence

Body:
><> (Fish), 30 Bytes

:2%?'/'o1-:?!;30.
30.  >'\'50p

First time using this language, but I think I at least saved a little room by conditionally using the / as either part of the output or a mirror to redirect flow. Probably still horribly inefficient though, I feel like it could probably be cut down a little more at the very least.

Input is the initial stack, output is stdout

Try it online!


问:
"99 Bottles of Beer"
Write a program that outputs the lyrics to 99 Bottles of Beer, in as few bytes as possible.

Lyrics:

```<code>99 bottles of beer on the wall, 99 bottles of beer.
Take one down and pass it around, 98 bottles of beer on the wall.

98 bottles of beer on the wall, 98 bottles of beer.
Take one down and pass it around, 97 bottles of beer on the wall.

97 bottles of beer on the wall, 97 bottles of beer.
Take one down and pass it around, 96 bottles of beer on the wall.

96 bottles of beer on the wall, 96 bottles of beer.
Take one down and pass it around, 95 bottles of beer on the wall.

95 bottles of beer on the wall, 95 bottles of beer.
Take one down and pass it around, 94 bottles of beer on the wall.

....

3 bottles of beer on the wall, 3 bottles of beer.
Take one down and pass it around, 2 bottles of beer on the wall.

2 bottles of beer on the wall, 2 bottles of beer.
Take one down and pass it around, 1 bottle of beer on the wall.

1 bottle of beer on the wall, 1 bottle of beer.
Go to the store and buy some more, 99 bottles of beer on the wall.
</code>```

Rules:

Your program must log to STDOUT or an acceptable alternative, or be returned from a function (with or without a trailing newline).

Your program must be a full, runnable program or function.

Languages specifically written to submit a 0-byte answer to this challenge are allowed, just not particularly interesting.

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.

This is different from the output by HQ9+ or 99. Any answers written in these languages will be deleted.

As this is a catalog challenge, this is not about finding the language with the shortest solution for this (there are some where the empty program does the trick) - this is about finding the shortest solution in every language. Therefore, no answer will be marked as accepted.

Catalogue

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

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

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

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

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

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

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

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

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

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

Shortest Solution by Language

Language	User	Score

Leaderboard

	Author	Language	Size

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

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

```

答:
C Preprocessor, 753 bytes

```<code>#ifndef T
#define N
#define T 9
#define G(A,B) I(A,B)
#define I(A,B) A##B
#define X Take one down and pass it around,
#define Y G(bottle,s) of beer
#define Z Y on the wall
#define E(x) G(T,x) Z, G(T,x) Y.
#define F(x) X G(T,x) Z.
#endif
E(9)
F(8)
N
E(8)
F(7)
N
E(7)
F(6)
N
E(6)
F(5)
N
E(5)
F(4)
N
E(4)
F(3)
N
E(3)
F(2)
N
E(2)
#if T+0
F(1)
N
E(1)
F(0)
N
E(0)
#if T<2
#undef T
#define T
#elif T<3
#undef T
#define T 1
#elif T<4
#undef T
#define T 2
#elif T<5
#undef T
#define T 3
#elif T<6
#undef T
#define T 4
#elif T<7
#undef T
#define T 5
#elif T<8
#undef T
#define T 6
#elif T<9
#undef T
#define T 7
#else
#undef T
#define T 8
#endif
F(9)
N
#include __FILE__
#else
#define s
X 1 Z.
N
1 Z, 1 Y.
#undef s
Go to the store and buy some more, 99 Z.
#endif
</code>```

Try it online!

It is my privilege to submit this C preprocessor solution to this catalog.  Note that this is a pure C Preprocessor solution (or, as I prefer to call it, a C Preprocessor solution).  To my knowledge this is the first such solution to be posted to a catalog (there are a few claimed "C preprocessor" solutions around, but they're really things like C programs using the C preprocessor to generate strings).

5 bytes could be saved if I exploited the file name (e.g. changing #include __FILE__ to #include "f").

If anyone can help golf this further let me know.

ContentLicense: CC BY-SA 4.0

Title: "99 Bottles of Beer"

Body:
C Preprocessor, 753 bytes

#ifndef T
#define N
#define T 9
#define G(A,B) I(A,B)
#define I(A,B) A##B
#define X Take one down and pass it around,
#define Y G(bottle,s) of beer
#define Z Y on the wall
#define E(x) G(T,x) Z, G(T,x) Y.
#define F(x) X G(T,x) Z.
#endif
E(9)
F(8)
N
E(8)
F(7)
N
E(7)
F(6)
N
E(6)
F(5)
N
E(5)
F(4)
N
E(4)
F(3)
N
E(3)
F(2)
N
E(2)
#if T+0
F(1)
N
E(1)
F(0)
N
E(0)
#if T<2
#undef T
#define T
#elif T<3
#undef T
#define T 1
#elif T<4
#undef T
#define T 2
#elif T<5
#undef T
#define T 3
#elif T<6
#undef T
#define T 4
#elif T<7
#undef T
#define T 5
#elif T<8
#undef T
#define T 6
#elif T<9
#undef T
#define T 7
#else
#undef T
#define T 8
#endif
F(9)
N
#include __FILE__
#else
#define s
X 1 Z.
N
1 Z, 1 Y.
#undef s
Go to the store and buy some more, 99 Z.
#endif

Try it online!

It is my privilege to submit this C preprocessor solution to this catalog.  Note that this is a pure C Preprocessor solution (or, as I prefer to call it, a C Preprocessor solution).  To my knowledge this is the first such solution to be posted to a catalog (there are a few claimed "C preprocessor" solutions around, but they're really things like C programs using the C preprocessor to generate strings).

5 bytes could be saved if I exploited the file name (e.g. changing #include __FILE__ to #include "f").

If anyone can help golf this further let me know.


答:
C - 267 bytes

I though C would be long... might as well just put it up. ;_;

```<code>#include <stdio.h>
#include <stdlib.h>
int main(){int x,y,z,w;char m,n,o,p;scanf("%d%c %d%c",&x,&m,&y,&n);scanf("%d%c %d%c",&z,&o,&w,&p);int a=x*(m<'O'?1:-1)+z*(o<'O'?1:-1),b=y*(n<'F'?1:-1)+w*(p<'F'?1:-1);printf("%d%c %d%c\n",abs(a),a<0?'S':'N',abs(b),b<0?'W':'E');}
</code>```

Title: Traveling on a flat Earth

Body:
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)

Body:
C - 267 bytes

I though C would be long... might as well just put it up. ;_;

#include <stdio.h>
#include <stdlib.h>
int main(){int x,y,z,w;char m,n,o,p;scanf("%d%c %d%c",&x,&m,&y,&n);scanf("%d%c %d%c",&z,&o,&w,&p);int a=x*(m<'O'?1:-1)+z*(o<'O'?1:-1),b=y*(n<'F'?1:-1)+w*(p<'F'?1:-1);printf("%d%c %d%c\n",abs(a),a<0?'S':'N',abs(b),b<0?'W':'E');}