# Question
Title: Create a simple math calculator +-/* accepting only Chinese characters
**The task:**
Build a calculator that takes a simple math equation in Chinese and outputs the correct answer(To the equation from the users input) in Chinese.

---

**Scope:**

* Any programming language can be used.
* Input must be in Chinese otherwise an error message will be displayed .
* Output must be in Chinese.
* Only input and output of whole numbers between 0-999 will be in scope (this is meant to be a simple calcaulation).
* The full original input must be included prior to equals then the answer.
* Display answer with no decimal points.
* Long number form output is mandatory.
* Input must accept Long number form, inclusion of short form is optional.

**Sample input/output:**

> 二乘以八 (2\*8)
> 二乘以八等于十六 (2\*8=16)

**Cheat Sheet:**

> 零 or 〇 → 0 (either form or both, you choose)
> 一 → 1
> 二 → 2
> 三 → 3
> 四 → 4
> 五 → 5
> 六 → 6
> 七 → 7
> 八 → 8
> 九 → 9
> 十 → 10
> 百 → 100
> 加 → + Operator
> 减 → - Operator
> 乘以 → * Operator
> 除以 → / Operator
> 等于 → = Operator
>
> Chinese numbering is basic 333 is just 3 100 3 10 3 三百三十三 only exception is 十 where you don't need 一十 to say 10 (but you might to), but you do need 一百 to say 100 (i.e., can't say just 百).

Useful link: http://www.mandarintools.com/numbers.html

If you can't see the chinese symbols, you may see them here.

Get creative and happy coding!

# Answer
> 5 votes
# Java

It parses the equation as a context-free language, using these productions for that:

```
U1 = [一-九]                 (i.e. [1-9])
D1 = U1 十 U1?
DO = U1? 十 U1?
CDN = 〇 U1 | D1
C1 = U1 百 CDN?
F = C1 | DO | U1 | 〇
F2 = 負? F
OP = 加 | 减 | 乘以 | 除以    (i.e., + | - | * | / )
EQ = F2 (OP F2)*

```

The `DO` and `D1` productions are handled in the same method, diferentiated by a parameter. The other productions take one method each. The `EQ` is the grammar main symbol. Before starting the parse, it replaces 零 for 〇, so it need to handle just 〇 after that.

The 負 is for negative numbers. It can handle numbers from -999 to 999 (or 負九百九十九 to 九百九十九).

Further, to make it much more chinese, all the identifiers are in chinese. The only exception is the class name (using international characters there may cause problems) that is a chinese name transliterated to latin characters.

For the input I had to use a `JOptionPane`. Sorry for that, but I had trouble about encodings using other input methods. If you don't like this method of input, you can use the `解方程` method directly, it takes the input formula and produce the output equation (or error message).

```
import javax.swing.JOptionPane;

public class ZhongguoJisuanQi {

    private final String 文字输入;
    private int 源指数;

    public ZhongguoJisuanQi(String 文字输入) {
        this.文字输入 = 文字输入.replace("零", "〇");
        this.源指数 = 0;
    }

    public static void main(String... 参数) {
        String 方程 = 解方程(读取文本行());
        System.out.println(方程);
        JOptionPane.showMessageDialog(null, 方程, "答案是", JOptionPane.INFORMATION_MESSAGE);
    }

    private static String 读取文本行() {
        return JOptionPane.showInputDialog(null, "输入数学公式", "输入数学公式", JOptionPane.QUESTION_MESSAGE);
    }

    public static String 解方程(String 数学公式) {
        if (数学公式 == null) return "错误：给定的数学公式的格式不正确。";
        ZhongguoJisuanQi 计算器 = new ZhongguoJisuanQi(数学公式);
        Integer 结果 = 计算器.解析并解决了式();
        if (结果 == null) return "错误：给定的数学公式的格式不正确。";
        return 数学公式 + "等于" + 整数转换为文本(结果);
    }

    private boolean 找到字符(char 字符, int 指数) {
        return 指数 < 文字输入.length() && 文字输入.charAt(指数) == 字符;
    }

    private Integer 解析生产一() {
        int 数 = "一二三四五六七八九".indexOf(文字输入.charAt(源指数));
        if (数 == -1) return null;
        源指数++;
        return 数 + 1;
    }

    private Integer 解析生产十(boolean 必须带有前缀) {
        int 原始来源索引 = 源指数;
        Integer 第一个数字 = 解析生产一();
        if (第一个数字 == null && 必须带有前缀) return null;
        if (!找到字符('十', 源指数)) {
            源指数 = 原始来源索引;
            return null;
        }
        源指数++;
        Integer 第二个数字 = 解析生产一();
        return (第一个数字 == null ? 1 : 第一个数字) * 10 + (第二个数字 == null ? 0 : 第二个数字);
    }

    private Integer 解析生产或零十() {
        int 原始来源索引 = 源指数;
        if (找到字符('〇', 源指数)) {
            源指数++;
            Integer 数 = 解析生产一();
            if (数 == null) {
                源指数 = 原始来源索引;
                return null;
            }
            return 数;
        }
        return 解析生产十(true);
    }

    private Integer 解析生产百() {
        int 原始来源索引 = 源指数;
        Integer 第一个数字 = 解析生产一();
        if (第一个数字 == null) return null;
        if (!找到字符('百', 源指数)) {
            源指数 = 原始来源索引;
            return null;
        }
        源指数++;
        Integer 第二个数字 = 解析生产或零十();
        return 第一个数字 * 100 + (第二个数字 == null ? 0 : 第二个数字);
    }

    private Integer 解析生产数无符号() {
        Integer 数 = 解析生产百();
        if (数 != null) return 数;
        数 = 解析生产十(false);
        if (数 != null) return 数;
        数 = 解析生产一();
        if (数 != null) return 数;
        if (找到字符('〇', 源指数)) {
            源指数++;
            return 0;
        }
        return null;
    }

    private Integer 解析该生产号() {
        boolean 负 = false;
        if (找到字符('負', 源指数)) {
            源指数++;
            负 = true;
        }
        Integer 数 = 解析生产数无符号();
        return 数 == null ? null : 负 ? -数 : 数;
    }

    private String 解析算术运算符() {
        if (找到字符('加', 源指数)) { 源指数++; return "加"; }
        if (找到字符('减', 源指数)) { 源指数++; return "减"; }
        if (找到字符('乘', 源指数) && 找到字符('以', 源指数 + 1)) { 源指数 += 2; return "乘以"; }
        if (找到字符('除', 源指数) && 找到字符('以', 源指数 + 1)) { 源指数 += 2; return "除以"; }
        return null;
    }

    public Integer 解析并解决了式() {
        Integer 第一个数字 = 解析该生产号();
        while (true) {
            String 算术运算符 = 解析算术运算符();
            if (算术运算符 == null) return 源指数 == 文字输入.length() ? 第一个数字 : null;
            Integer 第二个数字 = 解析该生产号();
            if (第二个数字 == null) return null;
            switch (算术运算符) {
                case "加": 第一个数字 += 第二个数字; break;
                case "减": 第一个数字 -= 第二个数字; break;
                case "乘以": 第一个数字 *= 第二个数字; break;
                case "除以": 第一个数字 /= 第二个数字; break;
                default: throw new AssertionError();
            }
        }
    }

    private static String 整数转换为文本(int 参数) {
        if (参数 == 0) return "〇";
        StringBuilder 字符串生成器 = new StringBuilder(7);
        int 数 = 参数;
        if (数 < 0) {
            字符串生成器.append("負");
            数 = -数;
        }
        if (数 >= 1000) return null;
        if (数 >= 100) {
            字符串生成器.append("〇一二三四五六七八九".charAt(数 / 100)).append("百");
            数 %= 100;
            if (数 >= 1 && 数 <= 9) 字符串生成器.append("〇");
            if (数 >= 10 && 数 <= 19) 字符串生成器.append("一");
        }
        if (数 >= 20) 字符串生成器.append("〇一二三四五六七八九".charAt(数 / 10));
        if (数 >= 10) 字符串生成器.append("十");
        数 %= 10;
        字符串生成器.append("〇一二三四五六七八九".charAt(数));
        return 字符串生成器.toString();
    }
}

```

Compile with:

```
javac -encoding UTF8 ZhongguoJisuanQi.java

```

Run with:

```
java ZhongguoJisuanQi

```

Cheat sheet for identifiers names, accordingly to google translator:

```
(english original text) -> (chinese text) -> (english text back from chinese)
chinese calculator -> 中国计算器 (Zhōngguó jìsuàn qì) -> china calculator
text input -> 文字输入 -> text input
source index -> 源指数 -> source index
original source index -> 原始来源索引 -> original source index
Enter the mathematical formula -> 输入数学公式 -> Enter mathematical formulas
mathematical formula -> 数学公式 -> mathematical formulas
Error: The given mathematical formula is malformed. -> 错误：给定的数学公式的格式不正确。 -> Error: The given mathematical formula is not correct.
character -> 字符 -> character
read a text line -> 读取文本行 -> read a line of text
arguments -> 参数 -> parameter
equation -> 方程 -> equation
index -> 指数 -> index
find character at -> 找到字符 -> find characters
parse the production -> 解析生产 -> resolve the production
parse the production or zero -> 解析生产或零 -> resolve the production or zero
parse the production number -> 解析该生产号 -> resolve the production number
parse the production number without sign -> 解析生产数无符号 -> resolve production unsigned
parse and solve the formula -> 解析并解决了式 -> parse and resolve the formula
parse an arithmetic operator -> 解析算术运算符 -> parsing arithmetic operators
arithmetic operator -> 算术运算符 -> arithmetic operators
must be prefixed -> 必须带有前缀 -> must be prefixed with
calculator -> 计算器 -> calculators
solve the equation -> 解方程 -> solving equations
result -> 结果 -> result
number -> 数 -> number
minus -> 负 -> minus
first number -> 第一个数字 -> the first number
second number -> 第二个数字 -> second number
string builder -> 字符串生成器 -> string builder
convert integer to text -> 整数转换为文本 -> integer is converted to text
the answer is -> 答案是 -> the answer is

```

# Answer
> 4 votes
## Haskell

Here is a solution in Haskell with custom made parser combinators. No library is required, all pure functional power. :)

The grammar in the middle of the file describes the structure of the expressions that will be parsed. The grammar itself is the parser, and it is build from terminal parsers, with parser combinators to put them in sequence (`<:>`,`<::>`) or as alternatives (`|||`). Each of the terminal parsers parses a certain string or character, such as an operator or a digit. The evaluation combinator (`==>`) then transforms and calculates the expression.

Some inspiration I found in this blog, but mainly I learned this when I worked with a DSL embedded in Haskell that uses the same approach (ADP, Algebraic Dynamic Programming, I wrote a typechecker for it), here we can even solve optimization problems with dynamic programming! Also there is a nice paper by G.Hutton about parsing with combinators in Haskell.

This was a really fun problem, thanks for suggesting it!

The `calc_own_combi.hs` file:

```
type Parser a = String -> Maybe (a, String)

dict = [('零', 0) ,('〇', 0) ,('一', 1) ,('二', 2) ,('三', 3) ,('四', 4) ,('五', 5) ,('六', 6) ,('七', 7) ,('八', 8) ,('九', 9), ('十',10), ('百',100)]

-- parse 1 character
char :: Parser Char
char [] = Nothing
char (x:xs) = Just(x, xs)

-- parse a chinese digit
cndigit :: Parser Char
cndigit = char <== isCNdigit
  where isCNdigit c = elem c $ map fst dict

-- parse a string literal
literal :: String -> Parser String
literal s [] = Nothing
literal s xs = if (head==s) then Just(head, tail)
                            else Just("", xs)
  where (head,tail) = splitAt (length s) xs

-- parse and evaluate the following terminal symbols
digit = cndigit ==> cnDigitToInt
  where cnDigitToInt d = head [snd x | x <- dict, fst x==d]
add  = literal "加"   ==> (\_ -> (+))
subt = literal "减"   ==> (\_ -> (-))
mult = literal "乘以" ==> (\_ -> (*))
divi = literal "除以" ==> (\_ -> div)
tens = literal "十"   ==> (\_ -> t)
  where t a b = a * 10 + b
hndrds = literal "百" ==> (\_ -> h)
  where h a b = a * 100 + b

-- inject a 1 into the parse in case people underspecify tens
inject1 :: Parser Integer
inject1 s = Just (1, s)

-- the grammar
expression = number <:> add  <::> number |||
             number <:> subt <::> number |||
             number <:> mult <::> number |||
             number <:> divi <::> number |||
             number
number = digit <:> (hndrds <::> (digit <:> tens <::> digit)) |||
         digit <:> tens <::> digit |||
         digit |||
         inject1 <:> tens <::> digit -- inject 1 to reuse the function

-- run the calculator as a repl
main = putStrLn "type ':q' to quit." >> repl
 where
  repl = do
         input <- getLine
         let result = printNum $ eval input
         if ((== ":q") input)
           then return ()
           else putStrLn (input ++ "等于" ++ result) >> repl

-- call the grammar to parse and evaluate
eval s = case expression s of
   Just (n,[]) -> n
   Just (n,xs) -> error $ "Could not parse input, got stuck on "++xs
   Nothing -> error $ "Could not parse input at all "++s

-- reencode a number into chinese
printNum x = h' ++ t' ++ o
 where o  = if ((h'/="" || t'/="") && tRest == 0) then "" else [intToCNDigit tRest]
       h' = printDigit h "百"
       t' = printDigit t "十"
       printDigit d c | d==0 = ""
                      | d==1 && c=="百" = '一':c
                      | d==1 = c
                      | otherwise = intToCNDigit d:c
       (t, tRest) = divMod hRest 10
       (h, hRest) = divMod x 100
       intToCNDigit d =  head [fst x | x <- dict, snd x==d]

-- the combinators:

-- return the result of the parser only if
-- it also satisfies the given predicate - like `with` in ADP
infix 7 <==
(<==) :: Parser a -> (a -> Bool) -> Parser a
(m <== p) s = case m s of
        Nothing     -> Nothing
        Just(a,s)  -> if p a then Just(a,s) else Nothing

-- alternative/or combinator
infixl 3 |||
(|||) :: Parser a -> Parser a -> Parser a
(m ||| n) s = case m s of
    Nothing -> n s
    ms -> ms

-- next/sequence combinator
-- reverse polish notation needs just this:
-- testRPExp = digit <:> (digit <:> add)
infixl 6 <:>
(<:>) :: Parser a -> Parser (a -> b) -> Parser b
(m <:> n) s = case m s of
    Nothing -> Nothing
    Just (a, s') -> case n s' of
        Nothing -> Nothing
        Just (b, s2) -> Just (b a, s2)

-- next/sequence combinator, right side
-- infix notation needs this second combinator:
-- testExp = digit <:> add <::> digit
infixl 5 <::>
(<::>) :: Parser (a->b) -> Parser a -> Parser b
(m <::> n) s = case m s of
    Nothing -> Nothing
    Just (a, s') -> case n s' of
        Nothing -> Nothing
        Just (b, s2) -> Just (a b, s2)

-- evaluate a parse result :)
infixl 5 ==>
(==>) :: Parser a -> (a -> b) -> Parser b
(m ==> n) s = case m s of
    Nothing -> Nothing
    Just (a, s') -> Just (n a, s')

```

Running it:

```
┌─[linse@yolocat]─[~/test]
└──╼ ghc -o calc calc_own_combi.hs
[1 of 1] Compiling Main             ( own_combi.hs, own_combi.o )
Linking calc ...
┌─[linse@yolocat]─[~/test]
└──╼ ./calc
type ':q' to quit.
二乘以八
二乘以八等于十六
:q

```

# Answer
> 2 votes
# Smalltalk (Smalltalk/X)

using a packrat parser (just a q&d hack, I guess, this could be done better, especially the number parsing; I was not 100% sure, when it is allowed to leave out zeros...).
Also, I don't understand what "零 or 〇 → 0" means; does it mean "it must support both" or "I can choose to support either"?
Anyway, if required, the d0 rule could be changed easily.
For readability, the code is not golfified.

```
"/ parsing digits
d0 := ($零 asParser ==> [:c|0]).
d1 := ($一 asParser ==> [:c|1]).
d2 := ($二 asParser ==> [:c|2]).
d3 := ($三 asParser ==> [:c|3]).
d4 := ($四 asParser ==> [:c|4]).
d5 := ($五 asParser ==> [:c|5]).
d6 := ($六 asParser ==> [:c|6]).
d7 := ($七 asParser ==> [:c|7]).
d8 := ($八 asParser ==> [:c|8]).
d9 := ($九 asParser ==> [:c|9]).
t:= $十 asParser.
h:= $百 asParser.
d := d1|d2|d3|d4|d5|d6|d7|d8|d9.
"/ parsing numbers
n :=
    ((d,h,d,t,d) ==> [:a| (a first*100)+(a third *10)+a fifth])
    / ((d,h,d,t) ==> [:a| (a first*100)+(a third *10)])
    / ((d,h,d) ==> [:a| (a first*100)+(a third)])
    / ((d,h) ==> [:a| a first*100])
    / ((d,t,d) ==> [:a| (a first*10)+(a third)])
    / ((d,t) ==> [:a| a first*10])
    / ((t,d) ==> [:a| a second+10])
    / d0
    / d
    / (t ==> [:c|10])
    .
"/ operators
A:= ($加 asParser)==>[:c|#+].
S:= ($减 asParser)==>[:c|#-].
M := ($乘 asParser , $以 asParser)==>[:c|#*].
D:= ($除 asParser , $以 asParser)==>[:c|#/].

"/ times and quotient
T:= ((n,M,T) ==>[:a|(a first * a third)])
   / ((n,D,T) ==>[:a|(a first / a third)])
   / n
   .

"/ sum and difference
E:=((T,A,E) ==>[:n|(n first + n third)])
   / ((T,S,E) ==>[:n|(n first - n third)])
   / T
   .

"/ printing (number->string)
di:= #( $一 $二 $三 $四 $五 $六 $七 $八 $九).
P:=[:n|
  n>=100
    ifTrue:[ (di at:(n//100)),$百,(P value:(n\\100)) ]
    ifFalse:[
      n>20
        ifTrue:[ (di at:(n//10)),$十,(P value:(n\\10)) ]
        ifFalse:[
          n>10
            ifTrue:[$十,(P value:(n\\10))]
            ifFalse:[
              n==10
                ifTrue:[$十]
                ifFalse:[
                  n==0
                    ifTrue:[$零]
                    ifFalse:[(di at:n) ]]]]]].
"/ evaluate an expression and return numeric value
p:= (E end) ==> P.

"/ the calculator, parse, concatenate input,EQ,number string
calc:=[:s | s,'等于',(p parse:s)].

```

usage:

```
calc value:'二乘以八'.

```

-\> '二乘以八等于十六'

# Answer
> 1 votes
I tried writing this one in python:

```
import compiler
# encoding: utf-8

# python chinese calculator,

c2e = {('1','一'),('2','二'),('3','三'),('4','四'),('5','五'),('6','六'),('7','七'),('8','八'),('9','九'),('0','零')}

def tochi(eq):
    for en,ch in c2e:
        eq.replace(en,ch)
    return eq

def toen(eq):
    for en,ch in c2e:
        eq.replace(ch,en)
    return eq

if __name__ == "__main__":
    while True:
        eqin = raw_input('Equation with chinese numbers: ')
        eqin = toen(eqin)
        eqout = compiler.parse(eqin)
        eqout = tochi(eqout)
        print eqout

```

---
Tags: math, popularity-contest
---


# Question
Title: Bloatware contest: producing 100+ MiB executable
Create short source code in your favourite compiled language that compiles into a big (not less than 104857600 bytes) executable file. The program must be runnable (assuming 1GB of free memory) and can do anything (preferrable something simple like a hello world).

Usage of non-obvious tricks is encouraged.

Boring example in C:

```
int a[1024*1024*25] = { 1 };

int main(){}

```

Bonus points if it can be "explained" why the executable can't be reduced in size (i.e. all bloat is actually used somehow).

# Answer
OK, here's another one in C, going for the vaguely defined bonus points:

```
#define a(x) x,x|1,x|2,x|3,x|4,x|5,x|6,x|7
#define b(x) a(x),a(x|8),a(x|16),a(x|24)
#define c(x) b(x),b(x|32),b(x|64),b(x|96)
#define d(x) c(x),c(x|128),c(x|256),c(x|384)
#define e(x) d(x),d(x|512),d(x|4<<8),d(x|6<<8)
#define f(x) e(x),e(x|2048),e(x|4096),e(x|6144)
#define g(x) f(x),f(x|8192),f(x|4<<12),f(x|6<<12)
#define h(x) g(x),g(x|2<<14),g(x|4<<14),g(x|6<<14)
#define i(x) h(x),h(x|2<<16),h(x|4<<16),h(x|6<<16)
#define j(x) i(x),i(x|2<<18),i(x|4<<18),i(x|6<<18)
#define k(x) j(x),j(x|2<<20),j(x|4<<20),j(x|6<<20)
int u,v,z[]={k(0),k(2<<22),k(4<<22),k(6<<22)}
int main(){for(u=v=0;u<1<<25;u++)v|=u!=z[u];return v;}

```

Basically, at compile time, it build a ascending sequence of integers from 0 to 225 − 1. At runtime, it verifies that the sequence indeed contains the expected values, and if not, returns a non-zero error code.

Ps. If I did my math right, the executable should be over 100 MiB. I'll let you know the exact size once it's done compiling...
> 13 votes

# Answer
## C#

Not sure if this qualifies as short, because the source code ended up being \>30k :)

I.e - too big to quote. Here's a slightly shortened version of it

```
using System.Collections.Generic;
class Program
{
    static void Main()
    {
        var a = new List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<int>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>();
    }
}

```

The code I actually compiled can be found here: http://pastebin.com/R5T3e3J0

This will create a .EXE file of ~45KiB when compiled without optimizations. Compile it again with Ngen.exe (Native Image Generator) and it becomes a whopping 104MiB!

This works due to how the CLR generic type system works. Each and every List\<\> in the above code will generate a new type declaration (normally through JIT compilation, but Ngen performs AOT compilation). So one type for List\< int \>, another for List\< List\< int \> \>, and so on. So for this code, a total of 5160 different generic lists will be created.
> 6 votes

# Answer
**COBOL**

```
   ID DIVISION.
   PROGRAM-ID. BLOAT.
   ENVIRONMENT DIVISION.
   DATA DIVISION.
   WORKING-STORAGE SECTION.
   01  THE-TEST-STRINGS.
       05  FILLER OCCURS 11584 TIMES.
           10  TEST-STRING          PIC X(11584).
   LOCAL-STORAGE SECTION.
   01  FIRST-TIME-FLAG              PIC X VALUE "Y".
   01  DISP-BEFORE-STRING     COMP  PIC 9(8).
   01  LOOP-COUNTER           COMP  PIC 9(8).
   01  START-STRING.
       05  FILLER OCCURS 0 TO 11584 TIMES
           DEPENDING ON DISP-BEFORE-STRING.
           10  FILLER               PIC X.
       05  THE-SUBSTRING            PIC X(12).
   01  INITIAL-STRING               PIC X(12)
                                     VALUE "HELLO WORLD!".
   LINKAGE SECTION.
   01  STRING-PARAMETER             PIC X(11584).
   01  THE-RESULT                   PIC X.
   PROCEDURE DIVISION USING
                                    STRING-PARAMETER
                                    THE-RESULT
                                    .

       IF FIRST-TIME-FLAG = "Y"
           PERFORM                  SET-UP-STRINGS
       END-IF
       PERFORM
         VARYING                    LOOP-COUNTER
         FROM                       1
           BY                       1
         UNTIL                      LOOP-COUNTER
           GREATER THAN 11584
         OR STRING-PARAMETER
             EQUAL TO               TEST-STRING
                                        ( LOOP-COUNTER )
       END-PERFORM
       IF STRING-PARAMETER
         EQUAL TO TEST-STRING ( LOOP-COUNTER )
           MOVE "Y"                TO THE-RESULT
       ELSE
           MOVE "N"                TO THE-RESULT
       END-IF
       GOBACK
       .
   SET-UP-STRINGS.
       PERFORM
         VARYING                    LOOP-COUNTER
         FROM                       0
           BY                       1
         UNTIL                      LOOP-COUNTER
           EQUAL TO 11584
           MOVE 11584               TO DISP-BEFORE-STRING
           MOVE SPACE               TO START-STRING
           MOVE LOOP-COUNTER        TO DISP-BEFORE-STRING
           MOVE INITIAL-STRING      TO THE-SUBSTRING
           MOVE START-STRING        TO TEST-STRING
                                        ( LOOP-COUNTER + 1 )
       END-PERFORM
       MOVE "N"                     TO FIRST-TIME-FLAG
       .

```

A little knowledge can be a dangerous thing.

It can be faster to do one large compare than a lot of small compares; IBM's Enterprise COBOL (up to Version 4.2) can have a maximum WORKING-STORAGE of 128MB (Version 5.0 can have 2GB); LOCAL-STORAGE offers a further 128MB if you need more space.

The task is to confirm that a 11584-byte piece of storage has the value "HELLO WORLD!" somewhere, and the rest is space.

The, fictitious, programmer decides to write a sub-program for this (just in case it is needed elsewhere), and to include their high-performance technique (bonus).

The programmer calculates that 11584 * 11584 is 128MB, so uses WORKING-STORAGE for a huge table, and LOCAL-STORAGE for everything else that is needed.

The programmer codes it up, and smiles knowingly to themselves when the compile is clean. They were right about the 128MB.

Tests the code. It works. Possibly a little slow, but there's a heavy load on machine. Smiles again, thinking how slow it would be if coded without their level of expert knowledge.

The WORKING-STORAGE comes in at 134,189,056 bytes, and there's a good few bytes of other stuff as well. Should be large enough.

The reality is that doing a long compare instead of a short compare, as implemented here, is a very slow way to do it.

Even slower, the LOCAL-STORAGE, which is initialised by run-time routines every time a sub-program is called, causes the entire 128MB to be set up for each CALL.

The programmer was just plain wrong about the size of the table, there is enough room without using LOCAL-STORAGE. Long compares can beat short compares, but only when the actual number of compares is reduced.

I considered swapping the LOCAL-STORAGE and WORKING-STORAGE around, it is just far less likely someone would code it that way round, so I didn't. Putting a VALUE SPACE on the table (if it had been in LOCAL-STORAGE) would have initilised the table *twice* on each CALL, so even slower.

The Bloat can't be removed, without rewriting the program. Most of the code is bad, though there is one useful technique.

This is not a real-life example, but I can imagine someone doing it, if that someone is clever enough :-)

Compiling is no problem at all. Running it with every possibility quickly proves to be not worth attempting.

Of course, there is a plain old Bug as well. A very common one in "searching" tasks.
> 5 votes

# Answer
# PowerBASIC

```
#BLOAT(104857600)
FUNCTION PBMAIN
  PRINT "Hello World"
  BEEP
END FUNCTION

```
> 0 votes

# Answer
# Scala

```
import scala.{specialized=>s}
import scala.Specializable.{Everything=>E}
class Printer[@s(E) A, @s(E) B, @s(E) C, @s(E) D, @s(E) E, @s(E) F, @s(E) G, @s(E) H]{
    def print(a:A,b:B,c:C)=println(s"$a, $b, $c")
}

object Main extends App{
    (new Printer[Int,Int,Int,Int,Int,Int,Int,Int]).print(1,2,3)
}

```

---

The specialized annotation creates a new class for each type in order to prevent boxing when the types eventually all get turned into objects. It will create 10^8 ((`Everything` consists of 10 types)^(8 type parameters on the class)) class files, each 300-500 bytes, if it doesn't crash first.

---

This could be explained by saying that performance is important, especially if the class actually did more than have a method to print. Using generic specialized methods instead of putting it all in the declaration would also make it harder to notice
> 0 votes

# Answer
## Javascript

```
function bigenough(){
        var kbytes = $('html').html().length;
        return (kbytes>1024*100);
}
while(!bigenough()){
$('html').append('<p>WASSUP</p>');}

```

Run this code in Browser Console on this page and when complete, save the page. it should result in a file size greater than 100 MB. Still testing. Will post actual size once done.

**update-**
the saved page is the result executable. The v8 engine of chrome is the compiler. And the code I posted is the program. i admit that it does take quiet a long to compile. :D
> -2 votes

---
Tags: popularity-contest, compile-time
---


title: Sharing Inherited Land

text:
# Question
Title: Sharing Inherited Land
You and your brother have inherited a rectanglar block of land. This block of land's corners are read in from stdio as `TLX,TLY,TRX,TRY,BLX,BLY,BRX,BRY` (all decimal numbers without units, T=Top, L=Left, B=Bottom, R=Right)

Unfortunately the city has seen fit to appropriate a small rectanglar section from inside your you newly aquired land. This appropriated land can be at any angle and in any position on your land. Its corners are read in from stdio as `TLX,TLY,TRX,TRY,BLX,BLY,BRX,BRY` (all decimal numbers without units).

You need to split this land evenly with your brother by building a fence. The fencing contractors can only build a single straight line fence. You need to supply them with the start and end co-ordinates which sit along the parameter of your property. These are written to stdio as `SX,SY,EX,EY` (all decimal numbers without units, S=Start, E=End)

The city has graciously agreed to allowed you to freely build the fence across their bit of appropriated property.

**Provide a solution which can accept the 2 rectangle co-ordinates and return a correct solution which divides the property area equally for you and your brother.**

visualized samples of potential input (white = your land, grey = city land):

*{I'll insert the credit here after people have answered}*

# Answer
**C**

```
#include <stdio.h>
#include <stdlib.h>
#include <memory.h>

enum mode
{
    CORD_MODE_CONST = 1,
    CORD_MODE_SLOPE = 2,
};
typedef struct point {
    float x;
    float y;
} CORD;

typedef struct l {
    int mode;
    float m;
    float b;
}LINE;

typedef struct r {

    CORD topL;
    CORD botL;

    CORD topR;
    CORD botR;

    CORD midRight;
    CORD midBot;
    CORD midLeft;
    CORD midTop;

    CORD center;
    LINE vertLine;
    LINE horLine;

} RECTANGLE;

void findBorderIntersection(RECTANGLE * pR, LINE * p);
int isPointContained(RECTANGLE * pR, CORD * pC1);
float dotProduct(float y1, float y2, float x1, float x2);
void findCenterOfRetangle(RECTANGLE * pR);
void findIntersection(LINE * pL1, LINE * pL2, CORD *pInt);
void findMidPointOfLine(CORD * pC1, CORD * pC2, CORD * pMid);
void getLine(CORD * pC1, CORD * pC2, LINE * pLine );

void dumpCord(char * pS, CORD * pC)
{
    printf(" %s y:%f x:%f\n",pS,pC->y,pC->x);
}

int main()
{
    RECTANGLE yourLand;
    RECTANGLE cityLand;
    LINE  lineThroughCenter;

    memset(&yourLand,0x0, sizeof(RECTANGLE));
    memset(&cityLand,0x0, sizeof(RECTANGLE));

    scanf("%f%f%f%f%f%f%f%f",&(yourLand.topL.x),
                             &(yourLand.topL.y),
                             &(yourLand.topR.x),
                             &(yourLand.topR.y),
                             &(yourLand.botL.x),
                             &(yourLand.botL.y),
                             &(yourLand.botR.x),
                             &(yourLand.botR.y));

    scanf("%f%f%f%f%f%f%f%f",&(cityLand.topL.x),
                             &(cityLand.topL.y),
                             &(cityLand.topR.x),
                             &(cityLand.topR.y),
                             &(cityLand.botL.x),
                             &(cityLand.botL.y),
                             &(cityLand.botR.x),
                             &(cityLand.botR.y));

    /* Find center of your land */
    findCenterOfRetangle(&yourLand);

    /* Find center of city land */
    findCenterOfRetangle(&cityLand);

    /* Handle the case where the centers are right on top of each other */
    if((yourLand.center.x == cityLand.center.x) &&
     (yourLand.center.y == cityLand.center.y))
    {
        /* Find the line through center and the top border */
        getLine(&(yourLand.midTop),&(cityLand.center),&lineThroughCenter);
    }
    else
    {
        /* Find the line through center of both lands */
        getLine(&(yourLand.center),&(cityLand.center),&lineThroughCenter);
    }

    /* Find the border cords */
    findBorderIntersection(&(yourLand),&lineThroughCenter);

    return 0;
}
void findBorderIntersection(RECTANGLE * pR, LINE * p)
{
    LINE line;
    CORD c1;
    CORD c2;

    int bTop = 0;

    getLine(&(pR->topL), &(pR->topR),&line);

    /* Figure out if the the line goes through the top/bottom or right/left */
    if( p->m != line.m)
    {
          findIntersection(p,&line, &c1);
          bTop = isPointContained(pR,&c1);
    }

    if(bTop)
    {
        getLine(&(pR->botL), &(pR->botR),&line);
        findIntersection(p,&line, &c2);
    }
    else
    {
        getLine(&(pR->topL), &(pR->botL),&line);
        findIntersection(p,&line, &c1);

        getLine(&(pR->topR), &(pR->botR),&line);
        findIntersection(p,&line, &c2);
    }

    dumpCord("Border Cord1:",&c1);
    dumpCord("Border Cord2:",&c2);

}

