title: Squish-unsquish ligatures

text:
# Question
Title: Squish-unsquish ligatures
Here is a list of some common ligatures in Unicode (the ones I could create with my Compose key on Debian):

```
Orig  Ascii  Lig
ae    [ae]   æ
AE    [AE]   Æ
oe    [oe]   œ
OE    [OE]   Œ
ij    [ij]   ĳ
IJ    [IJ]   Ĳ
ff    [ff]   ﬀ
fi    [fi]   ﬁ
fl    [fl]   ﬂ
ffi   [ffi]  ﬃ
ffl   [ffl]  ﬄ

```

You have two options in this challenge: use the actual UTF-8 ligatures, or use the ASCII-only variant. If you use the actual UTF-8 ligature variants, you gain a 20% bonus. If you use the ASCII-only variant, you may assume square brackets will never be involved except to signify a ligature.

The challenge: given a string as input, output the same string

* with all original ligatures replaced by their expanded counterparts.

+ match greedily: `affib` becomes `aﬃb` (`a[ffi]b`), not `aﬀib` (`a[ff]ib`) or `afﬁb` (`af[fi]b`).
* with all "expanded" letter sequences replaced by ligatures.

+ for example, `æOEfoo` (`[ae]OEfoo`) becomes `aeŒfoo` (`ae[OE]foo`).

Do this completely independently: `ﬀi` (`[ff]i`) becomes `ffi` (`ffi`), not  (`[ffi]`).

Sound simple enough? There's a catch: every time two non-ligatures overlap by *exactly one character*, **both** of the ligatures must be inserted into the string. Here's a few test cases to demonstrate:

```
Input   Ascii-output      Output
fij     [fi][ij]          ﬁĳ
fIJ     f[IJ]             fĲ     * remember, capitalization matters!
fffi    [ff][ffi]         ﬀﬃ
fff     [ff][ff]          ﬀﬀ
ffffi   [ff][ff][ffi]     ﬀﬀﬃ
ffffij  [ff][ff][ffi][ij] ﬀﬀﬃĳ

```

Be careful: the same greedy matching applies (note especially the last few test cases).

, so shortest code in bytes wins.

# Answer
> 3 votes
# JavaScript (ES6), 213 bytes - 20% bonus = 170.4

```
s=>eval('for(p=o="";m=s.match(r="ﬄ|ﬃ|ﬂ|ﬁ|ﬀ|Ĳ|ĳ|Œ|œ|Æ|æ|ffl|ffi|fl|fi|ff|IJ|ij|OE|oe|AE|ae",x=r.split`|`);s=s.slice(i+t.length-(p=t<"z")))o+=s.slice(p,i=m.index)+x[(x.indexOf(t=m[0])+11)%22];o+s.slice(p)')

```

## Explanation

```
s=>                           // s = input string
  eval(`                      // use eval to avoid writing {} or return
    for(                      // iterate over each ligature match
      p=                      // p = 1 if the last match was a non-unicode ligature
        o="";                 // o = output string
      m=s.match(              // find the next ligature

        // r = regex string for ligatures (unicode and non-unicode)
        r="ﬄ|ﬃ|ﬂ|ﬁ|ﬀ|Ĳ|ĳ|Œ|œ|Æ|æ|ffl|ffi|fl|fi|ff|IJ|ij|OE|oe|AE|ae",
        x=r.split\`|\`        // x = arrray of r

      );
      s=s.slice(i+t.length    // remove the part that has been added to the output
        -(p=t<"z"))           // if we matched a non-unicode ligature, keep the last
    )                         //     character so it can be part of the next match
      o+=s.slice(p,i=m.index) // add the text before the match to the output
        +x[(x.indexOf(        // add the opposite type of the matched ligature
          t=m[0]              // t = matched text
        )+11)%22];            // (index + 11) % 22 returns the opposite index
    o+s.slice(p)              // return o + any remaining characters
  `)

```

## Test

```
var solution = s=>eval('for(p=o="";m=s.match(r="ﬄ|ﬃ|ﬂ|ﬁ|ﬀ|Ĳ|ĳ|Œ|œ|Æ|æ|ffl|ffi|fl|fi|ff|IJ|ij|OE|oe|AE|ae",x=r.split`|`);s=s.slice(i+t.length-(p=t<"z")))o+=s.slice(p,i=m.index)+x[(x.indexOf(t=m[0])+11)%22];o+s.slice(p)')
```

```
<input type="text" id="input" value="ﬀiffffij" oninput="result.textContent=solution(input.value)" />
<pre id="result"></pre>
```

---
Tags: code-golf, string, unicode
---


# Question
Title: Find the absolute value of a number without built-in functions
The challenge is to take any real number as input and output or return the absolute value. You may not use any built-in functions other than those dealing with input and output/returning. This is code golf, so the shortest code wins. This is my first question here, so bear with me if I've left something obvious out of the challenge.

As per Quincunx's suggestion, I am limiting input to anywhere between -9E99 and 9E99.

Also, the only functions/operators you can use are `input`, `output`, `return`, `+`, `-`, `*`, `/`, `%`, `^` `+=`, `-=`, `*=`, `/=`, `>`, `<`, `==`, `>=`, `<=`, `!=`, `square`, and `square root` or their equivalents

# Answer
## J, 2 bytes

```
**

```

Usage:

```
   f =: **
   f 9.3
9.3
   f -9.3
9.3

```

**Explanation**:

This uses the `*` verb in both its monadic and dyadic forms. The monadic form returns `-1` if it's given a negative number, `0` if it's given `0` and `1` if it's given a positive number. The dyadic form is just plain old multiplication. Putting them in a function literal turns them into a hook which gets evaluated like this: `y * (*y)`.
> 21 votes

# Answer
# GolfScript, 4 characters

I believe I win. ;)

Works with integer or decimal numbers of any length.

```
'-'/

```

Try it online

These programs do the same and are of equal length:

```
'-'-

```

```
'-'%

```

# GolfScript (old version), ~~16~~ 13

My first GS program! (that actually does something)

Doesn't work with decimal numbers because GolfScript doesn't have floating point.

```
~:$0<{0$-}$if

```
> 15 votes

# Answer
## Perl: 5 characters

```
s/-//

```

The example:

```
perl -e '$_=-82.923; s/-//; print' # will print 82.923 or return it unless use 'print'

```
> 6 votes

# Answer
# C - 21

```
#define x(a) a<0?-a:a

```

This is a preprocessor macro, but does the same thing as Quincunx's Java solution when a real number is used as input.
> 5 votes

# Answer
## J - 7 3

**Max of number and inverse (3)**

```
>.-

```

When assigned to a function: take the maximum between the negative and the number, using a hook so: (f g) y = y f g y

```
f=:>.-
f _4 5 _1 0
   4 5 1 0

```

**root of the square (5 or 4)**

```
]&.*: _4 5 _1 0
    4 5 1 0
NB. or if an expression is good enough:
%:*: _4 5 _1 0
    4 5 1 0

```

**Negate if number smaller than its negative (7)**

```
-^:(<-)

```

Takes the inverse (the inverse is bigger than the number itself) times.

Would loosely translate to:

```
if -num > num then
    num= -num
end

```
> 5 votes

# Answer
# Mathematica ~~10~~ 8

**Method 1** (8 chars)

Take the square root of a number squared.

Sqrt@#²&

Examples

```
Sqrt@#²&[-.0176987]
Sqrt@#²&[.0176987]

```

> .0176987
> .0176987

---

**Method 2** (8 chars)

`Sign` returns -1 if negative, 0 if zero, 1 if positive.

```
# Sign@#&

```

Examples

```
# Sign@#&[-4.3]
# Sign@#&[4.3]

```

> 4.3
> 4.3

---

**4 chars?**

As the following picture shows, it is possible to legitimately reduce the function, but I haven't been able to replicate the input on SO.
> 4 votes

# Answer
# Brainfuck, 40 chars

```
+++++[>+++++++++<-],[->->+<<]>[>.>],[.,]

```

Or **35 chars** if wrapping is allowed.

```
-[+>+[+<]>+],+[->->+<<]>[>-.>],[.,]

```
> 4 votes

# Answer
## Python CLI, 20

```
lambda x:[x,-x][x<0]

```
> 4 votes

# Answer
## APL, 5

```
×∘×⍨⎕

```

A function would be **4 chars**

```
×∘×⍨

```

**Explanation**

`×`, when used with one argument, is the signum function; when used with two arguments, is multiplication.
is the compose(combination) of two functions.

`×∘×` is a function that takes two arguments and return the left argument times the signum of the right arugment.
means "use right argument as both left and right argument".
takes input from screen.
> 4 votes

# Answer
# C: 13 characters

I would assume using overloaded operators are not permitted? Just because something is abstracted and doesn't follow the standard formatting of a function call doesn't mean it isn't a function.

For example: (\**)n \<==\> abs(n) \<==\> '-'/

Anyways, here is my code: With explanation:

n+: ==\> +(true - false) ==\> +(1-0) ==\> +1

n-: ==\> -(false - true) ==\> -(0-1) ==\> -(-1) ==\> +1

```
a=n*(n>0 - (n<0))

```
> 4 votes

# Answer
**Haskell, 14 characters**

```
sqrt.flip(^)2$

```
> 3 votes

# Answer
# J, 13

Without using build-in functions (like signum and the like):

```
f =: -`]@.(0&<)

f -1.253
1.253
f 0.91235
0.91235

```
> 3 votes

# Answer
# Python 2.7 (16 charcters)

This one is the shortest here in python.

```
(input()**2)**.5

```

Let n = `input()`, then
> 3 votes

# Answer
EXCEL, 10:

```
=SQRT(n^2)

```

-- n is a defined cell name with the input value.
> 3 votes

# Answer
# TI-Basic, 3 bytes

Outputs square root of input squared.

```
√(Ans²

```

Alternates

```
√(AnsAns          3 bytes
Ans²^.5           5 bytes
max(Ans,-Ans      5 bytes
Anscos(angle(Ans  5 bytes
-min(Ans,-Ans     6 bytes
If Ans<0:-Ans     7 bytes
Ans-2Ans(Ans<0    8 bytes
Ans(2(Ans>0)-1    10 bytes
Ans(-1+2(Ans>0    10 bytes

```
> 3 votes

# Answer
# Python - ~~31~~ ~~28~~ ~~26~~ ~~24~~ ~~23~~ 18

Uses boothby's idea of a lambda function, saving 5 characters (or 3 if I need to assign it to a variable):

```
lambda x:(x*x)**.5

```

---

# Old Methods

Uses a generator function to save 1 char, so it is necessary to print the value with some function that uses a generator/iterator, like `for i in a(b):print(i)`

```
def a(b):yield(b*b)**.5

```

Saved ~~2~~ 3 characters by squaring and unsquaring.

---

```
def a(b):yield(b<0)*-2*b+b

```

Old one:

```
def a(b):yield b if b>0 else-b

```

Edit: saved two characters by factoring `b` in.
> 2 votes

# Answer
# JavaScript 26 13

`alert((b=prompt())<0?-b:b)`

Reducing it further with fat arrow functions...

`a=b=>b<0?-b:b`

Et voila! Reduction by 50%! Only issue is that this now only works for Firefox 22 and above with thanks to the fat arrows...
> 2 votes

# Answer
# C, 19

Slightly more than some other C answers, but guaranteed branch-less. the `f` variable is a `float`. I hope the bitwise operator `&` is allowed.

```
*(int*)&f&=INT_MAX;

```

Inspired from http://devmaster.net/posts/9998/the-ultimate-fast-absolute-value
> 2 votes

# Answer
## Seriously, ~~8~~ ~~7~~ ~~4~~ 3 bytes

Thanks @quintopia

My first Seriously answer, to a 2 yr old question!

Note the challenge is older than the language

```
,ª√

```

Seriously is a stack based language. What this does is it pushes the input on the stack, then multiplies if with itself. Then it takes the square root of the result. It is based on the fact that sqrt(x^2)=|x|.
> 2 votes

# Answer
# Java - 36

This is the obvious solution.

```
double a(double b){return b<0?-b:b;}

```
> 1 votes

# Answer
# Ruby, 15 characters

```
a=->b{b>0?b:-b}

```

# Ruby, 22 chars (with I/O)

```
p (a=gets.to_f)>0?a:-a

```

Accepts input on stdin, outputs on stdout
> 1 votes

# Answer
# Befunge 98 - ~~11~~ ~~7~~ 8

```
~:'-`!j,

```

Explained:

```
~  read character input
:  duplicate
'- fetch - and push it
`  compare duplicated value with it, 1 if first is greater, otherwise 0
!  if the number on the stack is 0, set it to 1, otherwise 0
j  jump the number of characters on the top of the stack, which is 1 if the input character is -
,  print the character on top of the stack

```

If I understand this correctly, then this works for any input, but only if constant looping is allowed. It simply prints everything but the minus sign. If infinite looping is not allowed, then this should work (~~13~~ 10 chars (Thanks FireFly)):