int isPointContained(RECTANGLE * pR, CORD * pC1)
{
    float pointProduct1;
    float vectorProduct1;
    float pointProduct2;
    float vectorProduct2;

    vectorProduct1 = dotProduct((pR->topL.y - pR->botL.y),
                               (pR->topL.y - pR->botL.y),
                               (pR->topL.x - pR->botL.x),
                               (pR->topL.x - pR->botL.x));

    pointProduct1 = dotProduct((pC1->y - pR->botL.y),
                              (pR->topL.y - pR->botL.y),
                              (pC1->x - pR->botL.x),
                              (pR->topL.x - pR->botL.x));

    vectorProduct2 = dotProduct((pR->botR.y - pR->botL.y),
                               (pR->botR.y - pR->botL.y),
                               (pR->botR.x - pR->botL.x),
                               (pR->botR.x - pR->botL.x));

    pointProduct2 = dotProduct((pC1->y - pR->botL.y),
                              (pR->botR.y - pR->botL.y),
                              (pC1->x - pR->botL.x),
                              (pR->botR.x - pR->botL.x));

    if( (pointProduct1 <= vectorProduct1) &&
        (pointProduct1 >= 0) &&
        (pointProduct2 <= vectorProduct2) &&
        (pointProduct2 >= 0))
    {
        return 1;
    }

    return 0;

}
float dotProduct(float y1, float y2, float x1, float x2)
{
    return y1*y2 + x1*x2;
}

void findCenterOfRetangle(RECTANGLE * pR)
{
     /* Find the mid point of the left side */
    findMidPointOfLine(&(pR->topL), &(pR->botL), &(pR->midLeft));

     /* Find the mid point of the right side */
    findMidPointOfLine(&(pR->topR), &(pR->botR), &(pR->midRight));

    /* Get the line */
    getLine(&(pR->midLeft), &(pR->midRight), &(pR->horLine));

     /* Find the mid point of the top side */
    findMidPointOfLine(&(pR->topL), &(pR->topR), &(pR->midTop));

     /* Find the mid point of the bottom side */
    findMidPointOfLine(&(pR->botL), &(pR->botR), &(pR->midBot));

    /* Get the line */
    getLine(&(pR->midTop), &(pR->midBot), &(pR->vertLine));

    /* Find the center of the first rectangle */
    findIntersection(&(pR->horLine), &(pR->vertLine),&(pR->center));

}
void findIntersection(LINE * pL1, LINE * pL2, CORD *pInt)
{

    if(pL1->mode == CORD_MODE_CONST)
    {
        pInt->x = pL1->m;
        pInt->y = ((pL2->m * pInt->x) + pL2->b);
    }
    else if(pL2->mode == CORD_MODE_CONST)
    {
        pInt->x = pL2->m;
        pInt->y = ((pL1->m * pInt->x) + pL1->b);
    }
    else
    {
        pInt->x = (pL2->b - pL1->b) / (pL1->m - pL2->m);
        pInt->y = ((pL2->m * pInt->x) + pL2->b);
    }
}