```
~:'-`!j,#@

```

---

Old version (Befunge 93) - 11

```
&:0`2*1-*.@

```

It works like this:

```
& push input
: push a duplicate
0 push a zero
` pop duplicate and 0, if duplicate greater than 0, push 1 else 0
2 push a two
* pop the 1 or 0 and 2 , multiply the 1 or 0 by the 2
1 push a one
- pop last two values and subtract the second value on the stack by the first (ie a-1)
* pop last two values and multiply last two values on stack (ie + or - 1 * input)
. print
@ end program

```

Note: Only integers are valid numbers in Befunge.

---

If I need to support floating point input, then it is **18** chars:

```
&&\:0`2*1-*.".",.@

```

It is **17** chars in **Befunge 98**:

```
&&\:0`2*1-*.'.,.@

```

Note: these print a space before the decimal point
> 1 votes

# Answer
# Clojure 13 ~~18~~ chars

```
#(max %(- %))

```

~~i am not sure if max is allowed, but i have seen others use it so here it goes :)~~

after the debate in the comments below, it was decided that max is indeed allowed!

use it like that:

```
(#(max %(- %)) -2) ; returns 2

```

---

~~edit - it seems max isnt allowed, so lets resort to the trivial solution~~

a trivial solution:

```
#(if(< % 0)(- %)%)

```

or

```
#((if(< % 0)- +)%)

```
> 1 votes

# Answer
# C# 6.0, 29 bytes

```
double m(double n)=>n<0?-n:n;

```
> 1 votes

# Answer
# MATLAB, 10 bytes

```
@(a)a^2^.5

```

Pretty straight forward. We are allowed `sqauare` and `square root`, so the absolute value of a number (assuming it is not complex!) is simply square it then square root it.
> 1 votes

# Answer
## Burlesque, 4 bytes

```
XXim

```

`XX` returns the digits of an integer and `im` converts the digits back to an integer. `XX` removes the sign.

You might also go with `Jsn?*` depending on the exact types.
> 1 votes

# Answer
# Swift, 35 bytes (Not Competitive)

This is just for fun, and because Swift was developed after this question was posted, is not a competitive answer.

```
func a(v:Int)->Int{return v<0?-v:v}

```

un-golfed version

```
func absolute(value: Int) -> Int{
   return value < 0 ? -value : value
}

```
> 1 votes

# Answer
# Prolog, 22 bytes

Saves 7 bytes over printing as we were allowed to return the absolute value.

**Code:**

```
p(X,Y):-Y is(X^2)^0.5.

```

**Explanation:**

Input **X** is squared, taken the root of and returned as **Y**.

**Example:**

```
p(-9.0e99,X).
X = 9.0e+99

```
> 1 votes

# Answer
# Milky Way 1.1.5, 13 bytes

```
':0e?{_^_;-}!

```

---

### Explanation

```
'              # read input from the command line
 :             # push a duplicate of the TOS to the stack
  0            # push 0 to the stack
   e           # push the truth value of A > B where A and B are the top two stack elements
    ?{_ _  }   # if-else statement
       ^       # pop the TOS without outputting
         ;     # swap the top two stack elements
          -    # push the value of A - B where A and B are the top two stack elements
            !  # output the TOS

```

---

### Usage

```
./mw <path-to-code> -i <input-integer>

```
> 1 votes

# Answer
# PHP, 30

```
<?=($n=$argv[1])*(1-($n<0)*2);

```
> 1 votes

# Answer
# Gema, 2 characters

Same as edem's Perl answer.

```
-=

```

Sample run:

```
bash-4.3$ gema -p '-=' <<< '-82.923'
82.923

```
> 1 votes

# Answer
## PowerShell: 38

Lazy if/else. Maybe I'll find a shorter way later.

```
if(($x=+(read-host))-lt0){-$x}else{$x}

```
> 0 votes

# Answer
# R 17 characters

```
max(n<-scan(),-n)

```

Or 13 characters by adapting David Carraher Mathematica answer:

```
sqrt(scan()^2)

```
> 0 votes

# Answer
## Ti-84 Table, ~~12~~ 5 characters

The text in brackets are the square root character and the squared character, respectively.

```
Y=[square root]X[^2]

```

The old code:

```
Y=X(2(X>0)-1

```

Both of these handle rational and irrational numbers. Any real number is valid, with limits of `-9.99999999*10^99` and `9.99999999*10^99` for the second one and `sqrt(-9.99999999*10^99)` and `sqrt(9.99999999*10^99)` for the first one.

Gets input on X and shows equivalent absolute number as Y.
> 0 votes

# Answer
## PowerShell, 22

```
(read-host)-replace'-'

```

Or, if the returned value has to typed as numeric, 23:

```
+(read-host)-replace'-'

```
> 0 votes

# Answer
## F#, 30

```
let a x=if x<0. then -x else x

```
> 0 votes

# Answer
# Python (20)

```
lambda x:x*2*(x>0)-x

```
> 0 votes

# Answer
# Python - 27 chars

```
>>> f=lambda x:-x if x<0 else x
>>> f(-19.768)
19.768

```
> 0 votes

# Answer
**AWK, 15**

```
1,$0*=$1<0?-1:1

```

Note that, the following code can handle all values except 0

**AWK, 13**

```
 $0*=$1<0?-1:1

```
> 0 votes

# Answer
No one use sed? similar as perl

```
s/-//

```
> 0 votes

# Answer
## PHP, 40

```
<? $n=$argv[1];if($n<0) $n*=-1;echo $n;

```
> 0 votes

# Answer
# SQL - 43 chars

```
SELECT CASE WHEN @n<0 THEN -@n ELSE @n END;

```
> 0 votes

# Answer
# Arcyóu, 16 bytes

```
(F(x)(^(^ x 2).5

```

This is an anonymous function taking one numeric type. It returns a floating point number equal to the number's absolute value. This is just nested exponentiation.
> 0 votes

# Answer
## FP15 (7)

```
(*)sqrt

```

The `(*)` function squares a number. How does it work? In Haskell, `(2*)` means `\x -> 2 * x` and `(*2)` is `\x -> x * 2`, but `(*)` isn't `\x -> x * x`. In FP15, you can do `(*)` and even things like `(*2+1)` and `(^2 - 5*sqrt)`. Also, in FP15, function composition is left-to-right.

Examples (`~` is negation):

```
$ ./fp15-repl.py
> 12(*)sqrt
12.0
> 0(*)sqrt
0.0
> ~12(*)sqrt
12.0

```

If the signum function is allowed:

```
(*sgn)

```

If conditionals are allowed:

```
{(<0):~|_}

```

If max is allowed:

```
(~.max)
[,~]max

```

I created this language and it's still work in progress (no IO functions for now), but the last time I worked on it was early October.
> 0 votes

# Answer
# Go, 62 bytes

Pretty straightforward, I should think. Submitting a noncompilable standalone function feels so... wrong.

```
func a(){a:=""
Scanln(&a)
b,_:=Atoi(a)
if b<0{b=0-b}
Print(b)}
```
> 0 votes

# Answer
# Rotor, 2 bytes

```
sS

```

Challenge predates this language by two years, so this isn't competitive.

Squares input and then square roots it. Nothing special.
> 0 votes

# Answer
**Note: this answer was written before the rule change mess, and was valid at time of posting.**

---

# Mouse-2002, 11 bytes

The DUP word is two bytes too long, and it requires a space after it. :( However, it still costs less than a var. (2 bytes *per use*)

```
?&DUP 0<[_]

```

Expanded:

```
?      ~ input
&DUP   ~ dup
0 <    ~ cmp
[      ~ if
  _    ~ signflip
]      ~ fi

```

---

Or, if leaving the value on the stack is not sufficient, then **12 bytes**:

```
 ?&DUP 0<[_]!

```

This language needs implicit printing if nothing was.

---

```
$ mouse abs.mou
-100e99
100e99
$ mouse abs.mou
-INF
INF
$

```

Do I get a bonus if my program can compute *every* real number?
> 0 votes

# Answer
# LISP, 38

```
(define (abs x)
 (cond ((< x 0) (- x))
        (else x)
        ))

```
> -1 votes

# Answer
## Ti-Basic 84, 10 bytes

```
Ans(2(Ans>0)-1

```
> -2 votes

---
Tags: code-golf, restricted-source
---


# Question
Title: Solve a mathematical expression from alternating sides
Create a program that solves a mathematical expression using the elements from alternating sides of the expression. The way it’s done is, instead of reading from left to right, you read the first character, then the last, then the second, then the second to last etc. This will give you a new expression that you must evaluate and output.

```
a*b/c+d-e
135798642  <-- Order you read the expression in
ae*-bd/+c  <-- Order of operation.

```

Example:

```
1*3/2+4-5
15*-34/+2 = -255

```

If the expression doesn’t «work», a `1` must be inserted in the necessary positions to make it work.

A few examples will probably illustrate it better:

```
Input: 1+1+1+1+1
Result: 23     // Because 1+1+1+1+1 -> 11++11++1 -> 23

Input: 1+2-3+12-5
Result: -19    // Because 1+2-3+12-5 -> 15+-22-13+ -> 15+-22-13+1 -> -19
               //                                 |
               //                                 Not valid expression

Input: 2*2*2*2*2
Result: 968    // Because 2*2*2*2*2 -> 22**22**2 -> 22*1*22*1*2 -> 968
               //                        ||  ||
               //                        Not valid, 1 must be inserted

Input: 17/2
Output: 127    // Because 17/2 = 127/ -> 127/1 -> 127

```

The operators that must be supported are `+ - * /`. There won't be parentheses. Normal math rules and "syntax" is used, so for instance `**` does not mean exponentiation. `a++++1` is equivalent to `a+1` (i.e. MATLAB style, not C++).

In case there's any doubt, some valid operations are:

```
-a
+a
a++b
a+-b
a*-b
a*+b
a*++b
a/b
a/-b
a/+b
-a/--b

```

While all of the following are not valid. It's shown what they should be substituted with:

```
a+      | a+1
a-      | a-1
a++++   | a++++1   (This is equivalent to a+1)
a*+++   | a*+++1   (This is equivalent to a*1)
a**b    | a*1*b
a*/b    | a*1/b
a/*b    | a/1*b
a*      | a*1
*a      | 1*a
***a    | 1*1*1*a

```

Rules:

* The code can be a function or a full program
* The input can be STDIN or function argument
* The input must be a valid mathematical expression, **without quotation marks, `''` or `""`**.
* The output should be the answer to the new expression, as an integer, decimal or a simplified fraction.
* At least three digits after the decimal point must be supported. So `1/3 = 0.333`, not `0.33`. `0.333333333` is accepted.
* `ans = ...` is accepted.
* Leading and trailing newlines and spaces are accepted.
* The input will only be integers
* Division by zero can result in an error, NaN, Inf etc. Outputting a number is not accepted.

As always, the shortest code in bytes win. A winner will be selected one week from the day the challenge was posted. Answers posted later may still win if it's shorter than the current leader.

# Answer
## Perl, ~~108~~ 100 bytes

```
$_="";while(@F){$_.=shift@F;$_.=pop@F}s@(\*|/)\1+@\1@g;s@^[*/]@1$&@;s@\D$@$&1@;s@\D@$&@g;$_=eval

```

The code is 96 bytes, plus 4 for the command-line argument `-pF//`, where

* `-p` inserts `while (<>) { .. } continue { print }` and
* `-F//` splits the input and puts it in `@F`.

Note that the input should not have a trailing newline, so use `/bin/echo -n 'formula' | perl ...`

Less golfed:

```
$_='';              # reset $_
while(@F) {         # reorder input
   $_.=shift @F;    # take first element off of @_
   $_.=pop @F       # idem for last; if @F is empty, undef is appended
}

s@(\*|/)\1+@\1@g;   # replace 2 or more '*' or '/' with just one: *1 and /1 = nop
s@^[*/]@1$&@;       # if expression starts with * or / prepend a 1
s@\D$@$&1@;         # if expression doesn't end with a number, append 1
s@\D@$& @g;         # eval doesn't like '++1': add spaces after operators
$_ = eval           # set $_ to 3v1l, so the `-p` will print the new value

```

---

### Testing

Put the above in a file called `114.pl`, and the below test script in a file next to it:

```
%test = (
    '1+1+1+1+1' =>   23,
    '1*3/2+4-5' => -255,
    '1+2-3+12-5'=>  -19,
    '2*2*2*2*2' =>  968,
    '17/2'      =>  127,
    '--/-1-2-'  =>   -2,
    '**2*'      =>    2,
    '++1++'     =>    1,
    '/2/'       =>  0.5,
    '10/'       =>   '',
);

printf "%-20s -> %5s: %5s\n", $_, $test{$_}, `/bin/echo -n '$_' | perl -pF// 114.pl`
for keys %test;

```

Running it outputs:

```
++1++                ->     1:     1
**2*                 ->     2:     2
17/2                 ->   127:   127
10/                  ->      :
1+1+1+1+1            ->    23:    23
1*3/2+4-5            ->  -255:  -255
2*2*2*2*2            ->   968:   968
1+2-3+12-5           ->   -19:   -19
--/-1-2-             ->    -2:    -2
/2/                  ->   0.5:   0.5

```

Note that `1/0` causes a division by zero error: the `eval` outputs `undef`, which is represented by the empty string.
> 3 votes

# Answer
# JavaScript ES6, 105 ~~106~~

**Edit** Saved 1 byte thx @Kenney

```
t=>eval("for(t=[...t],p=o='';c=t.reverse().pop();p=c)o+=p<'0'?(c=='/'|c<'+'||' ')+c:c;eval(p<'0'?o+1:o)")

// Less golfed
t=>{
  for(t = [...t], p = o = '';
      c = t.reverse().pop();
      p = c)
    o += p<'0'
     ? (c=='/' | c=='*' || ' ')+c  // '1' or ' '
     : c;
  return eval(p<'0' ? o+1 : o)
}

```

Test snippet

```
f=t=>eval("for(t=[...t],p=o='';c=t.reverse().pop();p=c)o+=p<'0'?(c=='/'|c<'+'||' ')+c:c;eval(p<'0'?o+1:o)")

console.log=x=>O.innerHTML+=x+'\n'

function test() { console.log(I.value + ' -> '+f(I.value)) }

;['1+1+1+1+1', '1*3/2+4-5', '1+2-3+12-5', '2*2*2*2*2',
  '17/2', '--/-1-2-', '**2*', '++1++', '/2/', '10/' ]
.forEach(t=>console.log(t+' -> '+f(t)))
```

```
Your test <input id=I><button onclick="test()">-></button>
<pre id=O></pre>
```
> 3 votes

---
Tags: code-golf, string, arithmetic
---


title: Flip the switches

text:
# Question
Title: Flip the switches
After you wake in a dark room, you see a rectangular grid of lights with corresponding switches. You decide to use a coordinate system with the bottom left light representing (1,1) and the coordinates increasing as you go up (y direction) and to the right (x direction). The grids are identical in that flipping the switch at (a,b) toggles (turns from off to on or from on to off) the light at (a,b) as well as the lights in the same column or same row as (a,b).

Your input will be a rectangular grid of two distinct characters representing on and off (I use 1 and 0, respectively). Also, a part of the input will be a series of at least one coordinate pair (with whatever format and separation you want) that will represent switches that you flip.

The output will be the same grid, with the "flip" applied at each of the coordinate pairs that were given as input. You may choose how to format your input, though the output must be a grid, not an array.

---

**Samples**

Sample input 1

```
111111
111111
111111
111111

(3,2)

```

Sample output 1

```
110111
110111
000000
110111

```

Sample input 2

```
01101
10100
00010
11111
10110

(1,1), (5,5)

```

Sample output 2

```
00010
00101
10011
01110
01000

```

Sample input 3

```
1

(1,1)

```

Sample output 3

```
0

```

Sample input 4

```
00000
11111
00000
11111

(2,3), (2,3)

```

Sample output 4

```
00000
11111
00000
11111

```

---

This is code golf. Standard rules apply. Shortest code in bytes wins.

# Answer
> 4 votes
## Dyalog APL, 20 bytes

```
{⍵≠⊃⊃≠/∘.∨/¨⍺=⊂⍳¨⍴⍵}

```

This is a dyadic function that takes the initial grid on the right and the list of coordinates on the left.

To input a single coordinate pair, use e.g. `(⊂2 3)` as the left argument.

Try it here.

# Answer
> 3 votes
## CJam, ~~37~~ 36 bytes

```
qN/W%(~{1$::!\{1a\Te[f.|z}/..^}/W%N*

```

Input should have the grid first, using any two non-NULL characters that only differ in the last bit (so `0` and `1` work), followed by a CJam-style list of coordinate pairs.

```
01101
10100
00010
11111
10110
[[1 1] [5 5]]

```

Test it here.

# Answer
> 1 votes
# MATL, 39 bytes

```
i,-1H$X!tyZ}:XJx:!XIxi"I@1)=J@2)=|+]2\X!

```

Input is of the following form (the example corresponds to sample input 2 in the challenge):

```
[0 1 1 0 1; 1 0 1 0 0; 0 0 0 1 0; 1 1 1 1 1; 1 0 1 1 0]
[1 5; 1 5]

```

First input is a matrix defining the grid of `0` and `1`. `;` is the row separator. Second input is a matrix of coordinate pairs, where each *column* is a pair.

### Example

```
>> matl i1_2$X!tyZ}:XJx:!XIxi"I@1)=J@2)=|+]2\X!
> [0 1 1 0 1; 1 0 1 0 0; 0 0 0 1 0; 1 1 1 1 1; 1 0 1 1 0]
> [1 5; 1 5]
0 0 0 1 0
0 0 1 0 1
1 0 0 1 1
0 1 1 1 0
0 1 0 0 0

```

### Explanation

```
i,           % input matrix
-1H$X!       % rotate clockwise to accomodate input to matrix coordinates
tyZ}         % get numbers of rows (r) and of cols (c)
:XJx         % row vector 1,2,,...,c. Copy to clipboard J and delete
:!XIx        % col vector 1,2,,...,r. Copy to clipboard I and delete
i            % input coordinates (matrix; each col is a coordinate)
"            % for each col of coordinate matrix
    I@1)=    % compare col vector of rows with row from coordinate
    J@2)=    % compare row vector of cols with col from coordinate
    |        % "or" with singleton expansion to generate mask
    +        % add that to matrix of values
]            % end for
2\           % modulo 2 to transform result into zeros and ones
X!           % undo rotation