void findMidPointOfLine(CORD * pC1, CORD * pC2, CORD * pMid)
{
    pMid->y = (pC1->y + pC2->y) / 2;
    pMid->x = (pC2->x + pC1->x) / 2;
}
void getLine(CORD * pC1, CORD * pC2, LINE * pLine )
{

    /* Find slope */
    if((pC1->x - pC2->x) == 0)
    {
        pLine->mode = CORD_MODE_CONST;
        pLine->m = pC1->x;
        pLine->b = 0;
    }
    else
    {
        pLine->mode = CORD_MODE_SLOPE;
        pLine->m = ((pC1->y - pC2->y) / (pC1->x - pC2->x));

        /* Find y inter. */
        pLine->b = pC1->y - (pLine->m * pC1->x);
    }
}

```
> 3 votes

# Answer
Assuming the land you inherit is square to the grid, this should do the job in **Java**.

```
import java.io.*;

class Land {

    public static void main(String[] args) {

        BufferedReader r = new BufferedReader(new InputStreamReader(System.in));

        double[] corners = new double[16];
        for(int i = 0; i < 16; i++) {
            try {
                corners[i] = Double.parseDouble(r.readLine());
            } catch (Exception e) {
                System.err.println("Error in input! Please try again.");
                i--;
            }
        }

        // Find mid point of own land
        double lx = (corners[0] + corners[6])/2;
        double ly = (corners[1] + corners[7])/2;
        System.out.println("Mid point of your land: "+ lx + ", " + ly);

        // Find mid point of city land
        double cx = (corners[8] + corners[14])/2;
        double cy = (corners[9] + corners[15])/2;
        System.out.println("Mid point of city land: "+ cx + ", " + cy);

        double sx, sy;

        // Check for div by 0
        if(cx-lx == 0) {
            sx = lx;
            sy = corners[1];
        } else {
            // Find gradient
            double m = (cy-ly)/(cx-lx);
            System.out.println("Gradient: " + m);
            // Find constant
            double c = ly - (m * lx);
            System.out.println("Constant: " + c);

            if((m*corners[0] + c) >= corners[1]) {
                sy = m*corners[0] + c;
                sx = corners[0];
            } else {
                // use where line crosses x axis
                sy = corners[1];
                sx = (sy - c) / m;
            }
        }

        // Apply the offsets to the lower corner
        double ex = corners[6] - (sx - corners[0]);
        double ey = corners[7] - (sy - corners[1]);

        System.out.println("Fence start: "+ sx + ", " + sy);
        System.out.println("Fence end  : "+ ex + ", " + ey);
    }

}

```

Edit: just to clarify this also assumes a grid where top left is 0,0.
> 1 votes

# Answer
## Python 2.7

My thinking is:

* Line should pass through the centre of the brothers' land to split the 'additive area' equally.
* Line should pass through the centre of the city's land to split the 'subtractive area' equally.
* Line will pass through 'opposite edges' of the brothers' land.
* Whether this is on the left-right edges or top-bottom edges depends on in which 'diagonal quadrant' of the land the centre of the city's portion lies.

So:

* find centres
* find diagonal quadrant
* find intersection points with edges

Code (Dense, huh? Only that pesky 'else' shorter than 70 chars! Not on purpose!):

```
cent = lambda p0,p1: {'x':(p0['x']+p1['x'])/2,'y':(p0['y']+p1['y'])/2}
dx = lambda p0,p1: p1['x']-p0['x']; dy = lambda p0,p1: p1['y']-p0['y']
dxdy=lambda p0,p1: 0 if (p0['x']==p1['x'] or p0['y']==p1['y']) else dx(p0,p1)/dy(p0,p1)
dydx=lambda p0,p1: 0 if (p0['x']==p1['x'] or p0['y']==p1['y']) else dy(p0,p1)/dx(p0,p1)
y_at_x = lambda p,lp0,lp1: lp0['y'] + (p['x']-lp0['x']) * dy(lp0,lp1)/dx(lp0,lp1)
print "input brothers' land TLX,TLY,TRX,TRY,BLX,BLY,BRX,BRY:"; land=input()
print 'input city land TLX,TLY,TRX,TRY,BLX,BLY,BRX,BRY:'; city=input()
land_cent = cent({'x':land[0],'y':land[1]},{'x':land[6],'y':land[07]})
city_cent = cent({'x':city[0],'y':city[1]},{'x':city[6],'y':city[7]})
in_half_tr = y_at_x(city_cent,{'x':land[0],'y':land[1]},{'x':land[6],'y':land[7]}) < city_cent['y']
in_half_br = y_at_x(city_cent,{'x':land[2],'y':land[3]},{'x':land[4],'y':land[5]}) < city_cent['y']
if in_half_tr ^ in_half_br # left or right = top-right XOR bottom-right
  sp0 = {'x': land[0], 'y': land_cent['y'] - (land_cent['x']-land[0])*dydx(city_cent,land_cent)}
  sp1 = {'x': land[2], 'y': land_cent['y'] - (land_cent['x']-land[2])*dydx(city_cent,land_cent)}
else:
  sp0 = {'x': land_cent['x'] - (land_cent['y']-land[1])*dxdy(city_cent,land_cent), 'y': land[1]}
  sp1 = {'x': land_cent['x'] - (land_cent['y']-land[5])*dxdy(city_cent,land_cent), 'y': land[5]}
print "splitting line from: (%s, %s) to (%s, %s)" % (sp0['x'], sp0['y'], sp1['x'], sp1['y'])

```

Seems to work for some test cases:

```
input brothers' land TLX,TLY,TRX,TRY,BLX,BLY,BRX,BRY:
0.0,0.0,4.0,0.0,0.0,4.0,4.0,4.0
input city land TLX,TLY,TRX,TRY,BLX,BLY,BRX,BRY:
1.0,0.0,3.0,0.0,1.0,1.0,3.0,1.0
splitting line from: (2.0, 0.0) to (2.0, 4.0)

```

And:

```
input brothers' land TLX,TLY,TRX,TRY,BLX,BLY,BRX,BRY:
0.0,0.0,4.0,0.0,0.0,4.0,4.0,4.0
input city land TLX,TLY,TRX,TRY,BLX,BLY,BRX,BRY:
0.0,0.0,1.0,0.0,0.0,1.0,1.0,1.0
splitting line from: (0.0, 0.0) to (4.0, 4.0)

```
> 0 votes

---
Tags: code-challenge, math
---


title: Calculate Chinese Zodiac sign

text:
# Question
Title: Calculate Chinese Zodiac sign
Given that the Chinese New Year is coming, here is a challenge to calculate the Chinese Zodiac, element and Taijitu for a given date.

The input should be a date:

```
1/31/2014

```

The date used here is the US style `mm/dd/yyyy`, but may alternatively be ISO-8601 style: `yyyy-mm-dd` so the style of date input is not strict.

The output should be the animal sign in the Chinese Zodiac including the element that corresponds to the date, and its Taijitu counterpart:

```
Horse - Wood - Yang

```

A table showing the Zodiac - element - Taijitu relationship can be seen here: Chinese Zodiac - Years

The output format is not strict but should contain animal, element and Taijitu component, and should be delimited in some fashion.

Examples of valid output for the above date might include:

```
(horse, wood, yang)
["Horse", "Wood", "Yang"]

```

Your program should return valid output for a range of at least 100 years, including today's date. This means that it will need to account for at least two 60 year (Sexagenary) cycles.

# Answer
# Python 2: 360* ~~387~~ ~~586~~ ~~594~~ \- Characters

Reduced further

```
m,n,p=map(int,raw_input().split("/"));p-=1924;d=int("5od2nauh6qe4obvj8rf5pd2math6re3ocvi8sf5pd2l9uh6rf3nbvi7sg5pd2k9th6rf4navj7sg5oc1m9ti7qe3navj8sg5pc1math6qd3nbvj8sf4oc1ma"[p],36);p-=31*m-31+n<(d<21)*31+d;print"Rat Ox Tiger Rabbit Dragon Snake Horse Goat Monkey Rooster Dog Pig".split()[p%12],"Wood Fire Earth Metal Water".split()[p%10/2],["Yang","Yin"][p%2]

```

The above code works for the following interval: 5 Feb 1924 – 31 Dec 2043

Example: after pasting the above code in the python interpreter cursor

```
>>> m,n,p=map(int,raw_input().split("/"));p-=1924;d=int("5od2nauh6qe4obvj8rf5pd2math6re3ocvi8sf5pd2l9uh6rf3nbvi7sg5pd2k9th6rf4navj7sg5oc1m9ti7qe3navj8sg5pc1math6qd3nbvj8sf4oc1ma"[p],36);p-=31*m-31+n<(d<21)*31+d;print"Rat Ox Tiger Rabbit Dragon Snake Horse Goat Monkey Rooster Dog Pig".split()[p%12],"Wood Fire Earth Metal Water".split()[p%10/2],["Yang","Yin"][p%2]

```

and then press `Enter`, input a date like this

```
6/13/2018

```

and then press `Enter` again, output will be

```
Dog Earth Yang

```

---

* reduced further 27 bytes with Brian's help see comments.
> 4 votes

# Answer
## Mathematica 63

Okay, this may be getting old, but it works (date input is ambiguous in many cases):

```
z=WolframAlpha[#<>" Chinese zodiac",{{"Result",1},"Plaintext"}] &

```

Example:

```
z@"1/31/2014"

```

> "Horse (Yang Wood)"
> 4 votes

# Answer
## C# – ~~357~~ ~~337~~ 339 bytes

```
string Z(System.DateTime d){var c=new System.Globalization.ChineseLunisolarCalendar();var y=c.GetSexagenaryYear(d);var s=c.GetCelestialStem(y)-1;return",Rat,Ox,Tiger,Rabbit,Dragon,Snake,Horse,Goat,Monkey,Rooster,Dog,Pig".Split(',')[c.GetTerrestrialBranch(y)]+" - "+"Wood,Fire,Earth,Metal,Water".Split(',')[s/2]+" - Y"+(s%2>0?"in":"ang");}

```

Formatted:

```
string Z(System.DateTime d)
{
  var c = new System.Globalization.ChineseLunisolarCalendar();
  var y = c.GetSexagenaryYear(d);
  var s = c.GetCelestialStem(y) - 1;
  return
    ",Rat,Ox,Tiger,Rabbit,Dragon,Snake,Horse,Goat,Monkey,Rooster,Dog,Pig".Split(',')[c.GetTerrestrialBranch(y)]
    + " - "
    + "Wood,Fire,Earth,Metal,Water".Split(',')[s / 2]
    + " - Y" + (s % 2 > 0 ? "in" : "ang");
}

```
> 4 votes

# Answer
## Ruby, 340

```
m,d,y=gets.split(?/).map(&:to_i);y+=1if 31*m+d-51>"d88jac8mlbuppp21ygmkjsnfsd4n3xsrhha4abnq9zgo6g2jupc39zav84434f75op4ftfhdcsa3xhc8nsw1ssw8p9qns1tf14mncy8j18msr9rsb7j7".to_i(36)>>5*y-9625&31
$><<[%w(Goat Monkey Rooster Dog Pig Rat Ox Tiger Rabbit Dragon Snake Horse)[y%12],%w(Metal Water Wood Fire Earth)[(y-1)/2%5],%w(Yin Yang)[y%2]]*' - '

```

This will work for dates between Feb 5, 1924 and Jan 29, 2044.
> 3 votes

# Answer
## GolfScript (212 chars)

This uses non-printable characters, so here's the output from xxd:

```
0000000: 272d 272f 6e2a 7e5c 2833 312a 2b5c 3a5e  '-'/n*~\(31*+\:^
0000010: 3139 2a22 d4e3 275a 747f 878c 70cb 996d  19*"..'Zt...p..m
0000020: a4f9 19e9 699e d818 bb61 c4e3 2232 3536  ....i....a.."256
0000030: 6261 7365 2033 6261 7365 5e31 3932 322d  base 3base^1922-
0000040: 3c7b 282d 7d2f 3330 2532 312b 3e5e 352d  <{(-}/30%21+>^5-
0000050: 2b3a 5e31 3225 2752 6174 0a4f 780a 5469  +:^12%'Rat.Ox.Ti
0000060: 6765 720a 5261 6262 6974 0a44 7261 676f  ger.Rabbit.Drago
0000070: 6e0a 536e 616b 650a 486f 7273 650a 476f  n.Snake.Horse.Go
0000080: 6174 0a4d 6f6e 6b65 790a 526f 6f73 7465  at.Monkey.Rooste
0000090: 720a 446f 670a 5069 6727 6e2f 3d6e 5e32  r.Dog.Pig'n/=n^2
00000a0: 2f35 2527 576f 6f64 0a46 6972 650a 4561  /5%'Wood.Fire.Ea
00000b0: 7274 680a 4d65 7461 6c0a 5761 7465 7227  rth.Metal.Water'
00000c0: 6e2f 3d6e 5e31 2627 5961 6e67 0a59 696e  n/=n^1&'Yang.Yin
00000d0: 276e 2f3d                                'n/=

```

An equivalent program which uses string escapes and is hence a bit longer is:

```
'-'/n*~\(31*+\:^19*"\xD4\xE3'Zt\x87\x8Cp\xCB\x99m\xA4\xF9\x19\xE9i\x9E\xD8\x18\xBBa\xC4\xE3"256base 3base^1922-<{(-}/30%21+>^5-+:^12%'Rat
Ox
Tiger
Rabbit
Dragon
Snake
Horse
Goat
Monkey
Rooster
Dog
Pig'n/=n^2/5%'Wood
Fire
Earth
Metal
Water'n/=n^1&'Yang
Yin'n/=

```

The interesting part is computing, given the date, whether it is before or after the Chinese New Year which falls in that Gregorian year. Taking inspiration from the Easter calculation algorithm which I've used on a previous question, I looked for a reasonably simple calculation of the New Year date. In the end I've gone with a simple formula which gets me most of the way there, plus a lookup table for the error term.

The simple calculation is `day_of_year = 21 + (19 * year % 30)`. The error term ranges from `0` to `8` over the range of interest (1924 to 2044), and never changes from year to year by more than one, so the lookup table is encoded in balanced ternary and the error is computed by summing the error terms of a prefix of the table.
> 3 votes

# Answer
## C#, 630 611 604 572 570 bytes, 120 years

### (add ~2⅔ bytes per additional year if you know the offset)

This is good for people born 31-Jan-1900 through 24-Jan-2020 and will likely crash outside of that range. Are there bonus points for the number of years covered?

```
string Z(DateTime date)
{
    int[] days = new int[] {  3, 22, 11,  1, 19,  7, -3, 16,  5, -6, 13,  2,
                             21,  9, -2, 17,  6, -5, 14,  4, 23, 11,  0, 19,
                              8, -3, 16,  5, -5, 13,  2, 20,  9, -2, 17,  7,
                             -4, 14,  3, 22, 11, -1, 18,  8, -3, 16,  5, -6,
                             13,  1, 20,  9, -1, 17,  6, -4, 15,  3, 21, 11,
                              0, 18,  8, -3, 16,  5, -7, 12,  2, 20,  9, -1,
                             18,  6, -5, 14,  3, 21, 10,  0, 19,  8, -3, 16,
                              5, 23, 12,  1, 20,  9, -1, 18,  7, -5, 13,  3,
                             22, 10,  0, 19,  8, -4, 15,  4, -6, 12,  1, 21,
                             10, -2, 17,  6, -5, 13,  3, 22, 11,  0, 19,  8 };
    string[] signs = "Rat,Ox,Tiger,Rabbit,Dragon,Snake,Horse,Goat,Monkey,Rooster,Dog,Pig".Split(',');
    string[] elements = "Metal,Water,Wood,Fire,Earth".Split(',');
    string[] polarities = new string[] { "Yang", "Yin" };
    int year = date.Year - 1900;
    int x = year - (date.DayOfYear < days[year] + 28 ? 1 : 0);
    return signs[x % 12] + " - " + elements[x / 2 % 5] + " - " + polarities[x % 2];
}

```

Or condensed (with added line breaks):

```
string Z(DateTime d){
int y=d.Year-1900,
x=y-(d.DayOfYear<new[]{3,22,11,1,19,7,-3,16,5,-6,13,2,21,9,-2,17,6,-5,14,4,23,11,0,19,8,-3,16,5,-5,13,2,20,9,-2,17,7,-4,14,3,22,11,-1,18,8,-3,16,5,-6,13,1,20,9,-1,17,6,-4,15,3,21,11,0,18,8,-3,16,5,-7,12,2,20,9,-1,18,6,-5,14,3,21,10,0,19,8,-3,16,5,23,12,1,20,9,-1,18,7,-5,13,3,22,10,0,19,8,-4,15,4,-6,12,1,21,10,-2,17,6,-5,13,3,22,11,0,19,8}[y]+28?1:0);
return "Rat,Ox,Tiger,Rabbit,Dragon,Snake,Horse,Goat,Monkey,Rooster,Dog,Pig".Split(',')[x%12]+" - "+"Metal,Water,Wood,Fire,Earth".Split(',')[x/2%5]+" - "+new[]{"Yang","Yin"}[x%2];
}

```

One of the tricks was to have the offset table's origin at 28-Jan. This proved to have the lowest character count.

If by chance it is insisted the input is a string, add 22 characters to change the method signature to:

```
string Z(string i){

```

and add the line:

```
var d=DateTime.Parse(i);

```

**EDITS:**

* Put all strings in one array and added offsets to the output selectors.
* Changed the day offset to 28-Jan.
* `string.Split()` Inspiration taken from Eduard Florinescu's answer.
* Inlined all arrays. It only saved me 2 characters. :-/
> 2 votes

---
Tags: code-golf, date
---


title: C code indenter

text:
# Question
Title: C code indenter
Situation: You are a high school teacher, teaching your computing class how to write C programs. However, since it is just the beginning of the term, you haven't taught them about the importance of indentation and spacing. As you are marking their work, your eyes hurt so much you scream in agony, and realise that this can't go on.

Task: You have decided to write a program, in any language, that takes a valid C sourcecode as input and output it nicely formatted. You should decide what is a nicely formatted code, as it is a popularity contest. You are encouraged to implement as many features as you can, the following are some examples:

* Add proper indentation at the front of each line
* Add spaces after `,` and other operators, e.g. converting `int a[]={1,2,3};` to `int a[] = {1, 2, 3};`. Remember not to process operators within string literals though.
* Remove trailing spaces after each line
* Separating statements into several lines, e.g. the student may write `tmp=a;a=b;b=tmp;` or `int f(int n){if(n==1||n==2)return 1;else return f(n-1)+f(n-2);}` all in one line, you can separate them into different lines. Be aware of `for` loops though, they have semicolons in them but I really don't think you should split them up.
* Add a new line after defining each function
* Another other features you can come up with the help you comprehend your students' codes.

Winning criteria: This is a popularity contest, so the answer with most upvotes wins. In case of a tie, the answer with the most features implemented wins. If that is a tie again then shortest code wins.

You are suggested to include in your answer a list of features that you have implemented, as well as a sample input and output.

Edit: As requested in the comments here is a sample input, though keep in mind that it is only for reference and you are recommended to implement as many features as possible.

Input:

```
#include <stdio.h>
#include<string.h>
int main() {
int i;
char s[99];
     printf("----------------------\n;;What is your name?;;\n----------------------\n"); //Semicolon added in the string just to annoy you
             /* Now we take the input: */
    scanf("%s",s);
    for(i=0;i<strlen(s);i++){if(s[i]>='a'&&s[i]<='z'){
        s[i]-=('a'-'A'); //this is same as s[i]=s[i]-'a'+'A'
}}printf("Your name in upper case is:\n%s\n",s);
   return 0;}

```

This is how I would normally format this code: (I'm a lazy person)

```
#include <stdio.h>
#include <string.h>
int main() {
    int i;
    char s[99];
    printf("----------------------\n;;What is your name?;;\n----------------------\n"); //Semicolon added in the string just to annoy you
    /* Now we take the input: */
    scanf("%s",s);
    for(i=0;i<strlen(s);i++) {
        if(s[i]>='a'&&s[i]<='z') {
            s[i]-=('a'-'A'); //this is same as s[i]=s[i]-'a'+'A'
        }
    }
    printf("Your name in upper case is:\n%s\n",s);
    return 0;
}

```

This is how I think is easier to read:

```
#include <stdio.h>
#include <string.h>
int main() {
    int i;
    char s[99];
    printf("----------------------\n;;What is your name?;;\n----------------------\n"); //Semicolon added in the string just to annoy you
    /* Now we take the input: */
    scanf("%s", s);
    for(i = 0; i < strlen(s); i++) {
        if(s[i] >= 'a' && s[i] <= 'z') {
            s[i] -= ('a' - 'A'); //this is same as s[i]=s[i]-'a'+'A'
        }
    }
    printf("Your name in upper case is:\n%s\n", s);
    return 0;
}

```

**Also, now that I start having answers, the answer with the highest vote count will be accepted 5 days after the last answer, i.e. if there are no more new answers within 5 days, this contest will end.**

# Answer
Because we are talking about indentation and whitespaces we just have to write the code in a programming a language that is actually designed around **whitespace**, as that has to be easiest, right?

So the solution is:

```

```

Here it is in base64:

```
ICAgCQogICAgCgkJICAgIAkgCiAgICAKCQkgICAgCQkKICAgIAoJCSAgICAJICAKICAgIAoJCSAgICAJIAkKICAgIAoJCSAKIAogCQoKICAgCSAKICAgCQoJCQkgICAJCQkgCQkKCSAgCQoJICAJICAKICAgCQoJCQkgICAJIAkgCgkgIAkKCSAgCSAJCiAgIAkKCQkJICAgCSAgCQoJICAJCgkgIAkgCQogICAJCgkJCSAgIAkgICAgIAoJICAJCgkgIAkgCQogICAJCgkJCSAgIAkJCQkJIAkKCSAgCQoJICAJCSAKICAgCQoJCQkgICAJICAgCSAKCSAgCQoJICAJICAgIAogICAJCgkJCSAgIAkgCSAgIAoJICAJCgkgIAkgICAJCQogICAJCgkJCSAgIAkgCSAgCQoJICAJCgkgIAkgIAkgIAogICAJIAogICAJCgkJIAogCSAJCQkKICAgCQoJCQkJCiAgCgkKCiAgIAkgIAogICAJCgkJCQkKICAKCQoKICAgCSAJCgoJCgogICAJCSAKICAgCQkKICAgCQkKCQkJICAgCQoJICAJCQkgICAgCSAKICAgCQoJCSAKIAkgCQkJCiAgIAkKCQkJCQogIAoJCgogICAJICAgIAogICAJIAogICAJIAoJCSAKIAkgCQkJCiAgIAkKCQkJCQogIAoJCgogICAJICAgCQkKICAgCSAJCiAgIAkgCQoJCQkgICAJCgkgICAJCSAgICAJIAogICAJCgkJIAogCSAJCQkKICAgCQoJCQkJCiAgCgkKCiAgIAkgIAkgIAogICAJIAkKICAgCSAJCgkJCSAgIAkKCSAgCQkJICAgIAkgCiAgIAkKCQkgCiAJIAkJCQogICAJCgkJCQkKICAKCQoKICAgCQkKICAgCQoJCQkgICAJIAkgCgkgIAkKCSAgCQkgIAogICAJCgkJCSAgIAkJCQkgCQkKCSAgCQoJICAJCSAJCiAgIAkKCQkJICAgCQkJCQkgCQoJICAJCgkgIAkJCSAKICAgCQoJCQkgICAJCQkgCQkKCSAgCQoJICAJCQkJCiAgIAkKCQkJICAgCSAgIAkgCgkgIAkKCSAgCQkgCQkKICAgCQoJCQkgICAJIAkgCSAKCSAgCQoJICAJCQkgIAogICAJCgkJCSAgIAkgCQkJCQoJICAJCgkgIAkJCSAJCiAgIAkKCQkJICAgCSAJICAgCgkgIAkKCSAgCSAgCSAJCiAgIAkKCQkJICAgCSAJICAJCgkgIAkKCSAgCSAgCQkgCiAgIAkKCQkJCQogIAoJCgogICAJCSAgCiAgIAkgCiAgICAKCQkgCgkKCiAgIAkJIAkKICAgCQoJCQkJCiAgICAgCSAKICAgIAoJCSAgICAJCQogICAJCQoJCQkgICAJCgkgICAJCSAKCQoKICAgCQkJIAogICAJCQogICAJCQoJCQkgICAJCgkgIAkJCSAKIAkgCQkJCiAgIAkKCQkJCQogICAgIAkgCiAgICAKCQkgCgkKCiAgIAkJCQkKICAgCQoJCQkJCiAgICAgCSAJCgkJCQoJICAJIAkgCgoJCgogICAJICAJCQkKICAgCSAKICAgIAoJCSAKCQoKICAgCQkgCQkKICAgCQoJCQkJCiAgICAgCSAKICAgCSAKCQkgCgkKCiAgIAkJCSAgCiAgIAkgIAoJCQkgICAJIAkJCQkKCSAgCQoJICAJCQkJIAogICAJCgkJCQkKICAKCQoKICAgCQkJIAkKICAgCSAgCgkJCSAgIAkgCQkJCQoJICAJCgkgIAkJCQkJCiAgIAkKCQkJCQogIAoJCgogICAJCQkJIAogICAJCgkJCQkKICAgICAJIAogICAJCQoJCSAKCQoKICAgCQkJCQkKICAgCQoJCQkJCiAgICAgCSAKICAgCSAgCgkJIAoJCgogICAJICAJIAkKICAgCSAJCiAgIAkgCQoJCQkgICAJCgkgICAJCSAgICAJCgkJCQkKICAKCQoKICAgCSAgCQkgCiAgIAkgCQogICAJIAkKCQkJICAgCQoJICAJCQkgICAgCQoJCQkJCiAgCgkKCiAgIAkJCQogICAJIAkgCgkKICAgICAJCQoJCQkKICAgCSAgCQogCiAKCSAgCSAgIAogCiAKCQkgCSAgIAogICAJICAgICAKCQogICAgIAkgICAgIAoJCiAgICAgCQoJICAJCiAKIAkgIAkKCiAgIAkgICAKCgkKCiAgIAkgCSAJCiAgIAkKCQkJICAgCSAJIAoJICAJCgkgIAkJICAgCiAgIAkKCQkJICAgCSAgIAkgCgkgIAkKCSAgCQkgIAkKICAgCQoJCQkJCiAgCgkKCiAgIAkJICAgCiAgIAkgCiAgICAKCQkgCgkKCiAgIAkJICAJCiAgIAkgIAoJCQkgICAJIAkJCSAgCgkgIAkKCSAgCQkgCSAKICAgCSAKICAgCQoJCSAgICAJCgkJCQkKICAKCQoKICAgCQkgCSAKICAgCQoJCQkJCiAgCgkKCiAgIAkgCQkgCiAgIAkKCQkJICAgCSAJCQkJCgkgIAkKCSAgCSAgICAgCiAgIAkKCQkJCQogIAoJCgogICAJICAgICAKICAgCSAgCgkJCSAgIAkgCSAJIAoJICAJCgkgIAkgICAgCQogICAJCgkJCQkKICAKCQoKICAgCSAgICAJCiAgIAkKCQkJCQogICAgIAkgCiAgIAkKCQkgCgkKCiAgIAkgCQkJCiAgIAkKCQkJICAgCSAJIAoJICAJCgkgIAkgICAJIAogICAJCgkJCQkKICAKCQoKICAgCSAgIAkgCiAgIAkgCiAgICAKCQkgCgkKCiAgIAkKICAgCSAgCiAgIAkKCQkJCQkgICAgCQoJCgkgICAgCSAKCQkJCgkgIAkgCSAKICAgCSAKCQkJICAgCQoJICAJCgkgIAkgICAJCiAgIAkgCgkJCSAgIAkgCgkgIAkKCSAgCSAgCSAKICAgCSAKCQkJICAgCQkKCSAgCQoJICAJICAJCQogICAJIAoJCQkgICAJICAKCSAgCQoJICAJIAkgIAoKICAgCSAgIAkKCiAJIAkJCgogCiAJIAkJCgogICAJIAkgCgogCSAJIAoKIAogCSAJCQoKICAgCSAgCSAKCiAJIAkgCSAJCgogCiAJIAkJCgogICAJICAJCQoKIAkgCSAJCSAKCiAKIAkgCQkKCiAgIAkgCSAgCgogCSAJIAkJCQoKICAgCSAJCQoKIAogCQoKCgo=

```

For those who have issues printing out the code on a paper here is the annotated version (you can find a compiler for this at the end of the answer):

```
# heap structure:
# 1: read buffer
# 2: parser state
#   0: before indentation
#   1: after indentation
#   2: inside a string literal
#   3: inside a multiline comment
#   4: inside a single line comment
# 3: identation
# 4: old read buffer
# 5: parenthesis nesting amount

# -------------------
# initialize heap
# -------------------
SS 1 | SS 0 | TTS # [1] := 0
SS 2 | SS 0 | TTS # [2] := 0
SS 3 | SS 0 | TTS # [3] := 0
SS 4 | SS 0 | TTS # [4] := 0
SS 5 | SS 0 | TTS # [5] := 0
LSL 1 # goto L1

# -------------------
# sub: determine what to do in state 0
# -------------------
LSS 2 # LABEL L2
SS 1 | TTT | SS  59 | TSST | LTS 4 # if [1] == ; GOTO L4
SS 1 | TTT | SS  10 | TSST | LTS 5 # if [1] == \n GOTO L5
SS 1 | TTT | SS   9 | TSST | LTS 5 # if [1] == \t GOTO L5
SS 1 | TTT | SS  32 | TSST | LTS 5 # if [1] == ' ' GOTO L5
SS 1 | TTT | SS 125 | TSST | LTS 6 # if [1] == } GOTO L6
SS 1 | TTT | SS  34 | TSST | LTS 16 # if [1] == " GOTO L16
SS 1 | TTT | SS  40 | TSST | LTS 35 # if [1] == ( GOTO L35
SS 1 | TTT | SS  41 | TSST | LTS 36 # if [1] == ) GOTO L36

SS 2 | SS 1 | TTS # [2] := 1
LST 7 # call L7
SS 1 | TTT | TLSS # print [1]
LTL # return

LSS 4 # label L4 - ; handler
SS 1 | TTT | TLSS # print [1]
LTL # return

LSS 5 # label L5 - WS handler
LTL # return

LSS 6 # label L6 - } handler
# decrease identation by one
SS 3 | SS 3 | TTT | SS 1 | TSST | TTS # [3] := [3] - 1
SS 2 | SS 1 | TTS # [2] := 1
LST 7 # call L7
SS 1 | TTT | TLSS # print [1]
LTL # return

LSS 16 # label L16 - " handler
SS2 | SS 2 | TTS # [2] := 2
LST 7 # call L7
SS1 | TTT | TLSS # print [1]
LTL

LSS 35
SS 5 | SS 5 | TTT | SS 1 | TSSS | TTS # [5] := [5] + 1
SS 2 | SS 1 | TTS # [2] := 1
LST 7 # call L7
SS1 | TTT | TLSS # print [1]
LTL

LSS 36
SS 5 | SS 5 | TTT | SS 1 | TSST | TTS # [5] := [5] - 1
SS 2 | SS 1 | TTS # [2] := 1
LST 7 # call L7
SS1 | TTT | TLSS # print [1]
LTL

# -------------------
# sub: determine what to do in state 1
# -------------------
LSS 3 # LABEL L3
SS 1 | TTT | SS  10 | TSST | LTS 12 # if [1] == \n GOTO L12
SS 1 | TTT | SS 123 | TSST | LTS 13 # if [1] == { GOTO L13
SS 1 | TTT | SS 125 | TSST | LTS 14 # if [1] == } GOTO L14
SS 1 | TTT | SS  59 | TSST | LTS 15 # if [1] == ; GOTO L15
SS 1 | TTT | SS  34 | TSST | LTS 27 # if [1] == " GOTO L27
SS 1 | TTT | SS  42 | TSST | LTS 28 # if [1] == * GOTO L28
SS 1 | TTT | SS  47 | TSST | LTS 29 # if [1] == / GOTO L29
SS 1 | TTT | SS  40 | TSST | LTS 37 # if [1] == ( GOTO L37
SS 1 | TTT | SS  41 | TSST | LTS 38 # if [1] == ) GOTO L38
SS 1 | TTT | TLSS # print [1]
LTL # return

LSS 12 # LABEL L12 - \n handler
SS 2 | SS 0 | TTS # [2] := 0
LTL # return

LSS 13 # LABEL L13 - { handler
SS 1 | TTT | TLSS # print [1]
SS 2 | SS 0 | TTS # [2] := 0
SS 3 | SS 3 | TTT | SS 1 | TSSS | TTS # [3] := [3] + 1
LTL # return

LSS 14 # LABEL L14 - } handler
SS 3 | SS 3 | TTT | SS 1 | TSST | TTS # [3] := [3] - 1
LST 7 # call L7
SS 1 | TTT | TLSS # print [1]
SS 2 | SS 0 | TTS # [2] := 0
LTL # return

LSS 15 # LABEL L15 - ; handler
SS 1 | TTT | TLSS # print [1]
SS 5 | TTT | LTS 10 # if [5] == 0 GOTO L39
LTL

LSS 39
SS 2 | SS 0 | TTS # [2] := 0
LTL # return

LSS 27 # label L27 - " handler
SS1 | TTT | TLSS # print [1]
SS2 | SS 2 | TTS # [2] := 2
LTL

LSS 28 # label L28 - * handler - this might start a comment
SS 4 | TTT | SS  47 | TSST | LTS 30 # if [4] == / GOTO L30
SS1 | TTT | TLSS # print [1]
LTL

LSS 29 # label L29 - / handler - this might start a comment
SS 4 | TTT | SS  47 | TSST | LTS 31 # if [4] == / GOTO L31
SS1 | TTT | TLSS # print [1]
LTL

LSS 30 # label L30 - /* handler
SS1 | TTT | TLSS # print [1]
SS2 | SS 3 | TTS # [2] := 3
LTL

LSS 31 # label L31 - // handler
SS1 | TTT | TLSS # print [1]
SS2 | SS 4 | TTS # [2] := 4
LTL

LSS 37
SS 5 | SS 5 | TTT | SS 1 | TSSS | TTS # [5] := [5] + 1
SS1 | TTT | TLSS # print [1]
LTL

LSS 38
SS 5 | SS 5 | TTT | SS 1 | TSST | TTS # [5] := [5] - 1
SS1 | TTT | TLSS # print [1]
LTL

# -------------------
# sub: print identation
# -------------------
LSS 7 # label L7 - print identation
SS 10 | TLSS # print \n
SS 3 | TTT # push [3]
LSS 9 # label L9 - start loop
SLS | LTS 8 # if [3] == 0 GOTO L8
SLS | LTT 8 # if [3] < 0 GOTO L8 - for safety
SS 32 | TLSS # print ' '
SS 32 | TLSS # print ' '
SS 1  | TSST # i := i - 1
LSL 9 # GOTO L9
LSS 8 # label L8 - end loop
LTL #

# -------------------
# sub: L21 - string literal handler
# -------------------
LSS 21
SS 1 | TTT | SS  10 | TSST | LTS 24 # if [1] == \n GOTO L24
SS 1 | TTT | SS  34 | TSST | LTS 25 # if [1] == " GOTO L25
SS 1 | TTT | TLSS # print [1]
LTL

LSS 24 # \n handler - this should never happen, but let's be prepared and reset the parser
SS 2 | SS 0 | TTS # [2] := 0
LTL # return

LSS 25 # " handler - this might be escaped, so be prepared
SS 4 | TTT | SS  92 | TSST | LTS 26 # if [4] == \ GOTO L26
SS 2 | SS 1 | TTS # [2] := 1
SS 1 | TTT | TLSS # print [1]
LTL

LSS 26 # \\" handler - escaped quotes don't finish the literal
SS 1 | TTT | TLSS # print [1]
LTL

# -------------------
# sub: L22 - multiline comment handler
# -------------------
LSS 22
SS 1 | TTT | SS  47 | TSST | LTS 32 # if [1] == / GOTO L32
SS 1 | TTT | TLSS # print [1]
LTL

LSS 32
SS 4 | TTT | SS  42 | TSST | LTS 33 # if [4] == * GOTO L33
SS 1 | TTT | TLSS # print [1]
LTL

LSS 33
SS 1 | TTT | TLSS # print [1]
SS 2 | SS 1 | TTS # [2] := 1
LTL
# -------------------
# sub: L23 - singleline comment handler
# -------------------
LSS 23
SS 1 | TTT | SS  10 | TSST | LTS 34 # if [1] == \n GOTO L34
SS 1 | TTT | TLSS # print [1]
LTL

LSS 34
SS 2 | SS 0 | TTS # [2] := 0
LTL

# -------------------
# main loop
# -------------------
LSS 1 # LABEL L1
SS 4 | SS 1 | TTT | TTS # [4] := [1]
SS 1 | TLTS # [1] := read

SS 2 | TTT | LTS 10 # if [2] == 0 GOTO L10
SS 2 | TTT | SS 1 | TSST | LTS 17 # if [2] == 1 GOTO L17
SS 2 | TTT | SS 2 | TSST | LTS 18 # if [2] == 2 GOTO L18
SS 2 | TTT | SS 3 | TSST | LTS 19 # if [2] == 3 GOTO L19
SS 2 | TTT | SS 4 | TSST | LTS 20 # if [2] == 4 GOTO L20

LSS 17
LST 3  # call L3
LSL 11 # GOTO L11

LSS 10 # label L10
LST 2  # call L2
LSL 11

LSS 18
LST 21
LSL 11

LSS 19
LST 22
LSL 11

LSS 20
LST 23

LSS 11 # label L11
LSL 1  # goto L1
LLL # END

```

This is still work in progress, although hopefully it should pass most of the criterias!

Currently supported features:

* fix identation based on the `{` and `}` characters.
* add a newline after `;`
* handle indentation characters inside string literals (including the fact that string literals are not closed when encountering a `\"`)
* handle indentation characters inside single and multiline comments
* doesn't add newline characters if inside parentheses (like a `for` block)

Example input (I added some edge cases based Quincunx's comment, so you can check that it behaves properly):

```
    /* Hai Worldz. This code is to prevent formatting: if(this_code_is_touched){,then+your*program_"doesn't({work)}correctl"y.} */
#include<stdio.h>
#include<string.h>
int main() {
int i;
char s[99];
     printf("----------------------\n;;What is your name?;;\n----------------------\n\""); //Semicolon added in the {;} string just to annoy you
             /* Now we take the {;} input: */
    scanf("%s",s);
    for(i=0;i<strlen(s);i++){if(s[i]>='a'&&s[i]<='z'){
        s[i]-=('a'-'A'); //this is same as s[i]=s[i]-'a'+'A'
}}printf("Your \"name\" in upper case is:\n%s\n",s);
   return 0;}

```

Example output:

```
[~/projects/indent]$ cat example.c | ./wspace indent.ws 2>/dev/null

/* Hai Worldz. This code is to prevent formatting: if(this_code_is_touched){,then+your*program_"doesn't({work)}correctl"y.} */
#include<stdio.h>
#include<string.h>
int main() {
  int i;;
  char s[99];;
  printf("----------------------\n;;What is your name?;;\n----------------------\n\"");; //Semicolon added in the {;} string just to annoy you
  /* Now we take the {;} input: */
  scanf("%s",s);;
  for(i=0;i<strlen(s);i++){
    if(s[i]>='a'&&s[i]<='z'){
      s[i]-=('a'-'A');; //this is same as s[i]=s[i]-'a'+'A'
    }
  }
  printf("Your \"name\" in upper case is:\n%s\n",s);;
  return 0;;
}

```

Note, that because whitespace doesn't support EOF checking the intepreter throws an exception, which we need to suppress. As there is no way in whitespace to check for EOF (as far as I know as this is my first whitespace program) this is something unavoidable, I hope the solution still counts.

This is the script I used to compile the annotated version into proper whitespace:

```
#!/usr/bin/env ruby
ARGF.each_line do |line|
  data = line.gsub(/'.'/) { |match| match[1].ord }
  data = data.gsub(/[^-LST0-9#]/,'').split('#').first
  if data
    data.tr!('LST',"\n \t")
    data.gsub!(/[-0-9]+/){|m| "#{m.to_i<0?"\t":" "}#{m.to_i.abs.to_s(2).tr('01'," \t")}\n" }
    print data
  end
end

```

To run:

```
./wscompiler.rb annotated.ws > indent.ws

```

Note that this, apart from converting the `S`, `L` and `T` characters, also allow single line comments with `#`, and can automatically convert numbers and simple character literals into their whitespace representation. Feel free to use it for other whitespace projects if you want
> 22 votes

# Answer
**Vim** the easy way, technically using only one character: `=`

I am not a vim guru, but I do never underestimate it's power and some consider it as a programming language. For me this solution is a winner anyway.

Open the file in vim:

```
vim file.c

```

Within vim press the following keys

`g``g``=``G`

Explanation:

`g``g` goes to the top of the file

`=` is a command to fix the indentation

`G` tells it to perform the operation to the end of the file.

You can save and quit with `:``w``q`

It is possible to let `vim` run command from the command-line, so this can also be done in a one-liner, but I leave that to people who know `vim` better than I do.

---

**Vim example** a valid input file (fibonacci.c) with bad indent.

```
/* Fibonacci Series c language */
#include<stdio.h>

int main()
{
int n, first = 0, second = 1, next, c;

            printf("Enter the number of terms\n");
scanf("%d",&n);
  printf("First %d terms of Fibonacci series are :-\n",n);

          for ( c = 0 ; c < n ; c++ )
   {
if ( c <= 1 )
         next = c;
 else
                                     {
next = first +    second;
              first = second;
        second = next;
      }
      printf("%d\n",next);
   }
 return 0;
}

```

Open in vim: `vim fibonacci.c` press `g``g``=``G`

```
/* Fibonacci Series c language */
#include<stdio.h>

int main()
{
  int n, first = 0, second = 1, next, c;

  printf("Enter the number of terms\n");
  scanf("%d",&n);
  printf("First %d terms of Fibonacci series are :-\n",n);

  for ( c = 0 ; c < n ; c++ )
  {
    if ( c <= 1 )
      next = c;
    else
    {
      next = first +    second;
      first = second;
      second = next;
    }
    printf("%d\n",next);
  }
  return 0;
}

```
> 10 votes

# Answer
Since this will be used to help the teacher understand the student's code better it is important to sanitize the input first. Pre-processor directives are unneeeded, as they just intruduce clutter, and macros can also introduce malicious code into the file. We don't want that! Also, it is completely unnecessary to retain the original comments the student wrote, as they are probably completely useless anyway.

Instead, as everyone knows good code needs good comments, apart from fixing the indentation, and the structure, why not add some highly useful comments around main points of the code to make the result even more understandable! This will definitely help the teacher in assessing the work the student has done!

So from this:

```
    /* Hai Worldz. This code is to prevent formatting: if(this_code_is_touched){,then+your*program_"doesn't({work)}correctl"y.} */
#include<stdio.h>
#include<string.h>
int main() {
int i;
char s[99];
     printf("----------------------\n;;What is your name?;;\n----------------------\n\""); //Semicolon added in the {;} string just to annoy you
             /* Now we take the {;} input: */
    scanf("%s",s);
    for(i=0;i<strlen(s);i++){if(s[i]>='a'&&s[i]<='z'){
        s[i]-=('a'-'A'); //this is same as s[i]=s[i]-'a'+'A'
}}printf("Your \"name\" in upper case is:\n%s\n",s);
   return 0;}

```

Let's produce this:

```
int main() {
    /* This will declare i. */
    int i;
    /* This will declare s[99]. */
    char s[99];
    /* This will call the function called printf with 1 parameters */
    printf("----------------------\n;;What is your name?;;\n----------------------\n\"");
    /* This will call the function called scanf with 2 parameters */
    scanf("%s", s);
    /* This will start a for loop, with initializator i = 0. It will loop until i < strlen(s), and will i++ at each iteration */
    for (i = 0; i < strlen(s); i++) {
        /* This will check, whether s[i] >= 'a' && s[i] <= 'z' is true or not. */
        if (s[i] >= 'a' && s[i] <= 'z') {
            s[i] -= 'a' - 'A';
        }
    }
    /* This will call the function called printf with 2 parameters */
    printf("Your \"name\" in upper case is:\n%s\n", s);
    /* This will return from the function. */
    return 0;
}

```

Isn't it much better, with all of the useful comments around the expressions?

---

So this is a **ruby** solution utilizing the `cast` gem, which is a C parser<sub>(Yes, I'm cheating)</sub>. As this will parse the code, and re-print it from scratch it means the result will be perfectly indented and also consistent, e.g.:

* Proper indentation across the code based on block level
* Consistent whitespacing around expressions, statements, conditions, etc.
* Complete re-indenting based on the structure of the code
* etc.

And also it will contain highly useful comments about how the code works, which will super useful for both the students and the teacher!

`indent.rb`

```
#!/usr/bin/env ruby
require 'cast'

code = ''
ARGF.each_line do |line|
  if line=~/\A#/
    code << "// #{line.strip}\n"
  else
    code << line
  end
end

class Comment < C::Literal
  field :val
  initializer :val
  def to_s
    "/* #{val} */"
  end
end

tree = C.parse(code)
tree.preorder do |n|
  break if n.kind_of?(Comment)
  if n.kind_of?(C::Declaration)
    dd = []
    n.declarators.each do |d|
      dd << "declare #{d.indirect_type ? d.indirect_type.to_s(d.name) : d.name}"
      dd.last << " and set it to #{d.init}" if d.init
    end
    unless dd.empty?
      n.insert_prev(Comment.new("This will #{dd.join(", ")}."))
    end
  end rescue nil
  n.parent.insert_prev(Comment.new("This will call the function called #{n.expr} with #{n.args.length} parameters")) if n.kind_of?(C::Call) rescue nil
  n.insert_prev(Comment.new("This will start a for loop, with initializator #{n.init}. It will loop until #{n.cond}, and will #{n.iter} at each iteration")) if n.kind_of?(C::For) rescue nil
  n.insert_prev(Comment.new("This will check, whether #{n.cond} is true or not.")) if n.kind_of?(C::If) rescue nil
  n.insert_prev(Comment.new("This will return from the function.")) if n.kind_of?(C::Return) rescue nil
end

puts tree

```

`Gemfile`

```
source "http://rubygems.org"
gem 'cast', '0.2.1'

```
> 8 votes

# Answer
# Bash, 35 characters

Input file must be named "input.c" and placed in the current working directory.

```
sh <(wget -q -O- http://x.co/3snpk)

```

Example output, having been fed the input in the original question:

It may take a few seconds to run depending on your hardware, so be patient :)
> 5 votes

# Answer
This is written in python and based on the GNU Coding Standards.

# Features so far:

* Indenting blocks
* Splitting lines (may split things that shouldn't be)
* GNU-style function definitions

Code:

```
import sys

file_in = sys.argv[1]

# Functions, for, if, while, and switch statements
def func_def(string):
    ret = ["", "", ""]
    func_name = ""
    paren_level = -1
    consume_id = False

    for x in string[::-1]:
        if x == "{":
            ret[2] = "{"
        elif ret[1] == "":
            if x == "(":
                paren_level -= 1
                func_name += x
            elif x == ")":
                paren_level += 1
                func_name += x
            elif paren_level == -1 and x.isspace():
                if consume_id:
                    ret[1] = func_name[::-1]
            elif paren_level == -1:
                consume_id = True
                func_name += x
            else:
                func_name += x
        else:
            # Return Type
            ret[0] += x
    else:
        ret[1] = func_name[::-1]

    ret[0] = ret[0][::-1]

    # Handle the case in which this is just a statement
    if ret[1].split("(")[0].strip() in ["for", "if", "while", "switch"]:
        ret = [ret[1], ret[2]] # Don't print an extra line

    return ret

with open(file_in) as file_obj_in:
    line_len = 0
    buffer = ""
    in_str = False
    no_newline = False
    indent_level = 0
    tab = " " * 4
    no_tab = False
    brace_stack = [-1]

    while True:
        buffer += file_obj_in.read(1)
        if buffer == "":
            break
        elif "\n" in buffer:
            if not no_newline:
                print(("" if no_tab else indent_level * tab) + buffer, end="")
                buffer = ""
                line_len = indent_level * 4
                no_tab = False
                continue
            else:
                buffer = ""
                line_len = indent_level * 4
                no_newline = False
                continue
        elif buffer[-1] == '"':
            in_str = not in_str
        elif buffer.isspace():
            buffer = ""
            continue

        if "){" in "".join(buffer.split()) and not in_str:
            for x in func_def(buffer):
                print(indent_level * tab + x)
            buffer = ""
            line_len = indent_level * 4
            no_newline = True
            indent_level += 1
            brace_stack[0] += 1
            brace_stack.append((brace_stack[0], True))
            continue
        elif buffer[-1] == "}" and not in_str:
            brace_stack[0] -= 1
            if brace_stack[-1][1]: # If we must print newline and indent
                if not buffer == "}":
                    print(indent_level * tab + buffer[:-1].rstrip("\n"))
                indent_level -= 1
                print(indent_level * tab + "}")
                buffer = ""
                line_len = indent_level * 4
            else:
                pass
            brace_stack.pop()
        line_len += 1

        if line_len == 79 and not in_str:
            print(indent_level * tab + buffer)
            buffer = ""
            line_len = indent_level * 4
            continue
        elif line_len == 78 and in_str:
            print(indent_level * tab + buffer + "\\")
            buffer = ""
            line_len = indent_level * 4
            no_tab = True
            continue

```

Example input (pass a filename as argument):

```
#include <stdio.h>
#include<string.h>
int main() {
int i;
char s[99];
     printf("----------------------\n;;What is your name?;;\n----------------------\n"); //Semicolon added in the string just to annoy you
             /* Now we take the input: */
    scanf("%s",s);
    for(i=0;i<strlen(s);i++){if(s[i]>='a'&&s[i]<='z'){
        s[i]-=('a'-'A'); //this is same as s[i]=s[i]-'a'+'A'
}}printf("Your name in upper case is:\n%s\n",s);
   return 0;}

```

Example output:

```
#include <stdio.h>
#include<string.h>
int
main()
{
    int i;
    char s[99];
    printf("----------------------\n;;What is your name?;;\n------------------\
----\n"); //Semicolon added in the string just to annoy you
    /* Now we take the input: */
    scanf("%s",s);
    for(i=0;i<strlen(s);i++)
    {
        if(s[i]>='a'&&s[i]<='z')
        {
            s[i]-=('a'-'A'); //this is same as s[i]=s[i]-'a'+'A'
        }
    }
    printf("Your name in upper case is:\n%s\n",s);
    return 0;
}

```

This **will** have bugs.
> 4 votes

# Answer
# Ruby

```
code = DATA.read

# first, we need to replace strings and comments with tilde escapes to avoid parsing them
code.gsub! '~', '~T'
lineComments = []
code.gsub!(/\/\/.*$/) { lineComments.push $&; '~L' }
multilineComments = []
code.gsub!(/\/\*.*?\*\//m) { multilineComments.push $&; '~M' }
strs = []
code.gsub!(/"(\\.|[^"])*"|'.'/) { strs.push $&; '~S' } # character literals are considered strings

# also, chop out preprocessor stuffs
preprocessor = ''
code.gsub!(/(^#.*\n)+/) { preprocessor = $&; '' }

# clean up newlines and excess whitespace
code.gsub! "\n", ' '
code.gsub! /\s+/, ' '
code.gsub!(/[;{}]/) { "#{$&}\n" }
code.gsub!(/[}]/) { "\n#{$&}" }
code.gsub! /^\s*/, ''
code.gsub! /\s+$/, ''

# fix for loops (with semicolons)
code.gsub!(/^for.*\n.*\n.*/) { $&.gsub ";\n", '; ' }

# now it's time for indenting; add indent according to {}
indentedCode = ''
code.each_line { |l|
    indentedCode += ('    ' * [indentedCode.count('{') - indentedCode.count('}') - (l =~ /^\}/ ? 1 : 0), 0].max) + l
}
code = indentedCode

# finally we're adding whitespace for more readability. first get a list of all operators
opsWithEq = '= + - * / % ! > < & | ^ >> <<'
opsNoEq = '++ -- && ||'
ops = opsWithEq.split + opsWithEq.split.map{|o| o + '=' } + opsNoEq.split
ops = ops.sort_by(&:length).reverse
# now whitespace-ize them
code.gsub!(/(.)(#{ops.map{|o| Regexp.escape o }.join '|'})(.)/m) { "#{$1 == ' ' ? ' ' : ($1 + ' ')}#{$2}#{$3 == ' ' ? ' ' : (' ' + $3)}" }

# special-cases: only add whitespace to the right
ops = ','.split
code.gsub!(/(#{ops.map{|o| Regexp.escape o }.join '|'})(.)/m) { "#{$1}#{$2 == ' ' ? ' ' : (' ' + $2)}" }
# special-cases: only add whitespace to the left
ops = '{'.split
code.gsub!(/(.)(#{ops.map{|o| Regexp.escape o }.join '|'})/m) { "#{$1 == ' ' ? ' ' : ($1 + ' ')}#{$2}" }

# replace the tilde escapes and preprocessor stuffs
stri = lci = mci = -1
code.gsub!(/~(.)/) {
    case $1
    when 'T'
        '~'
    when 'S'
        strs[stri += 1]
    when 'L'
        lineComments[lci += 1] + "\n#{code[0, $~.begin(0)].split("\n").last}"
    when 'M'
        multilineComments[mci += 1]
    end
}
code = (preprocessor + "\n" + code).gsub /^ +\n/, ''

puts code
__END__
    /* Hai Worldz. This code is to prevent formatting: if(this_code_is_touched){,then+your*program_"doesn't({work)}correctl"y.} */
#include<stdio.h>
#include<string.h>
int main() {
int i;
char s[99];
     printf("----------------------\n;;What is your name?;;\n----------------------\n\""); //Semicolon added in the {;} string just to annoy you
             /* Now we take the {;} input: */
    scanf("%s",s);
    for(i=0;i<strlen(s);i++){if(s[i]>='a'&&s[i]<='z'){
        s[i]-=('a'-'A'); //this is same as s[i]=s[i]-'a'+'A'
}}printf("Your \"name\" in upper case is:\n%s\n",s);
   return 0;}

```

**Output:**

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

int main() {
    int i;
    char s[99];
    printf("----------------------\n;;What is your name?;;\n----------------------\n");
    //Semicolon added in the string just to annoy you
     /* Now we take the input: */ scanf("%s", s);
    for(i = 0; i < strlen(s); i ++ ) {
        if(s[i] >= 'a' && s[i] <= 'z') {
            s[i] -= ('a' - 'A');
            //this is same as s[i]=s[i]-'a'+'A'
        }
    }
    printf("Your name in upper case is:\n%s\n", s);
    return 0;
}

```

**Output** for @SztupY's edge case input:

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

/* Hai Worldz. This code is to prevent formatting: if(this_code_is_touched){,then+your*program_"doesn't({work)}correctl"y.} */ int main() {
    int i;
    char s[99];
    printf("----------------------\n;;What is your name?;;\n----------------------\n\"");
    //Semicolon added in the {;} string just to annoy you
     /* Now we take the {;} input: */ scanf("%s", s);
    for(i = 0; i < strlen(s); i ++ ) {
        if(s[i] >= 'a' && s[i] <= 'z') {
            s[i] -= ('a' - 'A');
            //this is same as s[i]=s[i]-'a'+'A'
        }
    }
    printf("Your \"name\" in upper case is:\n%s\n", s);
    return 0;
}

```

Features so far:

* **`[x]`** Add proper indentation at the front of each line
* **`[x]`** Add spaces after `,` and other operators, e.g. converting `int a[]={1,2,3};` to `int a[] = {1, 2, 3};`. Remember not to process operators within string literals though.
* **`[x]`** Remove trailing spaces after each line
* **`[x]`** Separating statements into several lines, e.g. the student may write `tmp=a;a=b;b=tmp;` or `int f(int n){if(n==1||n==2)return 1;else return f(n-1)+f(n-2);}` all in one line, you can separate them into different lines. Be aware of `for` loops though, they have semicolons in them but I really don't think you should split them up.
* **`[ ]`** Add a new line after defining each function
* **`[ ]`** Another other features you can come up with the help you comprehend your students' codes.
> 3 votes

# Answer
# .Net

Open that file using Visual Studio

### Input:

```
#include<stdio.h>
#include<string.h>
int main() {
int i;
char s[99];
     printf("----------------------\n;;What is your name?;;\n----------------------\n\""); //Semicolon added in the {;} string just to annoy you
             /* Now we take the {;} input: */
    scanf("%s",s);
    for(i=0;i<strlen(s);i++){if(s[i]>='a'&&s[i]<='z'){
            s[i]-=('a'-'A'); //this is same as s[i]=s[i]-'a'+'A'
    }
}printf("Your \"name\" in upper case is:\n%s\n",s);
       return 0;}

```

### Output:
> 0 votes

---
Tags: popularity-contest, c, whitespace
---


title: Loophole for other challenge

text:
# Question
Title: Loophole for other challenge
You are to post an answer you posted that exploited a loophole in the challengers question. Bonus points if it caused them to rewrite the question.

For example, one challenge was to write a program that such that if a random character is removed, it still works, and your score is how many characters it fails on. Some one posted the empty program, since then it would fail on no characters (though the compiler would fail) and the question had to be changed. He was unrightly down-voted, so I hope he sees this challenge.

This is a popularity contest, so whoever gets the most votes wins!

# Answer
> 30 votes
In my answer to Loophole for other challenge, I deliberately exploit the fact that the poster didn't specify that the answer had to be responding to another question. This made my answer recursive and self-referential.

I also golfed my answer (even though it was a popularity contest). 0 bytes of code.

# Answer
> 8 votes
Render a version of the BBC Micro owl logo

I used curl to grab the challenge page and outputted an answer posted by someone else.

# Answer
> 6 votes
In Weirdest way to produce a stack overflow, i submitted an answer that opened a web browser and displayed stackoverflow.com.

# Answer
> 5 votes
In Shortest Program to Sort a List of numbers into Odd and Even Category, the question clearly states:

> ... The Size of the program is the size of the body of the function, i.e. excluding the size of the function signature.

I thought, "Why such a bizarre and specific rule?" And as I was trying to golf down my initial submission, it dawned on me--default parameter values! According to the language spec, they're definitively not part of the function body, so I went ahead and submitted my final solution: a function whose body is a single character. That *must* have been what the OP wanted!... right?...

Needless to say, it did not win. :/

After accepting another answer, the challenger did eventually add a footnote as to why the one-character solution wasn't considered. The rules of the challenge, however, still remain unchanged (as of the time of this post). So, in the strictest interpretation of the rules, who would *you* say actually won? ;\]

# Answer
> 3 votes
In Write a hash function for Morse Code, the OP didn't specifically exclude negative or floating point values which are entirely usable as hashes. Using this loophole, I was able to get a better than "perfect" score of 236. There was much griping, but the OP never changed the question, despite promising to, and the loophole was subsequently exploited by almost every other poster!

# Answer
> 2 votes
In the question https://codegolf.stackexchange.com/questions/21391/output-with-1-on-stdout-using-a-0-byte-source-code, it states that it will give a bonus of -500 bytes if we output '1' to the console using a source-code file which is 0 bytes long.

My answer is this one and 'abuses' the null devices in windows and linux.

The question wasn't rewritten, but this answer gave me a pretty big hole to go to the gold (the -500 byte bonus). Why? Because the null devices have ALWAYS 0 bytes in size and are guaranteed to exist!

# Answer
> 1 votes
Quoting this question:

> Your goal is to add two input numbers without using any of the following math operators: +,-,\*,/.
>
> Additionally, you can't use any built-in functions that are designed to replace those math operators.

I posted this answer, it was not very popular though. Quoting from my answer:

> And, as suggested by @Ismael Miguel (althought he was not exactly suggesting this), by really abusing the rules underspecification, we can note that only +, -, * and / operators were forbidden, but += was not, so it is allowed (it is not a built-in function either, since it is not even a function). This way, we can express the instruction with just 4 characters (and it will always work with negatives and non-integers too for both values):

```
y+=x

```

# Answer
> 0 votes
In the same question that @Victor refered (Add without addition (or any of the 4 basic arithmetic operators)), i gave this asnwer.

Basicly it "ABUSES" the Javascript internal casting to integer of the boolean values.

---

And This question itself exploits a loophole: there is NOTHING saying we can't refer to the same question in the answers. Or the number of answers. Or the number of answers from the same question.

---
Tags: popularity-contest, underhanded
---