```

# Answer
> 0 votes
# Ruby 114 bytes

Takes as input:

`g`, an array of arrays representing the starting grid.

`o`, an array of points, each point being an array with two elements, like `[x, y]`.

```
->g,o{o.map{|i|(r=g[i[1]-1])[e=(i[0]-1)]-=1;r.map!{|j|j+1};g.map{|x|x[e]+=1}};puts g.map{|i|i.map{|j|j%2}.join""}}

```

---
Tags: code-golf, grid
---


title: Has someone been defenestrated?

text:
# Question
Title: Has someone been defenestrated?
> **Defenestration** is the act of throwing someone or something out of a window.
> Wikipedia

## Input

The input will consist of two parts:

* A floor plan and a person inside the house/building.

+ `v><^` represents a person, pointing in the direction signified by the arrow. The input will contain exactly one person.
    + `-` and `|` represent walls, and `#` represents a window.  is empty space.

This portion of the input may be taken as either a single string, or an array/list/etc. of lines. There will never be any trailing or leading spaces, and the input will always be a rectangle.

Example:

```
-----###---
|         |
|     ^   |
-----------

```
* An integer ≥ 1 signifying how far (in characters) the person travels.

## Output

The output should be

* `1` if the person ends up "inside" a window (i.e. after moving forwards the distance specified in the input, the person is on top of a `#`).
* `2` if the person has been defenestrated (come into contact with a `#` and then continued further on).
* `3` if the person has hit a wall (come into contact with a `-` or `|`. Once hitting the wall, the person stops and does not continue through it).
* `0` if none of the above are true (and all the person has done is travel through empty space).

## Assumptions

All of the following can be assumed to be true:

* The person will never travel "out of bounds" of the input area.
* After being defenestrated, the person will never come into contact with another `#` or a `-`/`|` (so you don't have to worry about if `2` *and* `1` or `3` are both true).

## Test cases

For the following "floor plan":

```
-----
|   |
|###|
|   |
| ^ |

```

```
In   Out
1    0
2    1
3    2

```

For this floor plan:

```
> | # |

```

```
In   Out
1    0
2-99 3    * that is, any input 2-99 outputs 3

```

For this floor plan:

```
||####|#|#|##|<

```

```
In   Out
any  3

```

Final test case:

```
|v|
|#|
| |
| |
| |
| |

```

```
In   Out
1    1
2-5  2

```

# Answer
# JavaScript (ES6), ~~147~~ 146 bytes

```
(p,n)=>eval('l=p.search`\n`+1;m=p.match`[<>v^]`;for(r=d=i=0;i++<n&r<3;r-1?0:d=2)r=(c=p[m.index+i*({v:l,"<":-1,">":1}[m]||-l)])>"#"?3:c>" ";+r||d')

```

*Saved 1 byte thanks to @NinjaBearMonkey!*

## Explanation

Takes a floorplan as a string and the number of moves. Returns a number.

```
(p,n)=>                               // p = floor plan as string, n = number of moves
  eval(`                              // use eval to enable for loop without {} or return
    l=p.search\`\n\`+1;               // l = line length
    m=p.match\`[<>v^]\`;              // m = the position and orientation of the person
    for(
      r=                              // r = result at the current step
        d=                            // d = 2 if the person has been defenestrated
          i=0;                        // i = current step
      i++<n&r<3;                      // for each step while the person has not hit a wall
      r-1?0:d=2                       // set d to 2 once the person enters the window
    )
      r=(                             // r = 0 if on " ", 1 if on "#" or 3 if on "|" or "-"
        c=p[m.index+i*                // c = character after current step
          ({v:l,"<":-1,">":1}[m]||-l) // get the index offset of each step
        ]
      )>"#"?3:c>" ";
    +r||d                             // return the result of the current step or d
  `)

```

## Test

```
var solution = (p,n)=>eval('l=p.search`\n`+1;m=p.match`[<>v^]`;for(r=d=i=0;i++<n&r<3;r-1?0:d=2)r=(c=p[m.index+i*({v:l,"<":-1,">":1}[m]||-l)])>"#"?3:c>" ";+r||d')
```

```
<textarea id="floorplan" rows="6" cols="30">-----
|   |
|###|
|   |
| ^ |</textarea><br />
Moves = <input type="text" id="moves" value="3" />
<button onclick="result.textContent=solution(floorplan.value,moves.value)">Go</button>
<pre id="result"></pre>
```
> 11 votes

---
Tags: code-golf, string
---


title: Make a numeric list converter

text:
# Question
Title: Make a numeric list converter
Don't you hate it when you want to copy-paste a list of numbers (vector, array ...), from one program to another, but the format you have the numbers on doesn't match the format you need it on?

For instance, in MATLAB you may have a space separated list like this:

```
[1 2 3 4 5]    (you can also have it comma separated, but that's not the point)

```

In Python you would need to insert commas to make that list a valid input, so you'd have to convert it to

```
[1, 2, 3, 4, 5]

```

to make it work. In C++ you might want something like:

```
{16,2,77,29}

```

and so on.

To simplify everyone's life, let's create a list converter, that takes a list on any format\*, and outputs a list on another specified format.

The valid brackets are:

```
[list]
{list}
(list)
<list>
list      (no surrounding brackets)

```

The valid delimiters are:

```
a,b,c
a;b;c
a b c
a,  b,  c       <-- Several spaces. Must only be supported as input.
a;     b; c     <-- Several spaces. Must only be supported as input.
a   b   c       <-- Several spaces. Must only be supported as input.

```

Note, the input can have any number of spaces between the numbers, but the output can choose to have zero spaces (if `,` or `;` is used as delimiter), or a single space (if it's space-delimited).

In addition to the input list, there will be a string (or two characters) that defines the output format. The format string will first be the opening bracket type (only), `[`, `(`, `<`, `{` or  (the last one is a single space used when there is no surrounding bracket). The bracket type will be followed by the delimiter type, `,`, `;` or  (the last one is a single space). The two input format characters must be taken as a single argument (string or two consecutive characters) in the order described above.

Some examples of format strings:

```
[,    <-- Output format:   [a,b,c]
{;    <-- Output format:   {a;b;c}
      <-- Two spaces, output list has format:   a b c

```

Rules:

* The output can't have leading spaces
* The output can have trailing spaces and a newline
    + The output should *only* be the list of numbers, not `ans =` or similar
* The input will be a list of integer or decimal numbers (both positive and negative (and zero)), and a string of two characters
    + If the input consist of *only* integers, the output list should have only integers. If the input list consist of integers and decimal numbers, all output numbers can be decimal numbers. (It's optional to keep the integers as integers)
    + The maximum number of digits after the decimal point that must be supported are 3.
    + The input will be two arguments. I.e. the numbers are in one argument, and the format string is a single argument.
* The code can be a program or function
* The input can be function argument or STDIN

Some examples:

```
1 2 3 4
[,
[1,2,3,4]

<1;  2;  3>
 ;    <-- Space + semicolon
1;2;3
not valid:  1.000;2.000;3.000   (Input is only integers => Output must be integers)

{-1.3, 3.4, 4, 5.55555555}
[,
[-1.300,3.400,4.000,5.556]  (5.555 is also valid. Rounding is optional)
also valid: [-1.3,3.4,4,5.55555555]

```

The shortest code in bytes win. As always, the winner will be selected one week from the day the challenge was posted. Answers that are posted later can still win if they are shorter than the current winner.

---

## Leaderboard

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

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

```
## Language Name, N bytes

```

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

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

```

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

```
## Perl, 43 + 2 (-p flag) = 45 bytes

```

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

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

```

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

```
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
```

```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>
```

# Answer
> 1 votes
# CJam, 27 bytes

```
l)l_5ms`-SerS%*\S-_o_'(#(f-

```

Try it here.

### Explanation

```
l      e# Read the format string.
)      e# Extract the separator.
l_     e# Read the list.
5ms`   e# Get a string that contains -.0123456789.
-      e# Get the characters in the list that are not in the string.
Ser    e# Replace those characters with spaces.
S%     e# Split by those characters, with duplicates removed.
*      e# Join with the separator.
\S-    e# Remove spaces (if any) from the left bracket.
_o     e# Output a copy of that character before the stack.
_'(#   e# Find '( in the left bracket string.
(      e# Get -1 if '( is the first character, and -2 if it doesn't exist.
f-     e# Subtract the number from every character in the left bracket string,
          making a right bracket.

```

# Answer
> 8 votes
# JavaScript (ES6), 75 ~~82~~

As an anonymous function

Edit: 2 byte saved thx @user81655 (and 5 more just reviewing it)

```
(l,[a,b])=>a.trim()+l.match(/[-\d.]+/g).join(b)+']})> '['[{(< '.indexOf(a)]

```

Test snippet

```
F=(l,[a,b])=>a.trim()+l.match(/[-\d.]+/g).join(b)+']})> '['[{(< '.indexOf(a)]

// Test
console.log=x=>O.innerHTML+=x+'\n'
// default test suite
t=[['1 2 3 4','[,'],['<1;  2;  3>',' ;'],['{-1.3, 3.4, 4, 5.55555555}','[,']]
t.forEach(t=>console.log(t[0]+' *'+t[1]+'* '+F(t[0],t[1])))
function test() { console.log(P1.value+' *'+P2.value+'* '+F(P1.value,P2.value)) }
```

```
#P1 { width: 10em }
#P2 { width: 2em }
```

```
P1<input id=P1>
P2<input id=P2>
<button onclick="test()">-></button>
<pre id=O></pre>
```

# Answer
> 6 votes
## CJam, ~~35~~ 34 bytes

```
l(S-l"{[<(,}]>);":BSerS%@*1$B5/~er

```

Test it here.

Expects the format on the first line and the list on the second.

### Explanation

```
l   e# Read the format line.
(   e# Pull off the first character, which is the opening bracket.
S-  e# Set complement with a space, which leaves brackets unchanged and turns a space
    e# into an empty string.
l   e# Read the list.
"{[<(,}]>);":B
    e# Push this string which contains all the characters in the list we want to ignore.
Ser e# Replace each occurrence of one of them with a space.
S%  e# Split the string around runs of spaces, to get the numbers.
@   e# Pull up the the delimiter string.
*   e# Join the numbers in the list with that character.
1$  e# Copy the opening bracket (which may be an empty string).
B5/ e# Push B again and split it into chunks of 5: ["{[<(," "}]>);"]
~   e# Unwrap the array to leave both chunks on the stack.
er  e# Use them for transliteration, to turn the opening bracket into a closing one.

```

# Answer
> 5 votes
# Pyth, 33 bytes

```
rjjezrXwJ"<>[]  {}(),;"d7@c6JChz6

```

Try it online: Demonstration or Test Suite

# Explanation:

```
J"<>[]  {}(),;"  assign this string to J

rjjezrXwJd7@c6JChz6   implicit: z = first input string, e.g. "[;"
       w              read another string from input (the list of numbers)
      X Jd            replace every char of ^ that appears in J with a space
     r    7           parse ^ (the string of numbers and spaces) into a list
  jez                 put z[1] (the separator symbol) between the numbers
            c6J       split J into 6 pieces ["<>", "[]", "  ", "{}", "()", ",;"]
               Chz    ASCII-value of z[0] (opening bracket symbol)
           @          take the correspondent (mod 6) brackets from the list
 j                    and put the numbers between these brackets
r                 7   remove leading and trailing spaces

```

# Answer
> 5 votes
## PowerShell, ~~108~~ ~~100~~ ~~95~~ 85 Bytes

```
$i,$z=$args;($z[0]+($i-split'[^\d.-]+'-ne''-join$z[1])+' }) >]'[($z[0]-32)%6]).Trim()

```

<sub>(see revision history for previous versions)</sub>

Golfed another 15 bytes by removing `$b` and `$s` variables and changing parens on the inner string.

This takes input as two strings and stores them into `$i` and `$z`, then we construct a new output string. The inner parens `-split`s `$i` with a regex to select only numeric digits, then `-join`s back together with the requested delimiter. We concatenate that with the first character of the delimiter input (e.g., `[`) and close it with indexing into a string based on the ASCII value of the first character and some formulation trickery. The outer `.Trim()` removes any leading or trailing spaces.

# Answer
> 4 votes
# Python 2, 96 bytes

```
import re
lambda(a,(b,c)):(b+c.join(re.findall('[-\d\.]+',a))+'])>} '['[(<{ '.index(b)]).strip()

```

Call as:

```
f(('{-1.3, 3.4, ,4, 5.55555555}','[,'))

```

Output:

```
[-1.3,3.4,4,5.55555555]

```

# Answer
> 2 votes
# JavaScript (ES6), ~~82~~ ~~92~~ ~~116~~ 92 bytes

```
(a,b)=>(c=a.match(/-?\d+(\.\d+)?/g).join(b[1]),d=b[0],d<"'"?c:d+c+"]}>)"["[{<(".indexOf(d)])

```

An anonymous function, run it like this

```
((a,b)=>(c=a.match(/-?\d+(\.\d+)?/g).join(b[1]),d=b[0],d<"'"?c:d+c+"]}>)"["[{<(".indexOf(d)]))("{1;  2;3;   4}","<;")

```

This can probably be golfed way further..

### Ungolfed

```
(a,b)=>(                             // "{1;  2;3;   4}", "<;"
    c=a.match(/-?\d+(\.\d+)?/g)      // regex to match decimals
    .join(b[1]),                     // c -> "1;2;3;4"
    d=b[0],                          // d -> "<"
    d<"'" ?                          // if d is smaller than ' then ...
        c :                          // return just "1;2;3;4"
        d + c +                      // "<" + "1;2;3;4" + ...
        "]}>)" [ "[{<(".indexOf(d) ] // "]}>)"[2] -> ">"
)

```

# Answer
> 2 votes
# Mathematica, 108 bytes

Mathematica is generally clumsy with string inputs unless the string is meant to be interpreted as a text.

```
c=Characters;t_~f~p_:=({b,s}=c@p;b<>Riffle[StringCases[t,NumberString],s]<>(b/.Thread[c@"[ {<(" -> c@"] }>)"]))

```

---

**Explanation**

`StringCases[t,NumberString]`returns the list of number strings.

`Riffle`inserts the separators between the numbers.

`/.Thread[c@"[ {<(" -> c@"] }>)"])` replaces the left "bracket" with the right bracket.

`<>` is the infix form of `StringJoin`. It glues together the substrings.

# Answer
> 2 votes
# Bash + GNU Utilities, 90

```
b=${2:0:1}
echo $b`sed "s/[][{}()<>]//g;s/[,; ]\+/${2:1}/g"<<<"$1"``tr '[{(<' ']})>'<<<$b`

```

# Answer
> 2 votes
# Matlab, 85 bytes

```
@(s,x)[x(1) strjoin(regexp(s,'-?\d+\.?\d*','match'),x(2)) x(1)+(x(1)~=32)+(x(1)~=40)]

```

Example use:

```
>> @(s,x)[x(1) strjoin(regexp(s,'-?\d+\.?\d*','match'),x(2)) x(1)+(x(1)~=32)+(x(1)~=40)]
ans =
    @(s,x)[x(1),strjoin(regexp(s,'-?\d+\.?\d*','match'),x(2)),x(1)+(x(1)~=32)+(x(1)~=40)]

>> ans('1 2.4 -3 -444.555 5', '[,')
ans =
[1,2.4,-3,-444.555,5]

```

# Answer
> 1 votes
# Julia, 95 bytes

```
f(l,s)=(x=s[1]<33?"":s[1:1])*join(matchall(r"[\d.-]+",l),s[2])*string(x>""?s[1]+(s[1]<41?1:2):x)

```

This is a function `f` that accepts two strings and returns a string.

Ungolfed:

```
function f{T<:AbstractString}(l::T, s::T)
    # Extract the numbers from the input list
    n = matchall(r"[\d.-]+", l)

    # Join them back into a string separated by given separator
    j = join(n, s[2])

    # Set the opening bracket type as the empty string unless
    # the given bracket type is not a space
    x = s[1] < 33 ? "" : s[1:1]

    # Get the closing bracket type by adding 1 or 2 to the ASCII
    # value of the opening bracket unless it's an empty string
    c = string(x > "" ? s[1] + (s[1] < 41 ? 1 : 2) : x)

    # Put it all together and return
    return x * j * c
end

```

---
Tags: code-golf, string, syntax
---


title: Make a scalable Christmas Tree

text:
# Question
Title: Make a scalable Christmas Tree
Your challenge: Make a Christmas tree. The size must be choosable by some input method, but doesn't have to be directly related to any part of the tree; however, larger inputs should produce a larger tree.

How can you make it? You can make the tree any way you like, other than by printing the unicode character for the tree, such as ouputting an image, ascii art, with other aspects, etc. Whatever you do, remember that this is a , so be creative.

The answer with the most upvotes by the end of December wins, but I'll accept another if it gets higher

# Answer
> 90 votes
## Python

A fractal Christmas tree using the turtle package:

```
n = input()*1.

from turtle import *
speed("fastest")
left(90)
forward(3*n)
color("orange", "yellow")
begin_fill()
left(126)
for i in range(5):
    forward(n/5)
    right(144)
    forward(n/5)
    left(72)
end_fill()
right(126)

color("dark green")
backward(n*4.8)
def tree(d, s):
    if d <= 0: return
    forward(s)
    tree(d-1, s*.8)
    right(120)
    tree(d-3, s*.5)
    right(120)
    tree(d-3, s*.5)
    right(120)
    backward(s)
tree(15, n)
backward(n/2)

import time
time.sleep(60)

```

n is the size parameter, the shown tree is for n=50. Takes a minute or two to draw.

# Answer
> 76 votes
### JavaScript

Show the animated tree online.

```
var size = 400;

var canvas = document.createElement('canvas');
canvas.width = size;
canvas.height = size;
document.body.appendChild(canvas);

var ctx = canvas.getContext('2d');

var p3d = [];

var p = [Math.random(), Math.random(), Math.random(), 0];

for (var i = 0; i < 100000; i++) {
    p3d.push([p[0],p[1],p[2],p[3]]);
    var t = Math.random();
    if (t<0.4) {
        _y = 0.4 * p[1];
        _x = 0.1 * p[0];
        _z = 0.6 * p[2];
        var r = Math.floor(3*t/0.4)/3.0;
        var rc = Math.cos(Math.PI*2.0*r);
        var rs = Math.sin(Math.PI*2.0*r);
        p[1] = _x+0.1*r+0.5*_y*_y;
        p[0] = _y*rc+_z*rs;
        p[2] = _z*rc-_y*rs;
        p[3] = 0.2*t + 0.8*p[3];
    } else {
        p[1] = 0.2 + 0.8*p[1];
        p[0] = 0.8 * p[0];
        p[2] = 0.8 * p[2];
        p[3] = 0.2 + 0.8*p[3];
    }
}

var rot = 0.0;

function render() {
    rot = rot + 0.1;
    var rc = Math.cos(rot);
    var rs = Math.sin(rot);

    ctx.strokeStyle='#FF7F00';
    ctx.lineWidth=2;
    ctx.beginPath();
    ctx.moveTo(size/2,size/8);
    ctx.lineTo(size/2,size*15/16);
    ctx.stroke();

    var img = ctx.getImageData(0, 0, size, size);
    for (var j = 0; j < size*size; j++) {
        img.data[4*j+0] = 0.5*img.data[4*j+0];
        img.data[4*j+1] = 0.5*img.data[4*j+1];
        img.data[4*j+2] = 0.5*img.data[4*j+2];
        img.data[4*j+3] = 255;
    }

    for (var i = 0; i < p3d.length; i++) {
        var px = p3d[i][0];
        var py = 0.5 - p3d[i][1];
        var pz = p3d[i][2];
        var col = Math.floor(128.0*p3d[i][3]);

        var _x = rc*px + rs*pz;
        var _z = rc*pz - rs*px;

        var z = 3.0 * size / (_z + 4.0);
        var x = size / 2 + Math.round(_x * z);
        var y = size / 2 + Math.round(py * z);

        if(x>=0&&y>=0&&x<size&&y<size) {
            img.data[4 * (y * size + x) + 0] = col;
            img.data[4 * (y * size + x) + 1] = 128+col;
            img.data[4 * (y * size + x) + 2] = col;
            img.data[4 * (y * size + x) + 3] = 255;
        }
    }

    ctx.putImageData(img, 0, 0);
}

setInterval(render, 1000 / 30);

```

# Answer
> 75 votes
Yet another *Mathematica / Wolfram Language* tree based on Vitaliy's answer:

```
PD = .5;
s[t_, f_] := t^.6 - f
dt[cl_, ps_, sg_, hf_, dp_, f_, flag_] :=
    Module[{sv, basePt},
           {PointSize[ps],
            sv = s[t, f];
            Hue[cl (1 + Sin[.02 t])/2, 1, .3 + sg .3 Sin[hf sv]],
            basePt = {-sg s[t, f] Sin[sv], -sg s[t, f] Cos[sv], dp + sv};
            Point[basePt],
           If[flag,
              {Hue[cl (1 + Sin[.1 t])/2, 1, .6 + sg .4 Sin[hf sv]], PointSize[RandomReal[.01]],
               Point[basePt + 1/2 RotationTransform[20 sv, {-Cos[sv], Sin[sv], 0}][{Sin[sv], Cos[sv], 0}]]},
              {}]
          }]

frames = ParallelTable[
                       Graphics3D[Table[{
                                         dt[1, .01, -1, 1, 0, f, True], dt[.45, .01, 1, 1, 0, f, True],
                                         dt[1, .005, -1, 4, .2, f, False], dt[.45, .005, 1, 4, .2, f, False]},
                                        {t, 0, 200, PD}],
                                  ViewPoint -> Left, BoxRatios -> {1, 1, 1.3},
                                  ViewVertical -> {0, 0, -1},
                                  ViewCenter -> {{0.5, 0.5, 0.5}, {0.5, 0.55}}, Boxed -> False,
                                  PlotRange -> {{-20, 20}, {-20, 20}, {0, 20}}, Background -> Black],
                       {f, 0, 1, .01}];

Export["tree.gif", frames]

```

# Answer
> 61 votes
## Javascript

This is my first code golf!

```
var a=40,b=8,c=13,o="<div style='font-family:monospace;text-align:center;color:#094'>",w=1,x=0,y="|#|<br>";for(i=1;i<a;i++){for(j=0;j<w;j++){x%c==0?o+="<span style='color:#D00'>O</span>":o+="+";x++;}i%b==0?w-=4:w+=2;o+="<br>";}document.write(o+"<span style='color:#640'>"+y+y+y+"</span></div>");

```

It comes in at 295 Characters.

The size and decoration of the tree is set by the a,b,c variables:

* a sets the amount of rows in the tree
* b sets the amount of rows between decreases in width (set low for a skinny tree, high for a fat tree). Must be greater than or equal to 3.
* c sets the amount of baubles (set zero for none, 1 for only baubles, higher numbers for less dense placement of baubles)

It looks best when a is a multiple of b, as in the example.

Paste into the console to create a tree. Looks better from far away!

# Answer
> 61 votes
# Javascript

Quasirealistic fully 3D procedural fir tree generator.

Featuring: extensive configuration with even more configuration options present in code; a zigzagy trunk; branching branches; growth animation; rotation of a fully grown tree.

Not featuring: jQuery, Underscore.js or any other library; hardware dependency - only canvas support is required; messy code (at least that was the intention)

**Live page:** http://fiddle.jshell.net/honnza/NMva7/show/

**Edit page:** http://jsfiddle.net/honnza/NMva7/

**screenshot:**

**HTML:**

```
<canvas id=c width=200 height=300 style="display:none"></canvas>
<div id=config></div>

```

**Javascript:**

```
var TAU = 2*Math.PI,
    deg = TAU/360,

    TRUNK_VIEW      = {lineWidth:3, strokeStyle: "brown", zIndex: 1},
    BRANCH_VIEW     = {lineWidth:1, strokeStyle: "green", zIndex: 2},
    TRUNK_SPACING   = 1.5,
    TRUNK_BIAS_STR  = -0.5,
    TRUNK_SLOPE     = 0.25,
    BRANCH_LEN      = 1,
    BRANCH_P        = 0.01,
    MIN_SLOPE       = -5*deg,
    MAX_SLOPE       = 20*deg,
    INIT_SLOPE      = 10*deg,
    MAX_D_SLOPE     =  5*deg,
    DIR_KEEP_BIAS   = 10,
    GROWTH_MSPF     = 10, //ms per frame
    GROWTH_TPF      = 10, //ticks per frame
    ROTATE_MSPF     = 10,
    ROTATE_RPF      = 1*deg; //radians per frame

var configurables = [
//    {key: "TRUNK_SPACING", name: "Branch spacing", widget: "number",
//     description: "Distance between main branches on the trunk, in pixels"},
    {key: "TRUNK_BIAS_STR", name: "Branch distribution", widget: "number",
     description: "Angular distribution between nearby branches. High values tend towards one-sided trees, highly negative values tend towards planar trees. Zero means that branches grow in independent directions."},
    {key: "TRUNK_SLOPE", name: "Trunk slope", widget: "number",
     description: "Amount of horizontal movement of the trunk while growing"},
    {key: "BRANCH_P", name: "Branch frequency", widget: "number",
     description: "Branch frequency - if =1/100, a single twig will branch off approximately once per 100 px"},
    {key: "MIN_SLOPE", name: "Minimum slope", widget: "number", scale: deg,
     description: "Minimum slope of a branch, in degrees"},
    {key: "MAX_SLOPE", name: "Maximum slope", widget: "number", scale: deg,
     description: "Maximum slope of a branch, in degrees"},
    {key: "INIT_SLOPE", name: "Initial slope", widget: "number", scale: deg,
     description: "Angle at which branches leave the trunk"},
    {key: "DIR_KEEP_BIAS", name: "Directional inertia", widget: "number",
     description: "Tendency of twigs to keep their horizontal direction"},
    {get: function(){return maxY}, set: setCanvasSize, name: "Tree height",
     widget:"number"}
    ];

var config = document.getElementById("config"),
    canvas = document.getElementById("c"),
    maxX   = canvas.width/2,
    maxY   = canvas.height,
    canvasRatio = canvas.width / canvas.height,
    c;

function setCanvasSize(height){
    if(height === 'undefined') return maxY;
    maxY = canvas.height = height;
    canvas.width = height * canvasRatio;
    maxX = canvas.width/2;
x}

var nodes = [{x:0, y:0, z:0, dir:'up', isEnd:true}], buds = [nodes[0]],
    branches = [],
    branch,
    trunkDirBias = {x:0, z:0};

////////////////////////////////////////////////////////////////////////////////

configurables.forEach(function(el){
    var widget;
    switch(el.widget){
        case 'number':
            widget = document.createElement("input");
            if(el.key){
                widget.value = window[el.key] / (el.scale||1);
                el.set = function(value){window[el.key]=value * (el.scale||1)};
            }else{
                widget.value = el.get();
            }
            widget.onblur = function(){
                el.set(+widget.value);
            };
            break;
        default: throw "unknown widget type";
    }
    var p = document.createElement("p");
    p.textContent = el.name + ": ";
    p.appendChild(widget);
    p.title = el.description;
    config.appendChild(p);
});
var button = document.createElement("input");
button.type = "button";
button.value = "grow";
button.onclick = function(){
    button.value = "stop";
    button.onclick = function(){clearInterval(interval)};
    config.style.display="none";
    canvas.style.display="";
    c=canvas.getContext("2d");
    c.translate(maxX, maxY);
    c.scale(1, -1);
    interval = setInterval(grow, GROWTH_MSPF);
}
document.body.appendChild(button);
function grow(){
    for(var tick=0; tick<GROWTH_TPF; tick++){
        var budId = 0 | Math.random() * buds.length,
            nodeFrom = buds[budId], nodeTo, branch,
            dir, slope, bias

        if(nodeFrom.dir === 'up' && nodeFrom.isEnd){
            nodeFrom.isEnd = false;
            rndArg = Math.random()*TAU;
            nodeTo = {
                x:nodeFrom.x + TRUNK_SPACING * TRUNK_SLOPE * Math.sin(rndArg),
                y:nodeFrom.y + TRUNK_SPACING,
                z:nodeFrom.z + TRUNK_SPACING * TRUNK_SLOPE * Math.cos(rndArg),
                dir:'up', isEnd:true}
            if(nodeTo.y > maxY){
                console.log("end");
                clearInterval(interval);
                rotateInit();
                return;
            }
            nodes.push(nodeTo);
            buds.push(nodeTo);
            branch = {from: nodeFrom, to: nodeTo, view: TRUNK_VIEW};
            branches.push(branch);
            renderBranch(branch);
        }else{ //bud is not a trunk top
            if(!(nodeFrom.dir !== 'up' && Math.random() < BRANCH_P)){
                buds.splice(buds.indexOf(nodeFrom), 1)
            }
            nodeFrom.isEnd = false;
            if(nodeFrom.dir === 'up'){
                bias = {x:trunkDirBias.x * TRUNK_BIAS_STR,
                        z:trunkDirBias.z * TRUNK_BIAS_STR};
                slope = INIT_SLOPE;
            }else{
                bias = {x:nodeFrom.dir.x * DIR_KEEP_BIAS,
                        z:nodeFrom.dir.z * DIR_KEEP_BIAS};
                slope = nodeFrom.slope;
            }
            var rndLen = Math.random(),
                rndArg = Math.random()*TAU;
            dir = {x: rndLen * Math.sin(rndArg) + bias.x,
                   z: rndLen * Math.cos(rndArg) + bias.z};
            var uvFix = 1/Math.sqrt(dir.x*dir.x + dir.z*dir.z);
            dir = {x:dir.x*uvFix, z:dir.z*uvFix};
            if(nodeFrom.dir === "up") trunkDirBias = dir;
            slope += MAX_D_SLOPE * (2*Math.random() - 1);
            if(slope > MAX_SLOPE) slope = MAX_SLOPE;
            if(slope < MIN_SLOPE) slope = MIN_SLOPE;
            var length = BRANCH_LEN * Math.random();
            nodeTo = {
                x: nodeFrom.x + length * Math.cos(slope) * dir.x,
                y: nodeFrom.y + length * Math.sin(slope),
                z: nodeFrom.z + length * Math.cos(slope) * dir.z,
                dir: dir, slope: slope, isEnd: true
            }
            //if(Math.abs(nodeTo.x)/maxX + nodeTo.y/maxY > 1) return;
            nodes.push(nodeTo);
            buds.push(nodeTo);
            branch = {from: nodeFrom, to: nodeTo, view: BRANCH_VIEW};
            branches.push(branch);
            renderBranch(branch);
        }// end if-is-trunk
    }// end for-tick
}//end func-grow

function rotateInit(){
    branches.sort(function(a,b){
        return (a.view.zIndex-b.view.zIndex);
    });
    interval = setInterval(rotate, ROTATE_MSPF);
}

var time = 0;
var view = {x:1, z:0}
function rotate(){
    time++;
    view = {x: Math.cos(time * ROTATE_RPF),
            z: Math.sin(time * ROTATE_RPF)};
    c.fillStyle = "white"
    c.fillRect(-maxX, 0, 2*maxX, maxY);
    branches.forEach(renderBranch);
    c.stroke();
    c.beginPath();
}

var prevView = null;
function renderBranch(branch){
    if(branch.view !== prevView){
        c.stroke();
        for(k in branch.view) c[k] = branch.view[k];
        c.beginPath();
        prevView = branch.view;
    }
    c.moveTo(view.x * branch.from.x + view.z * branch.from.z,
             branch.from.y);
    c.lineTo(view.x * branch.to.x + view.z * branch.to.z,
             branch.to.y);
}

```

# Answer
> 59 votes
# C++

Let's make it in the spirit of IOCCC and have the code in the shape of a tree as well! :D

```
#include <iostream>
using namespace std;

               int
             main(){
              int a
                ;
               cin
             >>a;int
           w=a*2+5;for
             (int x=
           0;x<a;++x){
         for(int y=2;y>=
       0;--y){for(int z=0;
           z<a+y-x;++z
        ){cout<<" ";}for(
     int z=0;z<x*2-y*2+5;++z
        ){cout<<".";}cout
      <<endl;}}for(int x=0;
    x<w/5+1;++x){for(int z=0;
  z<w/3+1;++z){cout<<" ";}for(
int z=0;z<w-(w/3+1)*2;z+=1){cout
           <<"#";}cout
           <<endl;;;}}

```

Takes an integer as input, and returns a Christmas tree with that many "stack levels". For example, an input of

```
5

```

Returns:

```
       .
      ...
     .....
      ...
     .....
    .......
     .....
    .......
   .........
    .......
   .........
  ...........
   .........
  ...........
 .............
      ###
      ###
      ###
      ###

```

# Answer
> 49 votes
# Bash

Sample output:

The tree size (i.e. number of lines) is passed on the command line, and is limited to values of 5 or greater. The image above was produced from the command `./xmastree.sh 12`. Here's the source code:

```
#!/bin/bash
declare -a a=('.' '~' "'" 'O' "'" '~' '.' '*')
[[ $# = 0 ]] && s=9 || s=$1
[[ $s -gt 5 ]] || s=5
for (( w=1, r=7, n=1; n<=$s; n++ )) ; do
  for (( i=$s-n; i>0; i-- )) ;  do
    echo -n " "
  done
  for (( i=1; i<=w; i++ )) ; do
    echo -n "${a[r]}"
    [[ $r -gt 5 ]] && r=0 || r=$r+1
  done
  w=$w+2
  echo " "
done;
echo " "

```

# Answer
> 42 votes
Disclaimer: this is based on my LaTeX christmas tree, first posted here: https://tex.stackexchange.com/a/87921/8463

The following code will generate a chrismtas tree, with random decorations. You can change both the size of the tree, and the random seed to generate a different tree.

To change the seed modify the value inside `\pgfmathsetseed{\year * 6}` to any other numerical value (the default one will generate a new tree every year)

To change the size of the tree modify the `order=10` to be either larger, or smaller depending on the size of the tree you want.

Examples. `order=11`:

`order=8`

```
\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{calc, lindenmayersystems,shapes,decorations,decorations.shapes}
\begin{document}

\def\pointlistleft{}
\def\pointlistright{}
\pgfmathsetseed{\year * 6}

\makeatletter
\pgfdeclarelindenmayersystem{Christmas tree}{
    \symbol{C}{\pgfgettransform{\t} \expandafter\g@addto@macro\expandafter\pointlistleft\expandafter{\expandafter{\t}}}
    \symbol{c}{\pgfgettransform{\t} \expandafter\g@addto@macro\expandafter\pointlistright\expandafter{\expandafter{\t}}}
    \rule{S -> [+++G][---g]TS}
    \rule{G -> +H[-G]CL}
    \rule{H -> -G[+H]CL}
    \rule{g -> +h[-g]cL}
    \rule{h -> -g[+h]cL}
    \rule{T -> TL}
    \rule{L -> [-FFF][+FFF]F}
}
\makeatother

\begin{tikzpicture}[rotate=90]
\draw [color=green!50!black,l-system={Christmas tree,step=4pt,angle=16,axiom=LLLLLLSLFFF,order=10,randomize angle percent=20}] lindenmayer system -- cycle;

\pgfmathdeclarerandomlist{pointsleft}{\pointlistleft}
\pgfmathdeclarerandomlist{pointsright}{\pointlistright}
\pgfmathdeclarerandomlist{colors}{{red}{blue}{yellow}}

\foreach \i in {0,1,...,5}
{
    \pgfmathrandomitem{\c}{pointsleft}
    \pgfsettransform{\c}
    \pgfgettransformentries{\a}{\b}{\c}{\d}{\xx}{\yy}
    \pgfmathrandomitem{\c}{pointsright}
    \pgfsettransform{\c}
    \pgfgettransformentries{\a}{\b}{\c}{\d}{\XX}{\YY}
    \pgftransformreset

    \pgfmathsetmacro\calcy{min(\yy,\YY)-max((abs(\yy-\YY))/3,25pt)}

    \draw[draw=orange!50!black, fill=orange!50, decorate, decoration={shape backgrounds, shape=star, shape sep=3pt, shape size=4pt}, star points=5] (\xx,\yy) .. controls (\xx,\calcy pt) and (\XX,\calcy pt) .. (\XX,\YY);
}

\foreach \i in {0,1,...,15}
{
    \pgfmathrandomitem{\c}{pointsleft}
    \pgfsettransform{\c}
    \pgftransformresetnontranslations
    \draw[color=black] (0,0) -- (0,-4pt);
    \pgfmathrandomitem{\c}{colors}
    \shadedraw[ball color=\c] (0,-8pt) circle [radius=4pt];
}

\foreach \i in {0,1,...,15}
{
    \pgfmathrandomitem{\c}{pointsright}
    \pgfsettransform{\c}
    \pgftransformresetnontranslations
    \draw[color=black] (0,0) -- (0,-4pt);
    \pgfmathrandomitem{\c}{colors}
    \shadedraw[ball color=\c] (0,-8pt) circle [radius=4pt];
}

\end{tikzpicture}
\end{document}

```

# Answer
> 34 votes
# Befunge 93

This is an undecorated tree:

```
&::00p20pv
vp010    <
v              p00<
>:0`!#v_" ",1-
v,"/"$<
>10g:2+v
vp01   <
>:0`!#v_" ",1-
v,"\"$<
>91+,00g1-::0`!#v_^
v        *2+1g02<
>:0`!#v_"-",1-
v g02$<
>91+,v
v    <
>:0`!#v_" ",1-
"||"$ <@,,

```

Sample output, input is 10:

```
          /\
         /  \
        /    \
       /      \
      /        \
     /          \
    /            \
   /              \
  /                \
 /                  \
----------------------
          ||

```

Let's add some decorations:

```
&::00p20pv
vp010    <
v              p00<
>:0`!#v_" ",1-
v,"/"$<
>10g:2+v             >"O" v
vp01   <            >?v
>:0`!#v_           >?>>" ">,1-
v,"\"$<             >?<
>91+,00g1-::0`!#v_^  >"*" ^
v        *2+1g02<
>:0`!#v_"-",1-
v g02$<
>91+,v
v    <
>:0`!#v_" ",1-
"||"$ <@,,

```

Sample output:

```
          /\
         /O \
        /    \
       /   ** \
      /     *  \
     /    **   O\
    /* O* *  *   \
   / O      O     \
  / *  **   O*     \
 /   *OO   *  OOO * \
----------------------
          ||

```

# Answer
> 32 votes
# Java

```
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Toolkit;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

/**
 *
 * @author Quincunx
 */
public class ChristmasTree {
    public static double scale = 1.2;

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new ChristmasTree();
            }
        });
    }

    public ChristmasTree() {
        try {
            URL url = new URL("http://imgs.xkcd.com/comics/tree.png");
            BufferedImage img = ImageIO.read(url);

            JFrame frame = new JFrame();
            frame.setUndecorated(true);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            Dimension d = Toolkit.getDefaultToolkit().getScreenSize();

            BufferedImage result =
                    new BufferedImage((int)(img.getWidth() * scale),
                            (int) (img.getHeight() * scale),
                            BufferedImage.TYPE_INT_RGB);
            Graphics2D g = (Graphics2D) result.getGraphics();
            g.drawRenderedImage(img, AffineTransform.getScaleInstance(scale, scale));

            JImage image = new JImage(result);
            image.setToolTipText("Not only is that terrible in general, but you "
                    + "just KNOW Billy's going to open the root present first, "
                    + "and then everyone will have to wait while the heap is "
                    + "rebuilt.");
            frame.add(image);
            frame.pack();
            frame.setVisible(true);

        } catch (IOException ex) {

        }
    }

    class JImage extends JPanel implements MouseListener {

        BufferedImage img;

        public JImage(){
            this(null);
        }
        public JImage(BufferedImage image){
            img = image;
            setPreferredSize(new Dimension(image.getWidth(), image.getHeight()));
            addMouseListener(this);
        }

        @Override
        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            g.drawImage(img, WIDTH, WIDTH, this);
        }

        public void setImage(BufferedImage image) {
            img = image;
            repaint();
        }

        @Override
        public void mouseClicked(MouseEvent me) {
            System.exit(0);
        }

        @Override
        public void mousePressed(MouseEvent me) {

        }

        @Override
        public void mouseReleased(MouseEvent me) {

        }

        @Override
        public void mouseEntered(MouseEvent me) {

        }

        @Override
        public void mouseExited(MouseEvent me) {

        }
    }
}

```

To alter the size, change `scale` to some other double value (keep it around 1 if you want to see anything).

Sample output (for 1.0 as scale, too lazy to take a screenshot, so just posted what it does):

The program takes this image from the internet, resizes it according to `scale`, then puts it in an undecorated window where it is displayed. Clicking on the window closes the program. Also, the tool tip text is there, but the link is not.

# Answer
> 32 votes
# HTML and CSS

```
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Scalable christmas tree</title>
<style>
body {
  background-color: skyblue;
  background-size: 11px 11px, 21px 21px, 31px 31px;
  background-image: radial-gradient(circle at 5px 5px,white,rgba(255,255,255,0) 1px), radial-gradient(circle at 5px 5px,white,rgba(255,255,255,0) 2px), radial-gradient(circle at 5px 5px,white 1px,skyblue 1px);
}
div {
  float: left;
  border-style: solid;
  border-color: transparent;
  border-bottom-color: green;
  border-width: 20px;
  border-top-width: 0;
  border-bottom-width: 30px;
  border-bottom-left-radius: 35%;
  border-bottom-right-radius: 35%;
  box-shadow: red 0 15px 5px -13px;
  animation-name: light;
  animation-duration: 1s;
  animation-direction: alternate;
  animation-iteration-count: infinite;
  -webkit-animation-name: light;
  -webkit-animation-duration: 1s;
  -webkit-animation-direction: alternate;
  -webkit-animation-iteration-count: infinite;
}
section {
  float: left;
}
header {
  color: yellow;
  font-size: 30px;
  text-align: center;
  text-shadow: red 0 0 10px;
  line-height: .5;
  margin-top: 10px;
  animation-name: star;
  animation-duration: 1.5s;
  animation-direction: alternate;
  animation-iteration-count: infinite;
  -webkit-animation-name: star;
  -webkit-animation-duration: 1.5s;
  -webkit-animation-direction: alternate;
  -webkit-animation-iteration-count: infinite;
}
footer {
  float: left;
  width: 100%;
  height: 20px;
  background-image: linear-gradient(to right, transparent 45%, brown 45%, #600 48%, #600 52%, brown 55%, transparent 55%);
}
:target {
  display: none;
}
@keyframes star {
  from { text-shadow: red 0 0 3px; }
  to { text-shadow: red 0 0 30px; }
}
@-webkit-keyframes star {
  from { text-shadow: red 0 0 3px; }
  to { text-shadow: red 0 0 30px; }
}
@keyframes light {
  from { box-shadow: red 0 15px 5px -13px; }
  to { box-shadow: blue 0 15px 5px -13px; }
}
@-webkit-keyframes light {
  from { box-shadow: red 0 15px 5px -13px; }
  to { box-shadow: blue 0 15px 5px -13px; }
}
</style>
</head>
<body>
<section>
<header>★</header>
<div id="0"><div id="1"><div id="2"><div id="3"><div id="4"><div id="5"><div id="6"><div id="7"><div id="8"><div id="9"><div id="10"><div id="11"><div id="12"><div id="13"><div id="14"><div id="15"><div id="16"><div id="17"><div id="18"><div id="19"><div id="20"><div id="21"><div id="22"><div id="23"><div id="24">
</div></div></div></div></div></div></div></div></div></div></div></div></div></div></div></div></div></div></div></div></div></div></div></div></div>
<footer></footer>
</section>
</body>
</html>

```

Sizes between 1 and 25 are supported – just add the size to the URL as fragment identifier.

Works in Chrome, Explorer and Firefox. In Opera is ugly, but the scaling part works.

Sample access:

```
http://localhost/xmas.html#5

```

Sample access:

```
http://localhost/xmas.html#15

```

Live view:

http://dabblet.com/gist/8026898

(The live view contains no vendor prefixed CSS and includes links to change the size.)

# Answer
> 28 votes
# TI-89 Basic

Just because I wanted to see a Christmas Tree on my calculator. I shall type it here as it appears on my calculator.

```
:tree()
:Prgm
:
:Local size
:Prompt size
:
:Local d,x,y,str,orn
:size→x
:0→y
:{" "," "," "," "," "," "," "," ","°","∫","θ","O","©"}→orn
:size→d
:
:While d≥0
: d-1→d
: ""→str
:
: While x≥0
:  str&" "→str
:  x-1→x
: EndWhile
:
: str&"/"→str
: 2*y→x
:
: While x>0
:  str&elementAt(orn,rand(colDim(list▶mat(orn))))→str
:  x-1→x
: EndWhile
:
: str&"\"→str
: Disp str
: y+1→y
: d→x
:EndWhile
:
:""→str
:
:For x,1,2*(size+2)
: str&"-"→str
:EndFor
:Disp str
:
:""→str
:For x,1,size+1
: str&" "→str
:EndFor
:str&"||"→str
:Disp str
:
:EndPrgm

:elementAt(l,i)
:Func
:Local m
:list▶mat(l)→m
:
:Local cd
:colDim(m)→cd
:
:If i>cd or i≤0 Then
: 1/0
:Else
: If i=cd Then
:  Return sum(mat▶list(subMat(m,1,i))) - sum(mat▶list(subMat(m,1,i+1)))
: Else
:  Return sum(mat▶list(subMat(m,1,i))) - sum(mat▶list(subMat(m,1,i+1)))
: EndIf
:EndIf
:EndFunc

```

This works the same way as my Befunge answer, but I use different ornaments. Yes, my `elementAt` function's repeated uses slows the program down because of many conversions between lists and matrices, but as I wrote it before, I decided against editing it. Also, I learned while typing this answer that `©` makes a comment (I thought it looked like `@`, but that is another character). Never knew what it was before now.

Sample output:

```
size?
7
        /\
       / O\
      /∫   \
     / ©  ∫°\
    / θ ∫   ∫\
   /°  °  ©  ©\
  /O  ∫  O °   \
 / θ  °©  ∫ O  θ\
------------------
        ||

```

I love those 's; they look like candy canes.

# Answer
> 26 votes
# Wolfram Language ( *Mathematica* )

As discussed at famed Reddit thread: t\*sin (t) ≈ Christmas tree

```
PD = .5; s[t_, f_] := t^.6 - f;
 dt[cl_, ps_, sg_, hf_, dp_, f_] :=
    {PointSize[ps], Hue[cl, 1, .6 + sg .4 Sin[hf s[t, f]]],
     Point[{-sg s[t, f] Sin[s[t, f]], -sg s[t, f] Cos[s[t, f]], dp + s[t, f]}]};

 frames = ParallelTable[

    Graphics3D[Table[{dt[1, .01, -1, 1, 0, f], dt[.45, .01, 1, 1, 0, f],
                      dt[1, .005, -1, 4, .2, f], dt[.45, .005, 1, 4, .2, f]},
 {t, 0, 200, PD}],

     ViewPoint -> Left, BoxRatios -> {1, 1, 1.3}, ViewVertical -> {0, 0, -1},
    ViewCenter -> {{0.5, 0.5, 0.5}, {0.5, 0.55}}, Boxed -> False, Lighting -> "Neutral",
    PlotRange -> {{-20, 20}, {-20, 20}, {0, 20}}, Background -> Black],

   {f, 0, 1, .01}];

Export["tree.gif", frames]

```

# Answer
> 24 votes
# Bash with Bc and ImageMagick

```
#!/bin/bash

size="${1:-10}"

width=$(( size*25 ))
height=$(( size*size+size*10 ))

cos=( $( bc -l <<< "for (i=0;i<3.14*2;i+=.05) c(i)*100" ) )
sin=( $( bc -l <<< "for (i=0;i<3.14*2;i+=.05) s(i)*100" ) )
cos=( "${cos[@]%.*}" )
sin=( "${sin[@]%.*}" )

cos=( "${cos[@]/%-/0}" )
sin=( "${sin[@]/%-/0}" )

snow=()
needle=()
decor=()
for ((i=2;i<size+2;i++)); do
  for ((j=3;j<=31;j++)); do
    (( x=width/2+i*10+cos[62-j]*i*10/100 ))
    (( y=i*i+sin[j]*i*5/100 ))

    for ((e=0;e<i;e++)); do
      needle+=(
        -draw "line $x,$y $(( x+RANDOM%i-i/2 )),$(( y+RANDOM%i-i/2 ))"
        -draw "line $(( width-x )),$y $(( width-x+RANDOM%i-i/2 )),$(( y+RANDOM%i-i/2 ))"
      )
    done

    (( RANDOM%2 )) && (( x=width-x ))
    snow+=(
      -draw "circle $x,$(( y-i/2 )) $(( x+i/3 )),$(( y-i/2+i/3 ))"
    )

    (( RANDOM%10 )) || decor+=(
      -fill "rgb($(( RANDOM%5*20+50 )),$(( RANDOM%5*20+50 )),$(( RANDOM%5*20+50 )))"
      -draw "circle $x,$(( y+i )) $(( x+i/2 )),$(( y+i+i/2 ))"
    )
  done
done

flake=()
for ((i=0;i<width*height/100;i++)); do
  flake+=(
    -draw "point $(( RANDOM%width )),$(( RANDOM%height ))"
  )
done

convert \
  -size "${width}x$height" \
  xc:skyblue \
  -stroke white \
  -fill white \
  "${snow[@]}" \
  -blur 5x5 \
  "${flake[@]}" \
  -stroke brown \
  -fill brown \
  -draw "polygon $(( width/2 )),0 $(( width/2-size )),$height, $(( width/2+size )),$height" \
  -stroke green \
  -fill none \
  "${needle[@]}" \
  -stroke none \
  -fill red \
  "${decor[@]}" \
  x:

```

Sample run:

```
bash-4.1$ ./xmas.sh 5

```

Sample output:

Sample run:

```
bash-4.1$ ./xmas.sh 15

```

Sample output:

# Answer
> 22 votes
**C**

Sample output for depth=4, zoom=2.0

This answer employs an approach quite different from other answers. It generates a tree structure by recursively branching. Each branch is represented by a set of circles. And finally the main function samples the circles and fill with characters when circles are met. Since it is done by sampling a scene (like ray-tracing), it is intrinsically scalable. The downside is speed, since it traverse the whole tree structure for every "pixel"!

The first command-line argument controls the depth of branching. And the second controls scale (2 means 200%).

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

#define PI 3.14159265359

float sx, sy;

float sdCircle(float px, float py, float r) {
    float dx = px - sx, dy = py - sy;
    return sqrtf(dx * dx + dy * dy) - r;
}

float opUnion(float d1, float d2) {
    return d1 < d2 ? d1 : d2;
}

#define T px + scale * r * cosf(theta), py + scale * r * sin(theta)

float f(float px, float py, float theta, float scale, int n) {
    float d = 0.0f;
    for (float r = 0.0f; r < 0.8f; r += 0.02f)
        d = opUnion(d, sdCircle(T, 0.05f * scale * (0.95f - r)));

    if (n > 0)
        for (int t = -1; t <= 1; t += 2) {
            float tt = theta + t * 1.8f;
            float ss = scale * 0.9f;
            for (float r = 0.2f; r < 0.8f; r += 0.1f) {
                d = opUnion(d, f(T, tt, ss * 0.5f, n - 1));
                ss *= 0.8f;
            }
        }

    return d;
}

int ribbon() {
    float x = (fmodf(sy, 0.1f) / 0.1f - 0.5f) * 0.5f;
    return sx >= x - 0.05f && sx <= x + 0.05f;
}

int main(int argc, char* argv[]) {
    int n = argc > 1 ? atoi(argv[1]) : 3;
    float zoom = argc > 2 ? atof(argv[2]) : 1.0f;
    for (sy = 0.8f; sy > 0.0f; sy -= 0.02f / zoom, putchar('\n'))
        for (sx = -0.35f; sx < 0.35f; sx += 0.01f / zoom) {
            if (f(0, 0, PI * 0.5f, 1.0f, n) < 0.0f) {
                if (sy < 0.1f)
                    putchar('.');
                else {
                    if (ribbon())
                        putchar('=');
                    else
                        putchar("............................#j&o"[rand() % 32]);
                }
            }
            else
                putchar(' ');
        }
}

```

# Answer
> 20 votes
# Mathematica ASCII

I really like ASCII art, so I add another very different answer - especially so it's so short in Mathematica:

```
Column[Table[Row[RandomChoice[{"+", ".", "*", "~", "^", "o"}, k]], {k, 1, 35, 2}],
Alignment -> Center]

```

And now with a bit more sophistication a scalable dynamic ASCII tree. Watch closely - the tree is also changing - snow sticks to branches then falls ;-)

```
DynamicModule[{atoms, tree, pos, snow, p = .8, sz = 15},

 atoms = {
   Style["+", White],
   Style["*", White],
   Style["o", White],
   Style[".", Green],
   Style["~", Green],
   Style["^", Green],
   Style["^", Green]
   };

 pos = Flatten[Table[{m, n}, {m, 18}, {n, 2 m - 1}], 1];

 tree = Table[RandomChoice[atoms, k], {k, 1, 35, 2}];

 snow = Table[
   RotateLeft[ArrayPad[{RandomChoice[atoms[[1 ;; 2]]]}, {0, sz}, " "],
     RandomInteger[sz]], {sz + 1}];

 Dynamic[Refresh[

   Overlay[{

     tree[[Sequence @@ RandomChoice[pos]]] = RandomChoice[atoms];
     Column[Row /@ tree, Alignment -> Center, Background -> Black],

     Grid[
      snow =
       RotateRight[
        RotateLeft[#,
           RandomChoice[{(1 - p)/2, p, (1 - p)/2} -> {-1, 0, 1}]] & /@
          snow
        , {1, 0}]]

     }, Alignment -> Center]

   , UpdateInterval -> 0, TrackedSymbols -> {}]
  ]
 ]

```

# Answer
> 19 votes
I made this for a challenge on /r/dailyprogrammer, (not sure if reusing code is against the spirit/rules of this) but:

Brainfuck. Takes as input a number (length of bottom row of leaves) and two characters. One space between each.

Example input: 13 = +

Example output:

```
      +
     +++
    +++++
   +++++++
  +++++++++
 +++++++++++
+++++++++++++
     ===

```

Code:

```
                   >
                  ,--
                 -----
                -------
               ---------
              ---------[+
             +++++++++++++
            +++++++++++++++
           +++<[>>++++++++++
          <<-]>--------------
         ---------------------
        -------------[<+>-]>[<<
       +>>-]<,------------------
      --------------],>,,>>++++[<
     ++++++++>-]++++++++++>+<<<<<-
    [>>>>>>+>+<<<<<<<--]>>>>>>>[<<<
   <<<<++>>>>>>>-]<<<<<<<[>>>>>>[<<<
  .>>>>+<-]>[<+>-]<<[<<<.>>>>>+<<-]>>
 [<<+>>-]<<<.>>><-<++<<<<<--]>>...>>>-
--[>+<<<<..>>>--]<.>>[<<<.>>>>+<-]<<<<<
                ...>>>.

```

# Answer
> 16 votes
## Processing

The original fractal Christmas tree. Mouse Y position determines size, use up and down arrow keys to change the number of generations.

```
int size = 500;

int depth = 10;

void setup() {
  frameRate(30);
  size(size, size, P2D);
}

void draw() {
  background(255);
  tree(size/2.0, size, 0.0, radians(0), radians(108), (size - mouseY)/3, depth);
  tree(size/2.0, size, 0.0, radians(108), radians(0), (size - mouseY)/3, depth);
}

void keyPressed() {
  if(keyCode == UP) depth++;
  if(keyCode == DOWN) depth--;
  depth = max(depth, 1);
}

void tree(float posX, float posY, float angle, float forkRight, float forkLeft, float length, int generation) {
  if (generation > 0) {
    float nextX = posX + length * sin(angle);
    float nextY = posY - length * cos(angle);

    line(posX, posY, nextX, nextY);

    tree(nextX, nextY, angle + forkRight, forkRight, forkLeft, length*0.6, generation - 1);
    tree(nextX, nextY, angle - forkLeft,  forkRight, forkLeft, length*0.6, generation - 1);
  }
}

```

```
Or, if you prefer a fuller tree:

int size = 500;

int depth = 10;

void setup() {
  frameRate(30);
  size(size, size, P2D);
}

void draw() {
  background(255);
  tree(size/2.0 - 5, size, 0.0, 0.0, (size - mouseY)/3, depth);
}

void keyPressed() {
  if(keyCode == UP) depth++;
  if(keyCode == DOWN) depth--;
  depth = max(depth, 1);
}

void tree(float posX, float posY, float angle, float fork, float length, int generation) {
  if (generation > 0) {
    float nextX = posX + length * sin(angle);
    float nextY = posY - length * cos(angle);

    line(posX, posY, nextX, nextY);

    tree(nextX, nextY, angle + fork + radians(108), fork, length*0.6, generation - 1);
    tree(nextX, nextY, angle - fork,                fork, length*0.6, generation - 1);
    tree(nextX, nextY, angle + fork - radians(108), fork, length*0.6, generation - 1);
  }
}

```

# Answer
> 14 votes
# Ruby

```
((1..20).to_a+[6]*4).map{|i|puts ('*'*i*2).center(80)}

```

You can customize output by changing `*`.
For a green tree: `((1..20).to_a+[6]*4).map{|i|puts "\e[32m"+('*'*i*2).center(80)}`

**Approach 2** (Xmas tree that doesn't look like an arrow)

```
((1..6).to_a+(3..9).to_a+(6..12).to_a+[3]*4).map{|i|puts "\e[32m"+('*'*i*4).center(80)}

```

**Approach 3**

```
((1..20).to_a+[6]*4).map{|i|puts' '*(20-i)+'*'*(2*i-1)}

```

# Answer
> 14 votes
## Processing

I made this tree generator using an L-System and a Turtle.

code:

```
//My code, made from scratch:
final int THE_ITERATIONS = 7;
final float SCALE = 1;
final int ANGLE = 130;
final int SIZE = 4;

final int ITERATIONS = THE_ITERATIONS - 1;

int lineLength;

String lSystem;
ArrayList<Turtle> turtles;

int turtleIndex;
int lSystemIndex;

void setup()
{
  size(320, 420);
  background(255);
  translate(width / 2, height - 70);

  lineLength = ITERATIONS * 2 + 2;

  lSystem = "[-F][+F]F";

  turtles = new ArrayList<Turtle>(ITERATIONS + 1);
  lSystemIndex = 0;

  calculateLSystem();
  println(lSystem);

  turtles.add(new Turtle(0, 0));

  doTurtles();
  save("Tree.png");
}

void doTurtles()
{
  while(lSystemIndex < lSystem.length())
  {
    print("\"" + lSystem.charAt(lSystemIndex) + "\": ");
    if(lSystem.charAt(lSystemIndex) == 'F')
    {
      turtleForward();
    }
    else if(lSystem.charAt(lSystemIndex) == '[')
    {
      lineLength -= 2;
      addTurtle();
      println(turtles.size());
    }
    else if(lSystem.charAt(lSystemIndex) == ']')
    {
      lineLength += 2;
      removeTurtle();
      println(turtles.size());
    }
    else if(lSystem.charAt(lSystemIndex) == '+')
    {
      turtleRight();
    }
    else if(lSystem.charAt(lSystemIndex) == '-')
    {
      turtleLeft();
    }
    lSystemIndex++;
  }
}

void addTurtle()
{
  turtles.add(new Turtle(turtles.get(turtles.size() - 1)));
}

void removeTurtle()
{
  turtles.remove(turtles.size() - 1);
}

void turtleLeft()
{
  turtles.get(turtles.size() - 1).left(ANGLE + random(-5, 5));
}

void turtleRight()
{
  turtles.get(turtles.size() - 1).right(ANGLE + random(-5, 5));
}

void turtleForward()
{
  print(turtles.get(turtles.size() - 1) + ": ");
  strokeWeight(min(lineLength / SIZE, 1));
  stroke(5 + random(16), 90 + random(16), 15 + random(16));
  if(turtles.size() == 1)
  {
    strokeWeight(lineLength / 2);
    stroke(100, 75, 25);
  }
  turtles.get(turtles.size() - 1).right(random(-3, 3));
  turtles.get(turtles.size() - 1).forward(lineLength);
}

void calculateLSystem()
{
  for(int i = 0; i < ITERATIONS; i++)
  {
    lSystem = lSystem.replaceAll("F", "F[-F][+F][F]");
  }
  lSystem = "FF" + lSystem;
}

void draw()
{

}

//——————————————————————————————————————————————————————
// Turtle code, heavily based on code by Jamie Matthews
// http://j4mie.org/blog/simple-turtle-for-processing/
//——————————————————————————————————————————————————————

class Turtle {
  float x, y; // Current position of the turtle
  float angle = -90; // Current heading of the turtle
  boolean penDown = true; // Is pen down?
  int lineLength;

  // Set up initial position
  Turtle (float xin, float yin) {
    x = xin;
    y = yin;
    //lineLength = lineLengthin;
  }

  Turtle (Turtle turtle) {
    x = turtle.x;
    y = turtle.y;
    angle = turtle.angle;
    //lineLength = turtle.lineLength - 1;
  }

  // Move forward by the specified distance
  void forward (float distance) {
    distance = distance * SIZE * random(0.9, 1.1);
    // Calculate the new position
    float xtarget = x+cos(radians(angle)) * distance;
    float ytarget = y+sin(radians(angle)) * distance;

    // If the pen is down, draw a line to the new position
    if (penDown) line(x, y, xtarget, ytarget);
    println(x + ", " + y + ", " + xtarget + ", " + ytarget);
    // Update position
    x = xtarget;
    y = ytarget;
  }

  // Turn left by given angle
  void left (float turnangle) {
    angle -= turnangle;
    println(angle);
  }

  // Turn right by given angle
  void right (float turnangle) {
    angle += turnangle;
    println(angle);
  }
}

```

# Answer
> 14 votes
# Turtle Graphics

Based on properties of the Euler spiral.

Code:

The scale is determined by the step size (`move forward by: 6`). An interactive version is available here.

P.S. Inspired by this question.

# Answer
> 12 votes
# JavaScript (run on any page in console)

I was golfing this but then decided not to, so as you can see there are TONS of magic numbers :P

```
// size
s = 300

document.write('<canvas id=c width=' + s + ' height=' + s + '>')
c = document.getElementById('c').getContext('2d')
c.fillStyle = '#0D0'
for (var i = s / 3; i <= s / 3 * 2; i += s / 6) {
  c.moveTo(s / 2, s / 10)
  c.lineTo(s / 3, i)
  c.lineTo(s / 3 * 2, i)
  c.fill()
}
c.fillStyle = '#DA0'
c.fillRect(s / 2 - s / 20, s / 3 * 2, s / 10, s / 6)

```

Result for s = 300:

s = 600:

# Answer
> 10 votes
## Game Maker Language

**spr\_tree**

**The tree's Create Event**

```
image_speed=0
size=get_integer("How big do you want me to be?#Integer between 1 and 10, please!",10)
image_index=size-1

```

**Room, 402 by 599**

The tree is placed at `(0,0)`

**Bonus!** You can resize the Christmas tree after the initial input with the keys 0-9.

# Answer
> 8 votes
# AppleScript + SE Answer

Actually picked this up by accident while editing an answer in this question. Go figure.

Use this by running the code, typing in your number that you want, swiping over to the SE post and clicking in the text field. This exploits the fact that quotes stack.

```
tell application "System Events"
    set layers to (display dialog "" default answer "")'s text returned as number
    delay 5
    repeat layers times
        keystroke ">"
    end repeat
end tell
```

Output (input 50):

> > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > \>

# Answer
> 6 votes
## Decorated FORTRAN tree

```
    character(len=36) :: f='/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\'
    character(len=18) :: g = '                  '
    character(len=14) :: p = ".x$.+oO+oO.#,~"
    character(len=10) :: q

    n = iargc()
    if (n /= 1) then
        k = len(g)
    else
        call getarg(1,q)
        read(q,*) k
    end if
    l = modulo(k,len(g))+1
    do i=1,l
        j = mod(i,len(p)-1)+1
        print *,g(1:l-i),p(j:j),f(1:2*i),p(j+1:J+1)
        end do
    print *,g(1:l-1),f(1:4)
    end

```

The tree has a limited range of sizes, but it believe it accurately reflects the life of most Christmas trees.

From infant tree:

```
$./tree
 x/\$
 /\/\

```

To adolescent tree:

```
$./tree 6
       x/\$
      $/\/\.
     ./\/\/\+
    +/\/\/\/\o
   o/\/\/\/\/\O
  O/\/\/\/\/\/\+
 +/\/\/\/\/\/\/\o
       /\/\

```

To adult:

```
$./tree 17
                  x/\$
                 $/\/\.
                ./\/\/\+
               +/\/\/\/\o
              o/\/\/\/\/\O
             O/\/\/\/\/\/\+
            +/\/\/\/\/\/\/\o
           o/\/\/\/\/\/\/\/\O
          O/\/\/\/\/\/\/\/\/\.
         ./\/\/\/\/\/\/\/\/\/\#
        #/\/\/\/\/\/\/\/\/\/\/\,
       ,/\/\/\/\/\/\/\/\/\/\/\/\~
      ./\/\/\/\/\/\/\/\/\/\/\/\/\x
     x/\/\/\/\/\/\/\/\/\/\/\/\/\/\$
    $/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\.
   ./\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\+
  +/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\o
 o/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\O
                  /\/\

```

# Answer
> 5 votes
# Java

```
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.*;

import javax.imageio.ImageIO;

public class ChristmasTree {
    static class Point{
        Point(int a,int b){x=a;y=b;}
        int x,y;
        double distance(Point o){
            int dx=x-o.x;
            int dy=y-o.y;
            return Math.sqrt(dx*dx+dy*dy);
        }
    }
    static int siz;
    static BufferedImage b;
    static Random r=new Random();
    public static void main(String[]args) throws IOException{

        if(args.length==0){
            siz=(new Scanner(System.in)).nextInt();
        }else{
            siz=Integer.parseInt(args[0]);
        }
        b=new BufferedImage(20*siz,30*siz,BufferedImage.TYPE_INT_RGB);
        Graphics2D g=(Graphics2D)b.getGraphics();
        g.setColor(new Color(140,70,20));
        int h=b.getHeight();h*=0.4;
        for(int i=(int)(0.4*b.getWidth());i<(int)(0.6*b.getWidth());i++){
            if(r.nextDouble()<0.3){
                g.drawLine(i,b.getHeight(),i+r.nextInt(2)-1,h);
            }
        }
        for(int i=h;i<b.getHeight();i++){
            if(r.nextDouble()<0.3){
                g.drawLine((int)(0.4*b.getWidth()),i,(int)(0.6*b.getWidth()),i);
            }
        }
        for(int i=0;i<siz;i++){
            g.setColor(new Color(r.nextInt(4),150+r.nextInt(15),20+r.nextInt(7)));
            g.drawLine(b.getWidth()/2-(int)(b.getWidth()*0.42*i/siz),(int)(b.getHeight()*0.9)+r.nextInt(5)-2,b.getWidth()/2+(int)(b.getWidth()*0.42*i/siz),(int)(b.getHeight()*0.9)+r.nextInt(5)-2);
            g.setColor(new Color(r.nextInt(4),150+r.nextInt(15),20+r.nextInt(7)));
            g.drawLine(b.getWidth()/2-(int)(b.getWidth()*0.42*i/siz),(int)(b.getHeight()*0.9),b.getWidth()/2,(int)(b.getHeight()*(0.1+(.06*i)/siz)));
            g.setColor(new Color(r.nextInt(4),150+r.nextInt(15),20+r.nextInt(7)));
            g.drawLine(b.getWidth()/2+(int)(b.getWidth()*0.42*i/siz),(int)(b.getHeight()*0.9),b.getWidth()/2,(int)(b.getHeight()*(0.1+(.06*i)/siz)));
        }
        g.setColor(new Color(150,120,40));
        g.fillOval((b.getWidth()-siz-2)/2,b.getHeight()/10,siz+2,siz+2);
        g.setColor(new Color(250,240,80));
        g.fillOval((b.getWidth()-siz)/2,b.getHeight()/10,siz,siz);
        List<Color>c=Arrays.asList(new Color(0,255,0),new Color(255,0,0),new Color(130,0,100),new Color(0,0,200),new Color(110,0,200),new Color(200,205,210),new Color(0,240,255),new Color(255,100,0));
        List<Point>pts=new ArrayList<>();
        pts.add(new Point((b.getWidth()-siz)/2,b.getHeight()/10));
        loop:for(int i=0;i<8+siz/4;i++){
            int y=r.nextInt((8*b.getHeight())/11);
            int x=1+(int)(b.getWidth()*0.35*y/((8*b.getHeight())/11));
            x=r.nextInt(2*x)-x+b.getWidth()/2;
            y+=b.getHeight()/8;
            g.setColor(c.get(r.nextInt(c.size())));
            x-=siz/2;
            Point p=new Point(x,y);
            for(Point q:pts){
                if(q.distance(p)<1+2*siz)continue loop;
            }
            pts.add(p);
            g.fillOval(x,y,siz,siz);
        }
        ImageIO.write(b,"png",new File("tree.png"));
    }
}

```

**Sample results:**

Size=3:

Size=4:

Size=5:

Size=12:

Size=20:

# Answer
> 4 votes
**Rebol**

With a dialect to display the symbols. To change the tree size, just change the parameter of `make-tree`.

```
make-tree: func [int /local tr] [
  tr: copy []
  length: (int * 2) + 3
  repeat i int [
      repeat j 3 [
            ast: to-integer ((i * 2) - 1 + (j * 2) - 2)
            sp: to-integer (length - ast) / 2
            append/dup tr space sp
            append/dup tr "*" ast
            append tr lf
      ]
  ]
  append/dup tr space (length - 1) / 2
  append tr "|"
  append tr lf
  tr
]

print make-tree 3

```

# Answer
> 4 votes
**Python**

```
import sys
w = sys.stdout.write
def t(n,s):
    for i in range(n):
        for a in range(n-i):
            w(" ")
        w("[")
        for l in range(i<<1):
            if i==n-1:
                w("_")
            else:
                w("~")
        w("]")
        print("")
    for o in range(s):
        for i in range(n):
            w(" ")
        print("[]")

t(10, 2)

```

# Answer
> 1 votes
## Ti-Basic 84

Asks for a size:

```
              :
            Input
           S:Lbl 1
            S-1→S
              :
             "||
            "+""→
           Str1:"
             "→Str2
         :Disp Str2+
        "   **":Disp
       Str2+"  "+"*"+
      Str1+"*":Disp "
     "+Str1+"*-"+"||-*
    ":Disp Str1+"*--||-
   -*":Disp "   *---||--
  -*":Disp "  *----||----
 *":Disp Str1+"   "+Str2+"
":If S>0:Goto 2:Goto 1:Lbl
              2

```

Output (size 1):

```
       **
      *||*
     *-||-*
    *--||--*
   *---||---*
  *----||----*
       ||

```

---
Tags: popularity-contest
---