Output the text "Code Bowling" Code-Bowling

You've been hired by Brunswick Bowling to create a simple program to output the text Code Bowling on their monitors. This company is worth a pretty penny and you feel you can swindle them for quite the bit of cash.

The job description clearly states that they pay on a scoring basis and you're pretty confident you can manipulate their scoring system to your advantage and get the largest pay check possible from these guys. To do so will require you packing as much code as you can into your program/function, even though their scoring system is designed to prevent you from doing so.

Get out your piggy banks, let's code!

Challenge

The challenge is to simply output the text Code Bowling, exactly as it is written here, with the highest score possible. (See section: Scoring System below)

Leading and trailing new-lines (line-breaks) are acceptable.

Your code may be an entire program or just an executable function.

Rules

Obligatory: This challenge is using Code-Bowling: Common Rules, Revision 1.0.0; See Meta for details.

Character : Byte Ratio
In Code-Bowling a character-count is preferred over a byte-count. The obvious reasoning for this is that multi-byte unicode characters (e.g. ) can be used in place of single-byte unicode characters to fluff up byte count and will make bowling more about who renames the most variables with high-byte unicode characters rather than who most strategically creates meaningful complex code.
Variable/Function/Object Names
All variable names (or object pointers, function names, etc) should be 1 character long. The only acceptable time to use 2-character variables names is after all possible 1-character variables have been used. The only acceptable time to use 3-character variables names is after all possible 2-character variables have been used. Etc.
Un-used Code
All code must be used. Meaning the program must fail to always properly complete the task if any individual character (or varying set(s) of characters) is/are removed. Naturally, a subset of the program should not be able complete the task on its own without the rest of the program.
Comments
Comments are not permitted towards character-count, unless somehow utilized by your program/function.

Scoring System:

  Pangram Challenge:

A pangram is a sentence that uses every letter at least once. (The quick brown fox jumps over the lazy dog).

This challenge-type has a scoring systems designed where a perfect pangram would achieve the theoretical maximum score (though you are not required to use every character at least once.) Additionally, using any character more than once will start incurring a penalty. This challenge also expands to more than just the alphabetical characters.

  Scoring Metric:

  Each character used increases your score by 1.
  Repeated use of any alphanumeric character (a-z, A-Z, 0-9) will result in a deduction of 3 points per repeat (first use does not
  result in a deduction).
  Repeated use of basic punctuation ([!?.-,":';]) - including the brackets - will result in a deduction of 2 points per repeat.
  Repeated use of other ASCII characters {`~@#$%^&*_+=|\/><} - including the curly brackets - will result in a deduction of 4 points
  per repeat.
  Use of spaces, tabs, and newlines will result in a deduction of 1 point per use. That is, they do not count towards
  character total.
  Characters not mentioned above (Exotic Characters) will result in a deduction of 1 point per use. That is, they do not count towards
  character total.

  Scoring Tool:

An automated scoring widget has been created and can be found here.

This is a code-bowling variant. The program with the highest score wins! (Since there is a maximum score of 94, whoever reaches it first (if it can be reached) will be marked as the accepted answer, though others are free to keep answering for fun)

Python 3, 82 87 88

Thanks to @JonathanAllan for +1 score

print("g!#$%&'*n+,./012i34579;<l=>?@ADEwFGHIJKLoMNOPQRSBTUVWXYZ ^_`abchejkmqsuvdyz{|}~ \x6f       C"[::-8])

Try it online!

Nothing special, just slicing and skipping characters. The string is reversed so you can't remove characters and have the original string being printed.


Matchstick Equations Your task in this challenge is to analyize a given "Matchstick Equation" like this one...

... and to find out whether it can be turned into a valid equation by rearranging the matches. If so, you are to output the least number of moves to do so and the resulting equation.

Input

The input is a String that can be read from STDIN, taken as a function argument or even be stored in a file. It is an equation that represents a matchstick arrangement and can be described using the following EBNF:

input = term, "=", term ;
term = number | (term, ("+" | "-"), term) ;
number = "0" | (numeralExceptZero , {numeral}) ;
numeralExceptZero = "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" ;
numeral = "0" | numeralExceptZero ;

An example for a valid input would be 3+6-201=0+0+8.

Task

Consider the following illustration where each matchstick has a number assigned:

We now map each input symbol to the corresponding matchstick positions as follows:

0 ↦ 1,2,3,4,5,6
1 ↦ 4,5
2 ↦ 2,3,5,6,8
3 ↦ 3,4,5,6,8
4 ↦ 1,4,5,8
5 ↦ 1,3,4,6,8
6 ↦ 1,2,3,4,6,8
7 ↦ 4,5,6
8 ↦ 1,2,3,4,5,6,8
9 ↦ 1,3,4,5,6,8
- ↦ 8
+ ↦ 8,10
= ↦ 7,9

Each input formula can be turned into a matchstick arrangement. For example, the equation "45+6=92" becomes

where unused matchsticks are greyed out.
Your task is to find out the least number of matchsticks that have to be rearranged in order to make the equation valid.

Output

We distinguish between three possible cases:

If the input is not valid (i.e. it doesn't satisfy the above EBNF), output whatever you want.
Otherwise, if there are ways to turn the equation into a valid one by rearranging the matchsticks, you have to output both the minimum number of rearrangements and the corresponding equation. Just as the input, the outputted equation must also satisfy the given EBNF. In the above example, the correct output would be
1 and 46+6=52. If there are multiple possibilities for the resulting equation, output any of them.
Otherwise (so if the input is valid but there is no way to make the equation true), you have to output -1.

Details

You are not allowed to remove or to add matches. That means, if the input is built of n matchsticks, the output must also consist of exactly n matchsticks.
"Empty" matchstick-blocks are only allowed at the end and the beginning of an equation, not in the middle. So, for example, turning 7-1=6 into 7  =6-1 by simply removing -1 from the left side and adding it on the right side with just 3 matchstick rearrangements is not allowed.
Since I don't really see the mapping from numbers to matchstick positions as an interesting part of this challenge, for a plus of 20 bytes, you may either

access a file in which the mapping (number/operation ↦ matchstick positions) is stored in any reasonable way, or
if your programming language supports a Map datatype, assume that you have access to a map that is preinitialized with the (number/operation ↦ matchstick positions)-mapping. This map may for example look like that: {(0,{1,2,3,4,5,6}),(1,{4,5}),(2,{2,3,5,6,8}),(3,{3,4,5,6,8}), ..., (-,{8}),(+,{8,10}),(=,{7,9})}

Examples

Input: 1+1=3 ↦ Output: 1 and 1+1=2

Input: 15+6=21 ↦ Output: 0 and 15+6=21

Input: 1=7 ↦ Output: -1

Input: 950-250=750 ↦ Output: 2 and 990-240=750

Input: 1-2=9 ↦ Output: 1 and 1+2=3

Input: 20 + 3=04 ↦ Output: anything

Winner

This is code-golf, so the shortest correct answer (in bytes) wins. The winner will be chosen one week after the first correct answer is posted.


Not Your Routine Bean Machine Consider this ASCII version of a mechanism similar to a bean machine or plinko/pachinko game:
    O

    ^
   \ ^
  ^ ^ \
 \ ^ / ^
U U U U U
1 2 3 4 5

The O is a ball that falls down.

When it hits a ^, there's a 50-50 chance it will go left or right.
When it hits a /, it always goes left.
When it hits a \, it always goes right.

The ball eventually falls into one of the numbered U troughs at the bottom. The question is, what is the probability it will end up in each trough?
For this particular case, the probabilities are 0.0, 0.1875, 0.5625, 0.125, and 0.125, for troughs 1 through 5 respectively.
Here's another example with 3 troughs instead of 5. The probabilities are 0.5, 0.5, and 0.0:
  O

  /
 ^ ^
U U U
1 2 3

In this challenge we will generalize this problem to a mechanism with any number of layers set up in any fashion.
Challenge
Write a program or function that takes in the ASCII representation of the pyramid structure of the mechanism. (Input via stdin/command line/function arg.)
You may either assume it comes in with spaces that put it in the proper shape, e.g.
   ^
  \ ^
 ^ ^ \
\ ^ / ^

Or you may assume it comes in with no spaces at all, e.g.
^
\^
^^\
\^/^

(If desired, you may assume there is a trailing newline and/or some consistent pattern of trailing spaces.)
The input pyramid structure may have any number of levels (aka lines), including zero. Each level has one more ^, /, or \ than the last, and there are levels + 1 troughs at the bottom (which aren't part of the input).
You program/function must print/return the list of the probabilities that the ball lands in each of the troughs (in the order leftmost trough to rightmost trough). These should be floating point values that, when printed, have at least 3 decimal places (superfluous zeros or decimal points are not required; 1 is fine for 1.000, .5 is fine for 0.500, etc.). If you wrote a function, you may print the values or return a list/array of the floats.
Any reasonable printed list format is fine. e.g. 0.5 0.5 0.0, [0.5 0.5 0.0], [0.5, 0.5, 0.0], {0.5, 0.5, 0.0}, or 0.5\n0.5\n0.0 would all be alright.
Examples
0 Levels: (boils down to one trivial U)
Input: [no input/empty string given]
Output: 1.0
1 Level:
Input: ^
Output: 0.5 0.5
Input: /
Output: 1.0 0.0
Input: \
Output: 0.0 1.0
2 Levels: (second example above)
Input:
 /
^ ^

Output: 0.5 0.5 0.0
3 Levels:
Input:
  ^
 ^ ^
^ ^ ^

Output: 0.125 0.375 0.375 0.125
Input:
  \
 / \
/ / \

Output: 0.0 0.0 0.0 1.0
4 Levels: (first example above)
Input:
   ^
  \ ^
 ^ ^ \
\ ^ / ^

Output: 0.0 0.1875 0.5625 0.125 0.125
7 Levels:
Input:
      ^
     / ^
    ^ ^ /
   / \ / \
  ^ ^ / ^ \
 ^ \ ^ \ / ^
\ ^ ^ ^ \ ^ /

Output: 0.0 0.09375 0.28125 0.4375 0.1875 0.0 0.0 0.0
Scoring
The shortest answer in bytes wins. Tiebreaker is earlier post.

Ruby 140

->s{r=[1.0]
s.lines.map{|l|n=[i=0.0]*(r.size+1)
l.scan(/\S/).map{|e|a,b=e>?/?e>?]?[0.5]*2:[0,1]:[1,0]
z=r[i]
n[i]+=z*a
n[i+=1]+=z*b}
r=n}
r}

Function that takes as input the string (can be nicely formatted as a pyramid) and returns an array of floats.

Test it online: http://ideone.com/kmsZMe

Pretty straightforward implementation. Here it is ungolfed:

F = -> input {
  probabilities = [1.0]

  input.lines.each { |line|

    new_probabilities = [0.0] * (probabilities.size+1)
    elements = line.scan /\S/
    elements.map.with_index{|el, i|
      deltas = el > '/' ? (el > ']' ? [0.5,0.5] : [0,1]) : [1,0]

      d1, d2 = deltas

      new_probabilities[i] += probabilities[i] * d1
      new_probabilities[i + 1] += probabilities[i] * d2
    }
    probabilities = new_probabilities
  }
  return probabilities
}


Count balanced binary strings matching any of a set of masks A binary string is a string which contains only characters drawn from 01. A balanced binary string is a binary string which contains exactly as many 0s as 1s.

You are given a positive integer n and an arbitrary number of masks, each of which is 2n characters long, and contains only characters drawn from 012. A binary string and a mask match if it is the same length and agrees on the character in every position where the mask doesn't have a 2. E.g. the mask 011022 matches the binary strings 011000, 011001, 011010, 011011.

Given n and the masks as input (separated by newlines), you must output the number of distinct balanced binary strings which match one or more of the masks.

Examples

Input

3
111222
000112
122020
122210
102120

Reasoning

The only balanced binary string matching 111222 is 111000.
The only balanced binary string matching 000112 is 000111.
The balanced binary strings matching 122020 are 111000 (already counted), 110010 and 101010.
The balanced binary strings matching 122210 are 110010 (already counted), 101010 (already counted) and 100110.
The balanced binary strings matching 102120 are 101100 and 100110 (already counted).

So the output should be

6

Input

10
22222222222222222222

Reasoning

There are 20 choose 10 balanced binary strings of length 20.

Output

184756

Winner

The winner will be the one that computes the competition input the fastest, of course treating it the same way as it would any other input. (I use a determined code in order to have a clear winner and avoid cases where different inputs would give different winners. If you think of a better way to find the fastest code, tell me so).

Competition input

http://pastebin.com/2Dg7gbfV

ruby, pretty fast, but it depends upon the input

Now speed-up by a factor of 2~2.5 by switching from strings to integers.

Usage:

cat <input> | ruby this.script.rb

Eg.

mad_gaksha@madlab ~/tmp $ ruby c50138.rb < c50138.inp2
number of matches: 298208861472
took 0.05726237 s

The number of matches for a single mask a readily calculated by the binomial coefficient. So for example 122020 needs 3 2s filled, 1 0 and 2 1. Thus there are nCr(3,2)=nCr(3,1)=3!/(2!*1!)=3 different binary strings matching this mask.

An intersection between n masks m_1, m_2, ... m_n is a mask q, such that a binary string s matches q only iff it matches all masks m_i.

If we take two masks m_1 and m_2, its intersection is easily computed. Just set m_1[i]=m_2[i] if m_1[i]==2. The intersection between 122020 and 111222 is 111020:

122020 (matched by 3 strings, 111000 110010 101010)
111222 (matched by 1 string, 111000)
111020 (matched by 1 string, 111000)

The two individual masks are matched by 3+1=4 strings, the interesection mask is matched by one string, thus there are 3+1-1=3 unique strings matching one or both masks.

I'll call N(m_1,m_2,...) the number of strings matched all m_i. Applying the same logic as above, we can compute the number of unique strings matched by at least one mask, given by the inclusion exclusion principle and see below as well, like this:

N(m_1) + N(m_2) + ... + N(m_n) - N(m_1,m_2) - ... - N(m_n-1,m_n) + N(m_1,m_2,m_3) + N(m_1,m_2,m_4) + ... N(m_n-2,m_n-1,m_n) - N(m_1,m_2,m_3,m_4) -+ ...

There are many, many, many combinations of taking, say 30 masks out of 200.

So this solution makes the assumption that not many high-order intersections of the input masks exist, ie. most n-tuples of n>2 masks will not have any common matches.

Use the code here, the code at ideone may be out-dated.

Test case 1: number of matches: 6
Test case 2: number of matches: 184756
Test case 3: number of matches: 298208861472
Test case 4: number of matches: 5

I added a function remove_duplicates that can be used to pre-process the input and delete masks m_i such that all strings that match it also match another mask m_j.,For the current input, this actually takes longer as there are no such masks (or not many), so the function isn't applied to the data yet in the code below.

Code:

# factorial table
FAC = [1]
def gen_fac(n)
  n.times do |i|
    FAC << FAC[i]*(i+1)
  end
end

# generates a mask such that it is matched by each string that matches m and n
def diff_mask(m,n)
  (0..m.size-1).map do |i|
    c1 = m[i]
    c2 = n[i]
    c1^c2==1 ? break : c1&c2
  end
end

# counts the number of possible balanced strings matching the mask
def count_mask(m)
  n = m.size/2
  c0 = n-m.count(0)
  c1 = n-m.count(1)
  if c0<0 || c1<0
    0
  else
    FAC[c0+c1]/(FAC[c0]*FAC[c1])
  end
end

# removes masks contained in another
def remove_duplicates(m)
  m.each do |x|
    s = x.join
    m.delete_if do |y|
      r = /\A#{s.gsub(?3,?.)}\Z/
      (!x.equal?(y) && y =~ r) ? true : false
    end
  end
end

#intersection masks of cn masks from m.size masks
def mask_diff_combinations(m,n=1,s=m.size,diff1=[3]*m[0].size,j=-1,&b)
  (j+1..s-1).each do |i|
    diff2 = diff_mask(diff1,m[i])
    if diff2
      mask_diff_combinations(m,n+1,s,diff2,i,&b) if n<s
      yield diff2,n
    end
  end
end

# counts the number of balanced strings matched by at least one mask
def count_n_masks(m)
  sum = 0
  mask_diff_combinations(m) do |mask,i|
    sum += i%2==1 ? count_mask(mask) : -count_mask(mask)
  end
  sum
end

time = Time.now

# parse input
d = STDIN.each_line.map do |line|
  line.chomp.strip.gsub('2','3')
end
d.delete_if(&:empty?)
d.shift
d.map!{|x|x.chars.map(&:to_i)}

# generate factorial table
gen_fac([d.size,d[0].size].max+1)

# count masks
puts "number of matches: #{count_n_masks(d)}"
puts "took #{Time.now-time} s"

This is called the inclusion exclusion principle, but before somebody had pointed me to it I had my own proof, so here it goes. Doing something yourself feels great though.

Let us consider the case of 2 masks, call then 0 and 1, first. We take every balanced binary string and classify it according to which mask(s) it matches. c0 is the number of those that match only mask 0, c1 the nunber of those that match only 1, c01 those that match mask 0 and 1.

Let s0 be the number sum of the number of matches for each mask (they may overlap). Let s1 be the sum of the number of matches for each pair (2-combination) of masks. Let s_i be the sum of the number of matches for each (i+1) combination of masks. The number of matches of n-masks is the number of binary strings matching all masks.

If there are n masks, the desired output is the sum of all c's, ie. c = c0+...+cn+c01+c02+...+c(n-2)(n-1)+c012+...+c(n-3)(n-2)(n-1)+...+c0123...(n-2)(n-1). What the program computes is the alternating sum of all s's, ie. s = s_0-s_1+s_2-+...+-s_(n-1). We wish to proof that s==c.

n=1 is obvious. Consider n=2. Counting all matches of mask 0 gives c0+c01 (the number of strings matching only 0 + those matching both 0 and 1), counting all matches of 1 gives c1+c02. We can illustrate this as follows:

0: c0 c01
1: c1 c10

By definition, s0 = c0 + c1 + c12. s1 is the sum number of matches of each 2-combination of [0,1], ie. all uniqye c_ijs. Keep in mind that c01=c10.

s0 = c0 + c1 + 2 c01
s1 = c01
s = s0 - s1 = c0 + c1 + c01 = c

Thus s=c for n=2.

Now consider n=3.

0  : c0 + c01 + c02 + c012
1  : c1 + c01 + c12 + c012
2  : c2 + c12 + c02 + c012
01 : c01 + c012
02 : c02 + c012
12 : c12 + c012
012: c012

s0 = c0 + c1 + c2 + 2 (c01+c02+c03) + 3 c012
s1 = c01 + c02 + c12 + 3 c012
s2 = c012

s0 = c__0 + 2 c__1 + 3 c__2
s1 =          c__1 + 3 c__2
s2 =                   c__2

s = s0 - s1 + s2 = ... = c0 + c1 + c2 + c01 + c02 + c03 + c012 = c__0 + c__1 + c__2 = c

Thus s=c for n=3. c__i represents the of all cs with (i+1) indices, eg c__1 = c01 for n=2 and c__1 = c01 + c02 + c12 for n==3.

For n=4, a pattern starts to emerge:

0:   c0 + c01 + c02 + c03 + c012 + c013 + c023 + c0123
1:   c1 + c01 + c12 + c13 + c102 + c103 + c123 + c0123
2:   c2 + c02 + c12 + c23 + c201 + c203 + c213 + c0123
3:   c3 + c03 + c13 + c23 + c301 + c302 + c312 + c0123

01:  c01 + c012 + c013 + c0123
02:  c02 + c012 + c023 + c0123
03:  c03 + c013 + c023 + c0123
12:  c11 + c012 + c123 + c0123
13:  c13 + c013 + c123 + c0123
23:  c23 + c023 + c123 + c0123

012:  c012 + c0123
013:  c013 + c0123
023:  c023 + c0123
123:  c123 + c0123

0123: c0123

s0 = c__0 + 2 c__1 + 3 c__2 + 4 c__3
s1 =          c__1 + 3 c__2 + 6 c__3
s2 =                   c__2 + 4 c__3
s3 =                            c__3

s = s0 - s1 + s2 - s3 = c__0 + c__1 + c__2 + c__3 = c

Thus s==c for n=4.

In general, we get binomial coefficients like this (↓ is i, → is j):

   0  1  2  3  4  5  6  .  .  .

0  1  2  3  4  5  6  7  .  .  .
1     1  3  6  10 15 21 .  .  .
2        1  4  10 20 35 .  .  .
3           1  5  15 35 .  .  .
4              1  6  21 .  .  .
5                 1  7  .  .  .
6                    1  .  .  .
.                       .
.                          .
.                             .

To see this, consider that for some i and j, there are:

x = ncr(n,i+1): combinations C for the intersection of (i+1) mask out of n
y = ncr(n-i-1,j-i): for each combination C above, there are y different combinations for the intersection of (j+2) masks out of those containing C
z = ncr(n,j+1): different combinations for the intersection of (j+1) masks out of n

As that may sound confusing, here's the defintion applied to an example. For i=1, j=2, n=4, it looks like this (cf. above):

01:  c01 + c012 + c013 + c0123
02:  c02 + c012 + c023 + c0123
03:  c03 + c013 + c023 + c0123
12:  c11 + c012 + c123 + c0123
13:  c13 + c013 + c123 + c0123
23:  c23 + c023 + c123 + c0123

So here x=6 (01, 02, 03, 12, 13, 23), y=2 (two c's with three indices for each combination), z=4 (c012, c013, c023, c123).

In total, there are x*y coefficients c with (j+1) indices, and there are z different ones, so each occurs x*y/z times, which we call the coefficient k_ij. By simple algebra, we get k_ij = ncr(n,i+1) ncr(n-i-1,j-i) / ncr(n,j+1) = ncr(j+1,i+1).

So the index is given by k_ij = nCr(j+1,i+1) If you recall all the defintions, all we need to show is that the alternating sum of each column gives 1.

The alternating sum s0 - s1 + s2 - s3 +- ... +- s(n-1) can thus be expressed as:

s_j = c__j * ∑［(-1)^(i+j) k_ij］ for i=0..n-1
     = c__j * ∑［(-1)^(i+j) nCr(j+1,i+1)］ for i=0..n-1
     = c__j * ∑［(-1)^(i+j) nCr(j+1,i)］｛i=0..n｝ - (-1)^0 nCr(j+1,0)
     = (-1)^j c__j

s   = ∑［(-1)^j  s_j］ for j = 0..n-1
    = ∑［(-1)^j (-1)^j c__j)］ for j=0..n-1
    = ∑［c__j］ for j=0..n-1
    = c

Thus s=c for all n=1,2,3,...


Can you pretty-print a tree? Goal:

A tree can be represented as a nested list: the list elements represent nodes, and a node is a pair of the node name and node children.

Your program takes as input a nested list of pairs, and should output a pretty tree.

Examples:

Here are four example test cases below

["stump",[]]

["trunk",[["branch",[["leaf",[]],["leaf",[]]]],["branch",[]]]]

[".",[["bin",[]],["usr",[["bin",[]],["local",[["bin",[]],["lib",[]]]]]]]]

["kingdom",[["mineral",[]],["animal",[["dog",[["schnauzer",[]],["whippet",[]]]]]],["vegetable",[["cabbage",[]]]]]]

And these are the corresponding outputs

1

stump

2

trunk
├── branch
│   ├── leaf
│   └── leaf
└── branch

3

.
├── bin
└── usr
    ├── bin
    └── local
        ├── bin
        └── lib

4

kingdom
├── mineral
├── animal
│   └── dog
│       ├── schnauzer
│       └── whippet
└── vegetable
    └── cabbage

Notes:

If the characters │, ├, └, ─ are not conveniently available in your language, you may substitute with the ASCII characters |, +, L, - respectively.
You may assume there is one unique root node.  You may assume the input will be "nice", it doesn't matter what your program does if the input is not well-formed.
To avoid unfair advantages to any particular language, some flexibility in the input format is allowed within reason.  For example, specifying the nesting with parens () or braces {} is OK.  If it's more convenient for the node labels to be integers instead of strings, that's OK.  Extra whitespace in the input is OK, as long as it's not being used to define structure.  If you take the input as a string literal and parse it directly, that's OK.
No messing with the underlying structure of the tree!  E.g., you may not change how a leaf node is represented.
Tip: the representation used in the examples is valid json, so you can paste it into a json linter to better see the nesting.

Scoring:

This is code golf, shortest code wins.

Haskell, 159 bytes

With preprocessing of the input to fit the defined tree datatype (included in score) since trees can't be represented as a nested list.

data T=T[Char][T]
r=reverse;z=zipWith;a%b=a:cycle[b]
p(T s b)|k<-r$p<$>b=s:(concat$r$z(z(++))(("└── "%"    ")%("├── "%"│   "))k)
mapM putStrLn.p

Usage:

> mapM putStrLn.p $ T"kingdom"[T"mineral"[],T"animal"[T"dog"[T"schnauzer"[],T"whippet"[]]],T"vegetable"[T"cabbage"[]]]
kingdom
├── mineral
├── animal
│   └── dog
│       ├── schnauzer
│       └── whippet
└── vegetable
    └── cabbage


Interpreted Interpreter Duplicate? I knew somebody must've done this before.

Programming a programming language in itself is something that has interested me since I knew what a programming language was. So I thought I'd create a Code Golf challenge for you.
Challenge
Create an interpreter for a given programming language, programmed entirely in itself. The interpreter should be able to run any valid program in that language, including itself.
Inputs:
The program can take it's input as a file passed as a parameter (e.g. python myfile.py) or as lines from stdin (cat myfile.py | python).
Outputs:
Whatever an interpreter would normally output, on the correct streams (stdout, stderr etc.)
Specifications

The code needs to be written in an interpretable language, and serve as an interpreter for its own language.
It can't use an eval() function to interpret code.
It must run any valid program in that language. If the language allows external modules (or includes), it must be able to read those modules.
This task is code golf. The submission with the least characters that is correct wins. In case of a tie, the solution that was submitted first wins.

Loophole remover:

Yes, if you can interpret Java, Bytecode or HQ9++ in themselves, go ahead!
In JavaScript / ES, using HTML tags such as <script> is not allowed.

Nothing, 0 chars

The source code is an empty file. It does nothing, like any Nothing program, therefore it is the correct execution of every such program.


Compose a Vim quine! Goal:

Create and save file in Vim containing at least 25 ASCII characters. The exact keystrokes used during the creation and saving of this file must also produce identical contents in Windows Notepad (without having to save in Notepad).

Rules:

For the purposes of this challenge, Vim begins open in command mode.
The mouse is not allowed.
Shift is allowed. Ctrl, alt, or any other modifier keys are not allowed.
Your solution must work with the default "terminal" (non-GUI) Vim shipped with either Ubuntu 11.04 or OS X 10.6.7 (one of the two). Assume this Vim's .vimrc contains only set nocompatible (with no line break after it), which is itself located at ~/.vimrc. Pretend your operating system was just installed before opening Vim.
You must not open any pre-existing files except for your .vimrc. Any files you create while solving this puzzle may be saved and re-opened as many times as necessary.
Vim cannot be closed!

Disclosure, and  a possible reason to close: I do not have a solution.

The edited sequence (the first version was mangled).

2 A 2 A Esc 2 A 2 A Esc 2 A 2 A Esc

2 A 2 A Esc  2 A 2 A Esc 2 A 2 A Esc

2 A 2 A Esc 2 A 2 A Esc  A : w q Enter

Esc Backspace Backspace Backspace
Backspace Backspace : w q Enter

Should do the trick, if I'm counting my keystrokes correctly. No wait, is the escape key allowed?


Wardialing in the Modern World Introduction
Wardialing was a very interesting way to try to hack people back in the '80s and '90s. When everyone used dial-up, people would dial huge amounts of numbers to search for BBS's, computers, or fax machines. If it was answered by a human or answering machine, it hung up and forgot the number. If it was answered by a modem or a fax machine, it would make note of the number.
"Of course, you realize this means War...dialing?" <--- Pun made by @Shaggy
Challenge
Your job is to make a URL wardialer. Something that tests and checks if it's a valid website from one letter of the alphabet.
Constraints

Program must take user input. This input has to be a letter of the alphabet, no numbers. Just one letter of the alphabet and form multiple URLs that start with the letter. Input letter will be lowercase, not uppercase.
Standard loopholes apply.
You must make 8 URLs from 1 letter, and test to see if it is a valid site.
If you hit an error (not a response code), instead of leaving it blank, go ahead and return a 404
If you hit a redirect (3xx), return a 200 instead.
You may output the results in any reasonable format, as long as it includes the website name, status codes for all the websites and the redirects.
This is code-golf, so shortest amount of bytes wins.

What counts as a URL for this challenge?
http://{domain-name}.{com or net or org}
For this challenge, the domain name should only be 4 letters long, no more, no less.
What should I test?
For each 4 letter domain name, test it against three top-level domains (.com, .net, .org). Record all the response codes from each URL, remember from the constraints that any (3xx) should return 200 and be recorded as a redirect in the output and any error getting to the website should result in a 404.
Input

a

Output
+---------+------+------+------+------------+
| Website | .com | .net | .org | Redirects? |
+---------+------+------+------+------------+
| ajoe    | 200  | 200  | 200  | .com, .net |
+---------+------+------+------+------------+
| aqiz    | 200  | 404  | 404  | no         |
+---------+------+------+------+------------+
| amnx    | 200  | 503  | 404  | .com       |
+---------+------+------+------+------------+
| abcd    | 200  | 404  | 200  | .com       |
+---------+------+------+------+------------+
| ajmx    | 200  | 503  | 404  | no         |
+---------+------+------+------+------------+
| aole    | 200  | 200  | 200  | .com       |
+---------+------+------+------+------------+
| apop    | 404  | 200  | 200  | .net       |
+---------+------+------+------+------------+
| akkk    | 200  | 200  | 200  | .com       |
+---------+------+------+------+------------+

Python 2 + requests, 198 191 bytes

from requests import*
def f(c):
 for i in range(24):
	u='http://'+c+`i/3`*3+'.'+'cnooermtg'[i%3::3]
	try:a=get(u,allow_redirects=0).status_code
	except:a=404
	if a/100==3:a='200 R'
	print u,a

Sample output for a:

http://a000.com 404
http://a000.net 404
http://a000.org 404
http://a111.com 200
...
http://a666.org 502
http://a777.com 403
http://a777.net 200 R
http://a777.org 200


Make a string a e s t h e t i c Basically, between every character of a uni-line string, add a space, but there can't be two spaces in between one character.

aesthetic becomes a e s t h e t i c.
The quick brown fox jumps over the lazy dog becomes T h e q u i c k b r o w n f o x j u m p s o v e r t h e l a z y d o g.
I'm Nobody! Who are you? becomes I ' m n o b o d y ! W h o a r e y o u ?

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

Python, 36 bytes
lambda s:" ".join(s.replace(" ",""))


Russian Nesting Quine A Russian nesting doll, more commonly known as a Matryoshka doll, is a doll which contains a smaller version of itself, which then contains another smaller version of itself, which contains a smaller version of itself,  which contains a smaller version of itself, which contains a smaller version of itself... - until finally, the last one is empty. An example:

Today your goal is to emulate this Russian tradition by writing a program or function that, when it contains itself N times, will print itself containing N-1 copies of itself times.

For example, the doll program abcd will have the N=3 program abababcdcdcd, which will print the N=2 program ababcdcd, which prints the original N=1 program abcd, which finally prints N=0, which is empty. This should theoretically work for any reasonable value of N.

Rules:

Here is a TIO program to help generate doll programs based on your program
Standard Quine Rules apply
Standard Loopholes apply
'Contains' means directly in the center of the previous version, so your solution must have a positive even number of bytes. A program of length 10 will have a copy of the original inserted after the fifth byte, then another after the tenth byte etc.
A single trailing whitespace is allowed in the output
As this is code-golf, your goal is to make your N=1 program as short as possible.
An explanation of your code would be appreciated

Underload, 4 bytes
N=1: Try it online.
 ()S

N=2: Try it online.
 ( ()S)S

N=3: Try it online.
 ( ( ()S)S)S

Explanation:
Self-explanatory, but I add it anyway.

(...)S prints anything between the parenthesis to STDOUT
The space before it is a no-op to make the byte-count even and comply to the rules of the challenge.


Reachability measure in Conway's Soldiers Background
Conway's Soldiers is a version of peg solitaire played on an infinite checkerboard. The board is initially full of pegs below an infinite horizontal line, and empty above it. Following the ordinary peg solitaire rules (move a peg by jumping over another one horizontally or vertically, removing the one that was jumped over), the objective is to move a peg as far above the horizontal line as possible.
Wikipedia page has the solutions for 1 to 4 units above the line: (A and B denote two possible alternatives.)

In ASCII notation (using alternative B):
                         X
               X         .
        X      .         .
_X_   __._   __.__   ____.____
 O    OOO    OOOOO   OOOOOOOOO
 O      O      OOO     OOOO
                      OOOOO
                        OO

Conway proved that it is impossible to reach 5 units above the line with finite number of moves. To prove it, he assigned a value to each peg: if a peg is \$n\$ units away from the target position in terms of Manhattan distance, it is assigned the value of \$\varphi^n\$, where
$$
\varphi = \frac{\sqrt5 - 1}{2}
$$
(The value is the golden ratio minus 1.)
This value was carefully chosen to ensure that every possible move keeps the total value constant when a move is towards X, and decreasing when a move is away from it. Also, the final state must have a peg precisely at the target position, giving the value of \$\varphi^0 = 1\$, so the target position is unreachable if the initial configuration has the value sum less than 1.
For the target position at 5 units above the line, the configuration looks like this:
     X
     .
     .
     .
_____._____
OOOCBABCOOO
OOOOCBCOOOO
OOOOOCOOOOO
    ...

The peg at the position A is given \$\varphi^5\$, the ones at B are \$\varphi^6\$ each, and so on. Then he showed that the sum for the infinite number of pegs is exactly 1, and therefore the value sum of any finite subset is less than 1, concluding the proof of non-reachability.
Task
Now, let's apply this measure to an arbitrary configuration, not just for the original problem, e.g. the pegs may surround the target position:
OOOOO
O...O
O.X.O
O...O
OOOOO

Given such a configuration, calculate Conway's measure on it and output truthy if the measure is at least 1, falsey otherwise. (Note that the truthy output does not guarantee that the target is actually reachable, while the falsey output does say that the target is too far away from the pegs to reach it.)
The calculated measure should be within 1e-6 margin. A program that produces wrong answers when the computed one falls within \$\pm10^{-6}\$ from the true measure is acceptable. You can use (sqrt(5)-1)/2 or 0.618034, but not 0.61803 or 0.61804.
You can choose any three distinct symbols (characters, numbers, or any other kind of values) to indicate a peg, an empty space, and the target position respectively. You can take the grid as a matrix, a list of strings (or lists of symbols), or a single string (or a list of symbols) with a delimiter of your choice. You can assume that the input has exactly one target position, and it is not already occupied by a peg.
Test cases
In the test cases below, O is a peg, X is the target position, and . is a blank.
True
measure = 1 (0.61803 will fail all of the measure=1 cases)
OOX
--------------
measure = 1
OO.X
.O..
.O..
--------------
measure = 1
..X..
.....
.....
OOOOO
..OOO
--------------
measure = 1
....X....
.........
.........
.........
OOOOOOOOO
..OOOO...
.OOOOO...
...OO....
--------------
measure = 4
OOOOO
O...O
O.X.O
O...O
OOOOO
--------------
measure ~ 1.00813
X....OOOO
....OOOO.
...OOOO..
..OOOO...
.OOOO....

False
measure ~ 0.618
OO.X
--------------
measure ~ 0.999975 (0.61804 will fail)
OOOOOOOOOOOOOOOOOOOOOO.X
--------------
measure ~ 0.9868
X....OOO
....OOOO
...OOOO.
..OOOO..
.OOOO...
--------------
measure = 0
.....
.....
..X..
.....
.....

Python 3.8, 109 bytes

lambda s,i=-1:sum(c%2*.618034**(abs((i:=i+1)//(n:=(h:=s.index)(0)+1)-(x:=h(2))//n)+abs(i%n-x%n))for c in s)>1

Try it online!

Input is a list of integers, created by concatenating all rows of the grid. Each row is terminated by the number 0. Use the numbers 1, 2, 4 to represents "O", "X", ".".

Python 3.8, 108 bytes

lambda s,i=-1:sum(c%2*.618034**(abs((i:=i+1)//(n:=s.find(0)+1)-(x:=s.find(2))//n)+abs(i%n-x%n))for c in s)>1

Try it online!

Pushing the input format a little bit here by using unprintable characters. Input is a single byte string of concatenated rows, where each row is terminated by a NULL character (code point 0).
Replace X with the character SOT (code point 2).

Byte string is essentially an integer list of code points. The reason I'm not using list of integer is because list doesn't have find method. The code points of the row terminator and X are chosen to be single digit.

How:

The length of each row (including the terminator) can be simply calculated as:

n:=s.find(0)+1  # terminator is represented as 0

Similarly, the target position is

x:=s.find(2)    # X is represented as 2

We can then do some modular tricks to figure out the Manhattan distance between a position i and the target x:

abs(i//n + x//n) + abs(i%n + x%n)

All of these are shoved into a single expression by abusing walrus operator.


Backwards Long Addition The standard long addition method:

  The standard algorithm for adding multidigit numbers is to align the addends vertically and add the columns, starting from the ones column on the right. If a column exceeds ten, the extra digit is "carried" into the next column. (wikipedia)

A long addition example:

 145
+ 98
-----
 243

Backwards long addition is similar but you start adding from the leftmost column and carry to the next column (on it's right). If the last (ones) column produces a carry you write it behind the current sum in the next column. If there is no carry in the last column no extra column is needed.

 145
+ 98
-----
 1341

Explanation for the above example by columns, left to right: 1 = 1; 4+9 = 10(carried) + 3; 5+8+1(carry) = 10(carried) + 4; 1(carry) = 1

You should write a program or function which receives two positive integers as input and returns their sum using backwards long addition.

Input

Two positive integers.

Output

An integer, the sum of the two input numbers using backwards long addition.
There should be no leading zeros. (Consider 5+5=1 or 73+33=7.)

Examples

Format is Input => Output.

1 3 => 4
5 5 => 1
8 9 => 71
22 58 => 701
73 33 => 7
145 98 => 1341
999 1 => 9901
5729 7812 => 26411

Pyth, 16 bytes
Still new to Pyth, but this looks promising..
s_`smvs.[_d0lzcz

The idea here is simple. To do backwards addition, you need backwards numbers. We take the input, reverse it, make sure that it has same number of digits be adding trailing 0, sum the two numbers, reverse it again and make sure no leading zero exists.
Code expansion
              cz          # Take the input and Python split it. Splits on space automatically
    m                     # Now we map over these two strings
         _d               # Reverse the string
       .[  0lz            # Pad it with 0 on right so that its length is same as input length
     vs                   # We have array of character and number, stringify and eval
   s                      # Sum the numbers in array
  `                       # Stringify
 _                        # Reverse
s                         # Convert back to number, removing leading 0

Try it online here


Draw the Sawtooth Alphabet A simple one today. Write the shortest program that draws a "sawtooth alphabet" given a positive integer for the height. You must write the name of your programming language when you come to the letter it starts with.

For example, if your language is Python and the input is 1 the output should be:

ABCDEFGHIJKLMNOPythonQRSTUVWXYZ

If the input is 2 the output should be:

 B D F H J L N Python R T V X Z
A C E G I K M O      Q S U W Y

If the input is 4 the output should be:

   D     J     Python     V
  C E   I K   O      Q   U W
 B   F H   L N        R T   X Z
A     G     M          S     Y

Notes

A always starts at the bottom left.
Input can be via stdin or function call or similar. Output to stdout.
Input above 26 doesn't need to work.
No trailing spaces.

C, 134

n,m,c,p;
main(r){
for(scanf("%d",&n),m=--n?n*2:1;n+r--;puts(""))
for(c=-1,p=1;c++<25;)
p+=(c-n-r)%m*((c-n+r)%m)?1:1-printf("%*c",p,c+65);
}

Compiles on gcc with a few warnings. Newlines aren't included in the character count.

122 characters if the input is already stored in n.

Thanks to user2992539, tolos and edc65 for improvements.


Duct Tape some sorting Your job is to make a sorting algorithm. The catch, you must copy it from Stack Overflow.

Your program will take an input array (or equivalency), and output a sorted permutation of the array.

Your program must consist solely of copy and pasted code blocks from Stack Overflow.
You may not take parts of a code block, nor may you rearrange one. A code block is everything within a single gray box.
The original question of the post may not have a tag, title, or question body containing the word "sort" in it.
You must cite the both the post and poster(s).
You may not use built in sorts.
The post must be older than this question.

Also, here are allowed modifications:

You may move import statements to the top
For any type of identifier type thing, you may replace all of its occurrences within the code block with a different name. Please list substitutions.

This is a popularity contest, so the correct answer with the most up-votes wins!

GolfScript

Straightforward bubble sort implementation. Can probably be golfed down further. Try it online.

~x {{ document.write man [
putc( 'c', stdout ) ;
\b {{ return 1 echo ${10}
return
true;
Convert.ToDouble(o)
datagrid1.ItemsSource = dataTable1.DefaultView;
echo $a:u
cat > file {{ \b }} ~x
int* arr1[8];
}}
source ~/.bashrc
return
true;
] document.write
@echo off
IP=`curl ifconfig.me`
return
true;
~x return !0
return
true;
}} ~x
for {0..10..2}; do
  ..
done
set -x
\b
basename `pwd`
~x

Sources

https://stackoverflow.com/a/2513659 (https://stackoverflow.com/u/276101):

~x

https://stackoverflow.com/a/3773868  (https://stackoverflow.com/u/394167):

{{

https://stackoverflow.com/a/802894   (https://stackoverflow.com/u/8815):

document.write

https://stackoverflow.com/a/2188223 (https://stackoverflow.com/u/116908):

man [

https://stackoverflow.com/q/4563825 (https://stackoverflow.com/u/111307):

putc( 'c', stdout ) ;

https://stackoverflow.com/a/16876671 (https://stackoverflow.com/u/980550):

\b

https://stackoverflow.com/a/22604291 (https://stackoverflow.com/u/1622022):

return 1

https://stackoverflow.com/a/6146038 (https://stackoverflow.com/u/116908):

echo ${10}

https://stackoverflow.com/a/4054267 (https://stackoverflow.com/u/69083):

return
true;

https://stackoverflow.com/q/23657401 (https://stackoverflow.com/u/1171811):

Convert.ToDouble(o)

https://stackoverflow.com/q/6097907 (https://stackoverflow.com/u/517871):

datagrid1.ItemsSource = dataTable1.DefaultView;

https://stackoverflow.com/a/4813101 (https://stackoverflow.com/u/591720):

echo $a:u

https://stackoverflow.com/q/19114714 (https://stackoverflow.com/u/72436):

cat > file

https://stackoverflow.com/a/3773868 (https://stackoverflow.com/u/394167):

}}

https://stackoverflow.com/a/859676 (https://stackoverflow.com/u/87234):

int* arr1[8];

https://stackoverflow.com/a/2518150 (https://stackoverflow.com/u/245602):

source ~/.bashrc

https://stackoverflow.com/a/5750751 (https://stackoverflow.com/u/187690):

]

https://stackoverflow.com/q/8823643 (https://stackoverflow.com/u/1059446):

@echo off

https://stackoverflow.com/a/9764597 (https://stackoverflow.com/u/167925):

IP=`curl ifconfig.me`

https://stackoverflow.com/a/8255667 (https://stackoverflow.com/u/179669):

return !0

https://stackoverflow.com/a/966110 (https://stackoverflow.com/u/104162):

for {0..10..2}; do
  ..
done

https://stackoverflow.com/a/6930980 (https://stackoverflow.com/u/705676):

set -x

https://stackoverflow.com/a/4641636 (https://stackoverflow.com/u/333698):

basename `pwd`


Manufactoria: generate the slowest possible accepting program Write a Manufactoria program that will accept the empty input tape.  But don't do it quickly!  I mean, write the program quickly, but don't let it run quickly.  The slower the program, the better, as long as it terminates eventually.  The example program below takes 3:51 (the "total time" reported by the simulator).

http://pleasingfungus.com/Manufactoria/?lvl=36&code=g12:5f3;r9:8f1;p12:9f3;c13:9f0;r11:9f0;r10:9f0;r9:9f1;b11:8f0;b10:8f1;r9:7f2;c10:7f2;c11:7f2;c12:7f3;q12:8f3;y13:8f2;y14:8f2;y15:8f1;y15:7f0;y14:7f0;y13:7f0;g12:6f3;&ctm=Slow_Accepter!;Generate_the_slowest_possible_accepting_machine;:;7;3;0;

Your program starts with the empty tape.  It must doodle around a bit, but eventually reach the output square.  You may leave data on the tape if you wish.  The slowest program on the 7x7 Manufactoria board wins!

Your right arrow key is your friend, it speeds up the simulator.

Bonus points for crashing the simulator!

~1023 iterations ~1015 iterations ~108 iterations

http://pleasingfungus.com/Manufactoria/?lvl=32&code=g9:7f2;b12:8f2;p13:8f5;p11:8f3;r14:8f0;q11:10f3;q13:7f1;y13:9f1;r10:10f1;c12:9f2;c9:9f2;i11:9f7;i10:9f4;c9:8f3;i10:8f2;c14:9f0;c15:9f0;c15:8f3;c15:7f3;c14:7f2;g12:7f0;c11:7f3;c10:7f2;q9:6f7;r10:6f1;r9:5f3;c11:6f0;r10:5f2;r11:5f1;r9:4f3;r10:4f0;r11:4f0;y12:5f2;y13:5f2;y14:5f3;y14:6f0;y13:6f0;y12:6f0;&ctm=Slow_Accepter!;Generate_the_slowest_possible_accepting_machine;:;7;3;0;

The machine is basically an odometer running in base three, using the red, blue and yellow symbols to stand for the digits 0, 1, and 2 respectively. The green symbol is used to mark the end of the number. At the start, the tape is initialized with 49 red symbols. This is done by the parts in the top three rows of the machine. The bottom four rows handle the task of incrementing the number in a loop. On each iteration, the two branch cells on left-hand side work out how to apply the increment to current number, and then the branch cells on the right-hand side copy the remaining, unaffected digits.

Previously I've tried to estimate the machine's running time, were it allowed to run to completion, but at this level it makes more sense to just go by the number of iterations. Roughly speaking, it takes about a minute to complete one iteration -- but even if it took a second that would only decrease the running time by a single order of magnitude.


Finite Cantor's Diagonal Given a list of N integers, each with N digits, output a number which differs from the first number because of the first digit, the second number because of the second digit, etc.

Example

Given this list:

1234
4815
1623
4211

The number 2932's first digit is different from the first number's first digit, its second digit is different from the second number's second digit, etc. Therefore it would be a valid output.

Inputs

You may take both the list and N as input, or only the list if you wish.
Each integer in the list will necessarily have as many digits as the length of the list (N)
Numbers will not have any leading zeroes
The input list must contain numbers and not strings.
You may take inputs as function arguments, through STDIN, or anything similar.
You may assume that the list will not be longer than 10 elements (and no number in the list will be bigger than 2147483647)

Outputs

It is not sufficient that the output is not in the list. The digits must differ as explained above.
You can use any digit selection strategy that respects the constraint of different digits.
The number cannot have leading zeroes
You may output the number through STDOUT, return it from a function, etc.

Test cases

Input:
12345678
23456789
34567890
45678901
56789012
67890123
78901234
89012345

Possible output: 24680246

Input:
1

Possible output: 2

Scoring

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

CJam (15 14 bytes)

qN/ee{:=i2%)}%

Online demo

Thanks to Adnan for a one-byte saving.

Dissection

qN/    e# Split input on newlines
ee{    e# Label each line with its index and map:
  :=i  e#   Get the character at the same index (i.e. diagonalise)
  2%)  e#   Compute (ASCII value mod 2) + 1
       e#   Maps 0 1 2 3 4 5 6 7 8 9
       e#     to 1 2 1 2 1 2 1 2 1 2
}%


Calculating distances mod N You have been collecting data from a Advanced Collecting Device Controller™ for a long time. You check the logs, and to your horror you discover that something has gone terribly wrong: the data only contains the last bits of the numbers!

Luckily, you know the starting value and that the value never changes fast. That means you can recover the rest by just finding the distance from the start.

Challenge

You will write a program or a function to calculate the amount a value has changed, given a modulus N and a list of the intermediate values modulo N.

The change between every pair of numbers is always less than N/2, so there will only be one valid answer for each test case.

You will be given as input an integer N > 2 and a list of values, in a format of your choice. Input may be given via STDIN or command line or function arguments.

You will output a single integer, the amount the original value has changed. Output may be printed to STDOUT or returned.

Rules

Your program must work for any distance and modulus less than 2^20.
You may assume that:

N is at least 3.
The list has at least 2 values.
All the values in the list are at least 0 and less than N.
All changes in the numbers are less than N/2.

Anything else is an invalid input, and your program may do whatever it wants.
Standard loopholes, any non-standard libraries and built-in functions for this exact purpose are forbidden.
This is code-golf, so the shortest program in bytes wins.

Example test cases

Input:

3
0 1 2 2 0 1 0 2 1 2 0 1 2 1 1

Output:

4

Explanation (with example value):

Value mod 3: 0 1 2 2 0 1 0 2 1 2 0 1 2 1 1
Value:       0 1 2 2 3 4 3 2 1 2 3 4 5 4 4

Input:

10
5 2 8 9 5

Output:

-10

Explanation (with example value):

Value mod 10:  5  2  8  9  5
Value:        15 12  8  9  5

Invalid inputs:

2
0 0 0 0 0

(too small modulus)

6
2 5 4 2

(too large change between 2 and 5)

Python 2, 53 bytes

lambda n,l:sum((b-a+n/2)%n-n/2for a,b in zip(l,l[1:]))

Super straight forward answer. I wonder if there is a shorter way.


Count the Palindromes Given a number n, calculate the amount of bases in the range of [2, n) in which b(n) is a Palindrome.

Example

n = 8 has the base conversions:

2 = 1000
3 = 22
4 = 20
5 = 13
6 = 12
7 = 11

Of which 2 of them, 3 = 22 and 7 = 11 are palindromes. So return 2.

Clarifications

For the sake of convenience, Your answer only needs to be correct for inputs 3 - 36 inclusive, as few languages can handle base conversion of >36.
A single digit number is considered a palindrome.
This is sequence A135551 on OEIS

Test Cases

3   -> 1
4   -> 1
5   -> 2
6   -> 1
7   -> 2
8   -> 2
9   -> 2
10  -> 3
11  -> 1
12  -> 2
13  -> 2
14  -> 2
15  -> 3
16  -> 3
17  -> 3
18  -> 3
19  -> 1
20  -> 3
21  -> 4
22  -> 2
23  -> 2
24  -> 4
25  -> 2
26  -> 4
27  -> 3
28  -> 4
29  -> 2
30  -> 3
31  -> 3
32  -> 3
33  -> 3
34  -> 3
35  -> 2
36  -> 5

Finally

Standard Loopholes Apply.
This is code-golf, so fewest bytes wins.
Have Fun!

05AB1E,  10  8 bytes

-2 bytes thanks to Emigna (use "bifurcation" instruction Â to replace duplicate and reverse DR & increment the loop to avoid needing to close it.)

G¹N>вÂQO

Try it online!

How?

G¹N>вÂQO
G        - for N in range(1, input()+1):
 ¹       -   1st input
  N      -   N (the loop variable)
   >     -   increment
    в    -   base conversion
     Â   -   push reverse
      Q  -   equal?
       O -   sum
         - print top of stack


Oddly Even, Positively Negative Given N, output the Nth term of this infinite sequence:

-1 2 -2 1 -3 4 -4 3 -5 6 -6 5 -7 8 -8 7 -9 10 -10 9 -11 12 -12 11 ... etc.

N may be 0-indexed or 1-indexed as you desire.

For example, if 0-indexed then inputs 0, 1, 2, 3, 4 should produce respective outputs -1, 2, -2, 1, -3.

If 1-indexed then inputs 1, 2, 3, 4, 5 should produce respective outputs -1, 2, -2, 1, -3.

To be clear, this sequence is generated by taking the sequence of positive integers repeated twice

1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9 10 10 11 11 12 12 ...

and rearranging each pair of odd numbers to surround the even numbers just above it

1 2 2 1 3 4 4 3 5 6 6 5 7 8 8 7 9 10 10 9 11 12 12 11 ...

and finally negating every other term, starting with the first

-1 2 -2 1 -3 4 -4 3 -5 6 -6 5 -7 8 -8 7 -9 10 -10 9 -11 12 -12 11 ...

The shortest code in bytes wins.

Python 2, 23 bytes

lambda n:~n/2+n%2*(n|2)

Odd inputs give roughly n/2, even ones roughly -n/2. So, I started with -n/2+n%2*n and tweaked from there.

Try it online!


The weird and wild bean game Maybe some of you already know this game: you have a collection of jelly beans of different colors. For every color, the bean can have different tastes, some are good and some are bad, and you cannot tell them apart. You have to pick a bean of a given color, and pray you have select a good one.

So, write the shortest program that receives a color of your choice (from a given list), and randomly returns the taste selected. The taste has to be picked from a built-in list. The possible list of inputs and outputs are:

Input      Output choices [only one from the list]
--------------------------------------------------
green      lawn clippings, lime, mucus, pear
yellow     rotten eggs, buttered popcorn
blue       toothpaste, blue berry
orange     vomit, peach
brown      canned dog food, chocolate
white      stinky socks, tutti-frutti, baby diapers, coconut

Rules:

You can assume that the input is going to be always a color from the input choices.
Case and trailing spaces and/or newlines do not matter.
Output must be uniformly random: succesive program executions must yield different results, and the chances of getting a given taste must be the same for all tastes in a list.

This is code-golf, so may the shortest program win!

C#, 418 313 305 271 bytes

s=>{var a="lawn clippings,lime,mucus,pear|rotten eggs,buttered popcorn|toothpaste,blue berry|vomit,peach|canned dog food,chocolate|stinky socks,tutti-frutti,baby diapers,coconut".Split('|')["eluaoi".IndexOf(s[2])].Split(',');return a[new System.Random().Next(a.Length)];}

Too long even for C# but I can't see how to get it any shorter.

Full/Formatted version:

using System;

class P
{
    static void Main()
    {
        Func<string, string> f = s =>
        {
            var a = "lawn clippings,lime,mucus,pear|rotten eggs,buttered popcorn|toothpaste,blue berry|vomit,peach|canned dog food,chocolate|stinky socks,tutti-frutti,baby diapers,coconut"
                    .Split('|')["eluaoi".IndexOf(s[2])].Split(',');

            return a[new System.Random().Next(a.Length)];
        };

        Console.WriteLine(f("green"));
        Console.WriteLine(f("yellow"));
        Console.WriteLine(f("blue"));
        Console.WriteLine(f("orange"));
        Console.WriteLine(f("brown"));
        Console.WriteLine(f("white"));

        Console.ReadLine();
    }
}


Print sin, cos, and tan of special angles In trigonometry, there are certain angles known as "special angles". This is because when you take sin, cos or tan of one of these angles, you get a result that is easy to remember because it is a square root of a rational number. These special angles are always multiples of either pi/6, or pi/4. Here is a visualization of all the special angles, and their corresponding trig values.

As you can see, for each angle their is a corresponding pair of numbers. The first number is cosine of that angle, and the second is sine of that angle. To find tangent of one of these angles, just divide sin by cos. For example, tan(pi/6) is  equal to

sin(pi/6) / cos(pi/6) ==
(1/2) / (√3/2) ==
1/√3 ==
√3/3

The Challenge

You must write a full program that takes 3 inputs.

A single char representing the trig function you're supposed to calculate. This will be either 's' (sin), 'c' (cos), or 't' (tan).
The numerator of the input angle. This can be any positive integer. Note that an input of 5 means the numerator is 5 * pi.
The denominator of the input angle. This will always be one of the following: 1, 2, 3, 4, 6

Then print out the exact value the trig function of that angle. Here is a list of sin, cos, and tan of all angles up to 2 * pi:

sin(0pi):    0
sin(pi/6):   1/2
sin(pi/4):   root(2)/2
sin(pi/3):   root(3)/2
sin(pi/2):   1
sin(2pi/3):  root(3)/2
sin(3pi/4):  root(2)/2
sin(5pi/6):  1/2
sin(1pi):    0
sin(7pi/6):  -1/2
sin(5pi/4):  -root(2)/2
sin(4pi/3):  -root(3)/2
sin(3pi/2):  -1
sin(5pi/3):  -root(3)/2
sin(7pi/4):  -root(2)/2
sin(11pi/6): -1/2
sin(2pi):    0

cos(0pi):    1
cos(pi/6):   root(3)/2
cos(pi/4):   root(2)/2
cos(pi/3):   1/2
cos(pi/2):   0
cos(2pi/3):  -1/2
cos(3pi/4):  -root(2)/2
cos(5pi/6):  -root(3)/2
cos(1pi):    -1
cos(7pi/6):  -root(3)/2
cos(5pi/4):  -root(2)/2
cos(4pi/3):  -1/2
cos(3pi/2):  0
cos(5pi/3):  1/2
cos(7pi/4):  root(2)/2
cos(11pi/6): root(3)/2
cos(2pi):    1

tan(0pi):    0
tan(pi/6):   root(3)/3
tan(pi/4):   1
tan(pi/3):   root(3)
tan(pi/2):   nan
tan(2pi/3):  -root(3)
tan(3pi/4):  -1
tan(5pi/6):  -root(3)/3
tan(1pi):    0
tan(7pi/6):  root(3)/3
tan(5pi/4):  1
tan(4pi/3):  root(3)
tan(3pi/2):  nan
tan(5pi/3):  -root(3)
tan(7pi/4):  -1
tan(11pi/6): -root(3)/3
tan(2pi):    0

If you get a number larger than 2pi, subtract 2pi from it until you get a number that is in range. For example, sin(17pi/6) is the same as sin(5pi/6) == 1/2. Your program is expected to do basic simplification, for example, if your input is cos(2pi/4) this is the same as cos(pi/2) == 0. Builtin trigonometry functions are disallowed.

Shortest answer in bytes wins!

Pyth, 125 122 bytes

Uses the formula n = 4 - |floor(4.5-9k)|, where kπ = θ i.e. k is the quotient of the second and third inputs, to determine which special angle is in question: the angles 0, 30, 45, 60 and 90 degrees are numbered 0 to 4 respectively, and the 90~180 degrees angles go in reverse; this formula works for θ∈[0,π]. The values of corresponding sines would be sqrt(n)/2 and existent, non-zero tangents would be 3^(n/2-1). However, my implementation uses lists with hard-coded compressed strings for higher control of output format, and it seems the code is shorter that way too.

A,c." t8¾Îzp³9ÓÍÕ¬$ ·Íb³°ü"dc." t@a'óè©ê¶oyÑáîwÀ(";J+cEE?qz\c.5ZK-4.as-4.5*3*3%J1?qz\t+?>%J1 .5\-k@GK+?>%J2 1\-k@HK

Let's turn it into pythonic pseudocode:

                                   z = input()
                                   k = ""
                                   d = " "
                                   Z = 0
A,c." t8¾Îzp³9ÓÍÕ¬$ ·Íb³°ü"d       G = "0 sqrt(3)/3 1 sqrt(3) nan".split(d)
  c." t@a'óè©ê¶oyÑáîwÀ(";          H = "0 1/2 sqrt(2)/2 sqrt(3)/2 1".split()
J+cEE                              J = eval(input())/eval(input()) +
  ?qz\c.5Z                             0.5 if z == "c" else Z
                                   # the second term converts sin to cos
K-4.as-4.5*3*3%J1                  K = 4 - abs(int(4.5 - 3*3*(J%1)))
                                   # 9* would lose precision so 3*3* instead
?qz\t                              if z == "t"
  +?>%J1 .5\-k                         print(("-" if J%1 > 0.5 else k) +
   @GK                                     G[K])
                                   else:
  +?>%J2 1\-k                          print(("-" if J%2 > 1 else k) +
   @HK                                     H[K])

Test online.


Display the Hacker Logo You may have heard of the "Hacker Logo", also called the "Hacker Emblem". It looks like this:

This is a pattern from a mathematical simulation called the Game of Life. The glider is the simplest Life pattern that moves, and the most instantly recognizable of all Life patterns.

The challenge

The challenge is pretty simple: Display the hacker logo. This is defined as:

A 3x3 grid with a border, a white background and gray gridlines.
Five black dots arranged in the GoL glider pattern.
Nothing else.

The rules

The black dots must fill 40%-80% of their individual grid-boxes.
You will display the emblem with graphical output but no ASCII art.
The output must be at least 30x30 pixels.
The output must only have the colors gray, black and white.
Each grid-box in the grid will be the same size. The grid will be a regular 3x3 square.
You may not pull the logo from the internet or your filesystem.
Your program will display the logo on an empty screen/window. If it terminates it must do so normally.
Note that "dots" does not necessarily mean "circles". A "dot" is a single geometric shape centered in the middle of the grid-box with one surface. For example, while a circle or square will qualify as a dot, two triangles or a checkerboard will not.

The winner

As this is code-golf, the shortest answer in each language wins!

Please include a screenshot of the output of your program in your answer.

CSS+HTML, 56+84=140 bytes 52+84=136 bytes

Saved 4 bytes by incorporating suggestions from the comments.

td{border:1px solid#888;line-height:.4;font-size:3em

•
•
•••

This uses the UTF-8 character • which is 2 bytes long and takes advantage of the graciousness of HTML syntax.


Animated drawing of a Bézier curve Your job is to draw a Bézier curve given it's control points. The only criteria is that you actually have to show how to draw the curve from the initial control point to the last one.

Criterias

The result has to be animated, e.g. it has to show the drawing process somehow. The way you do the animation is irrelevant, it can generate a .gif, it can draw to a window, or generate ASCII results (and possibly clearing the screen after each draw), etc.
It has to support at least 64 control points.
This is a popularity contest, so you might want to add some additional features to your program to get more upvotes. (My answer for example draws the control points, and some visual aid on how to generate the image as well)
The winner is the most upvoted valid answer 7 days after the last valid submission.
My submission doesn't count as valid.

How to draw a Bézier curve

Assume we want to draw 100 iterations. To get the nth point of the curve you can use the following algorithm:

1. Take each adjanced control point, and draw a line between them
2. Divide this line by the number of iterations, and get the nth point based on this division.
3. Put the points you've got into a separate list. Let's call them "secondary" control points.
4. Repeat the whole process, but use these new "secondary" control points. As these points have one less points at each iteration eventually only one point will remain, and you can end the loop.
5. This will be nth point of the Bézier curve

This might be a bit hard to understand when written down, so here are some images to help visualize it:

For two control points (shown in black dots) you only have one line initally (the black line). Dividing this line by the number of iterations and getting the nth point will result in the next point of the curve (shown in red):

For three control points, you first have to divide the line between the first and the second control point, then divide the line between the second and third control point. You will get the points marked with blue dots.

Then, as you still have two points, you have to draw a line between these two points (blue in the image), and divide them again to get the next point for the curve:

As you add more control points the algorithm stays the same, but there will be more and more iterations to do. Here is how it would look like with four points:

And five points:

You can also check my solution, which was used to generate these images, or read more about generating Bézier curves at Wikipedia

Done recursively in Mathematica with no hard limits on the number control points in just three lines:

ctrlPts = {{0, 0}, {1, 1}, {2, 0}, {1, -1}, {0, 0}};
getLines[x_List] := Partition[x, 2, 1];
partLine[{a_, b_}, t_] := t a + (1 - t) b;
f[pts_, t_] := NestList[partLine[#, t] & /@ getLines@# &, pts, Length@pts- 1]

Showing it is more involved than the calculations!:

color[x_] := ColorData[5, "ColorList"][[x[[1]]]]
Animate[Graphics[{PointSize[.03], ,
        MapIndexed[{color@#2, Point/@ #1,Line@#1} &, f[ctrlPts,t]],
        Red, Point@Last@f[ctrlPts, t],
        Line@Flatten[(Last@f[ctrlPts, #]) & /@ Range[0, t, 1/50], 1]}], {t, 0, 1}]

Code dissection (kind of) for the calc part:

getLines[x_List] := Partition[x, 2, 1]; (* Takes a list of points { pt1, pt2, pt...}
                                           as input and returns {{pt1,pt2}, {pt2,pt3} ...}
                                           which are the endpoints for the successive
                                           lines between the input points *)

partLine[{a_, b_}, t_] := t a + (1 - t) b;(* Takes two points and a "time" as input
                                             and calculates
                                             a linear interpolation between them*)

f[pts_, t_] := NestList[partLine[#, t] & /@ getLines@# &, pts, Length@pts- 1]
                                          (* This is where the meat is :)
     Takes a list of n points and a "time" as input.
     Operates recursively on the previous result n-1 times, preserving all the results
     Each time it does the following with the list {pt1, pt2, pt3 ...} received:
           1) Generates a list {{pt1, pt2}, {pt2, pt3}, {pt3, pt4} ...}
           2) For each of those sublists calculate the linear interpolation at time "t",
              thus effectively reducing the number of input points by 1 in each round.
     So the end result is a list of lists resembling:
     {{pt1, pt2, pt3 ...}, {t*pt1+(1-t)*pt2, t*pt2+(1-t)*pt3,..}, {t*pt12+(1-t)*pt23, ..},..}
                             --------------   ---------------
                                  pt12              pt23
     And all those are the points you see in the following image:

With a few more lines you can drag the control points interactively while the animation is running:

Manipulate[
 Animate[Graphics[{
    PointSize[.03], Point@pts,
    MapIndexed[{color@#2, Point /@ #1, Line@#1} &, f[pts, t]],
    Red, Point@Last@f[pts, t], Line@Flatten[(Last@f[pts, #]) & /@ Range[0, t, 1/50], 1]},
   PlotRange -> {{0, 2}, {-1, 1}}], {t, 0, 1}],
  {{pts, ctrlPts}, Locator}]

Here dragging the green point:

BTW, the same code runs in 3D without modifications (For the Mathematica geeks you only have to replace Graphics[] by Graphics3D[] and add a third coordinate to the control points list):

NB:

Of course this kludge isn't needed in Mathematica as there are several primitives for drawing Beziers:

Graphics[{BSplineCurve[ctrlPts], Green, Line[ctrlPts], Red,  Point[ctrlPts]}]


2-dimensional ray tracing The challenge is to implement a 2-dimensional ray tracing program, text-based.

Sources of white light are @ symbols. R, G and B are light filters. / and \ are mirrors with 80% reflectivity. ? is a light sensor. >, <, ^ and V combine light in the appropriate direction (e.g. if one red and one green came into a > the light would be emitted toward the right and it would be yellow). Other non-whitespace characters absorb all light. Light is emitted from @ symbols in four directions.

When the program is run, it should produce output the same as the input, but with traced rays. Because this is 2 dimensional, and I guarantee in the input no rays will ever cross, there will be no problem with that. Each ray should be represented by a letter; r=red, g=green, b=blue, c=cyan, m=magenta, y=yellow, w=white. There won't be any ternary colors, ever. The casing is important to differentiate it from the input. After that output, the values of light captured by the question marks (in order of their appearance, left to right top to bottom) should be outputted as percentages and colors. For example, this input:

 /                  @
                    -
 \R>                 ?

 @B/

Should give the output:

 /wwwwwwwwwwwwwwwwww@w
 w                  -
w\R>mmmmmmmmmmmmmmmmm?
 w b
 @B/

#1: 72% Magenta

Another important point to note - when two colors are combined using a "prism" (the arrows) the strength of the combined light becomes the average strength of the two. Output must be exactly as specified (e.g. #x: [x][x]x% Color).

If your language cannot read from STDIN and write to STDOUT, create a function (anonymous or lambda when available) that accepts the input as an argument and returns the result.

Directives to the compiler, structures required or recommended for all or most programs created in the language, etc. can be omitted. For example, #include and using directives (but not #define) may be removed in C-style languages, #/usr/bin/perl -options in Perl, and

 Module Module1
      Sub Main()
      End Sub
 End Module

in VB.NET, for example. If you import namespaces or add include directives, please note them in your answer.

Is that hard enough, now? :)

Python, 602 559 614 chars

import sys
S=sys.stdin.readlines()
X=max(len(s)for s in S)
I='#'*X+''.join(t[:-1]+' '*(X-len(t))+'\n'for t in S)+'#'*X
L=len(I)
R=range(L)
B=[0]*L
C=[0]*L
for p in R:
 if'@'!=I[p]:continue
 for d in(1,-1,X,-X):
  q=p;c=7;b=100.
  while 1:
   q+=d;a=I[q];B[q]+=b;C[q]|=c
   if a in'\/':d=(ord(a)/30-2)*X/d;b*=.8
   elif a in'RGB':c&=ord(a)/5-12
   elif a in'><^V':d={'>':1,'<':-1,'^':-X,'V':X}[a];b/=2
   elif' '!=a:break
print''.join(I[p]if' '!=I[p]else' bgcrmyw'[C[p]]for p in R[X:-X])
i=0
for p in R:
 if'?'==I[p]:i+=1;print'#%d:'%i,'%.0f%%'%B[p],[0,'Blue','Green','Cyan','Red','Magenta','Yellow','White'][C[p]]

Edit: fixed so it doesn't need trailing spaces.


Print a table of numbers in decimal and 2**i bases Computers live by binary. All programmers know binary.

But the 2**x bases are often neglected as non-practical, while they have beautiful relations to binary.

To show you one example of such a beatiful relation, 19 will be my testimonial.

19 10011 103 23 13 j

19 is decimal, included for clarity.
10011 is 19 in binary.
103, in base 4 is made starting from binary this way:

log2(4) == 2, let us remember two.
Pad 10011 so that it has a multiple of 2 length -> 010011
Take digits 2 by 2 from left to right and treat them as 2-digits binary numbers:

01 -> 1
00 -> 0
11 -> 3

Done, 10011 in base-4 is 103.

For base 8, do the same but 3-by-3 as log2(8) = 3.

Pad 010011
010 -> 2
011 -> 3

23, Done.

For base 16, do the same but 4-by-4 as log2(16) = 4.

Pad 00010011
0001 -> 1
0011 -> 3

13, Done.

Task

Given a max number as input, you shall output a table

base-ten-i base-two-i base-four-i base-eight-i base-sixteen-i base-thirtytwo-i

for i that goes from 0 to n inclusive. Binary numbers are the epitome of the absolute minimum needed to work, so your code should be as short as possible.

Restrictions and bonuses

Base-ten -> binary and binary -> Base-ten built-ins are considered loopholes as Base-a -> Base-b are.
If you generate all the 2**i (for i > 2) bases by using the relations over mentioned you get a *0.6 bonus, but general base conversions (written by yourself) are allowed.

Example table

> 32
0 0 0 0 0 0
1 1 1 1 1 1
2 10 2 2 2 2
3 11 3 3 3 3
4 100 10 4 4 4
5 101 11 5 5 5
6 110 12 6 6 6
7 111 13 7 7 7
8 1000 20 10 8 8
9 1001 21 11 9 9
10 1010 22 12 a a
11 1011 23 13 b b
12 1100 30 14 c c
13 1101 31 15 d d
14 1110 32 16 e e
15 1111 33 17 f f
16 10000 100 20 10 g
17 10001 101 21 11 h
18 10010 102 22 12 i
19 10011 103 23 13 j
20 10100 110 24 14 k
21 10101 111 25 15 l
22 10110 112 26 16 m
23 10111 113 27 17 n
24 11000 120 30 18 o
25 11001 121 31 19 p
26 11010 122 32 1a q
27 11011 123 33 1b r
28 11100 130 34 1c s
29 11101 131 35 1d t
30 11110 132 36 1e u
31 11111 133 37 1f v
32 100000 200 40 20 10

CJam, 54 * 0.6 = 32.4 bytes

q~){_5,f{)L@{2md@+\}h(%/Wf%W%{{\2*+}*_9>{'W+}&}%S\}N}/

Test it here.

For reference, here is a shorter solution which doesn't qualify for the bonus (at 39 bytes):

q~){:X5{SLX{2I)#md_9>{'W+}&@+\}h;}fIN}/


Shortest code that raises a SIGSEGV Write the shortest code that raises a  Segmentation Fault (SIGSEGV) in any programming language.

C, 5 characters

main;

It's a variable declaration - int type is implied (feature copied from B language) and 0 is default value. When executed this tries to execute a number (numbers aren't executable), and causes SIGSEGV.

Try it online!


Deciphering XKCD colors Randall Munroe (author of XKCD) held a survey to give names to colors. The main outcome is a list of names for the 954 most common RGB monitor colors.

For ease of programming, here is the list in plain text: http://xkcd.com/color/rgb.txt. Beware, the first line is not data, but contains the license.

Write a program or function that takes a valid color name from above list as input and outputs the associated RGB color code. Your program does not have to handle invalid inputs in any defined manner.

Standard loopholes apply. Additionally, your answer must not use pre-defined (built-in or external) color code <-> color name maps. (This includes the linked list.) Shortest code in bytes wins. If you read from a file, the file's byte count must be included.

Examples:

dark peach -> #de7e5d
robin's egg blue -> #98eff9
pink/purple -> #ef1de7

Perl 5 - 4212 3956 3930

use IO::Uncompress::Gunzip qw(gunzip);
gunzip 'g'=>\$_;
while(/(\x00*)(.)(.)(.)(.)/gs){$c[$i+=ord($2)+255*length$1]=sprintf"#%02x%02x%02x\n",map{ord}$3,$4,$5}
@a[32,33,39,47,97..123]=(3,1812,3,17,82,4,1013,119,3,909,8,10,10,1827,1219,4,718,265,228,418,2347,10,3,31,3,1786,921,380,1223,1915,4);
$_=<>;
for$i(0..(($h=y///c-1)<=12?$h-1:12)){$h+=$a[(($i/2|0)==1)+ord((/./g)[$i])]if($i!=7&&$i!=10)}
print$c[$h];

407 bytes for the code and 3523 for the data file. Binary data is read from the file 'g', a hexdump of which can be found here.

This uses a perfect hash function generated using GNU gperf, which assigns each color name to a unique integer in the range 0 to 6304 that can be used to index a table. The gzipped data contains the color values in the format of 1 byte indicating the offset in the table from the previous color, then 3 bytes for the color itself (with two hex digits per byte). (A 0 byte for the offset means it's actually the next value + 255, since not every offset fit in one byte).

The code parses the data to create the table containing the color rgb string, then applies the hash function (translated to perl) to the input to select the matching output from the table.

Usage:

echo 'pale red' | perl get-color.pl
#d9544d

Edit: Further reduced the size by gzipping the data file


Advanced Code Golf - Write a small HTTP server Your challenge is to write a code-golf HTTP server that accepts GET requests. It obviously doesn't have to be fully featured, but it must serve files from a directory.

Rules:

The HTTP server must listen on TCP port 36895 (0x901F)
It must serve files from /var/www on *NIX systems (e.g. Linux), or C:\hgolf on Windows.
You may ignore all incoming HTTP headers except the GET itself.
If the HTTP method is not GET, you must send back a status code of "405 Not Supported" and a body of "405 Not Supported".
If the file does not exist, you must send back a status code of "404 File Not Found" and a body of "404 File Not Found".
If the file exists but could not be read for some reason, you must send back a status code of "500 Server Error" and a body of "500 Server Error".
If the user requests / or any other existing directory root (e.g. /foo/ where a directory foo exists in /var/www/), respond with a blank page.
Your response must contain at least the minimum headers to allow the content to be displayed on Firefox 8.0 and Internet Explorer 8.0
You must respond with the Content-Type header set, but you only have to support extensions html => text/html and txt => text/plain. For any other file extension, Send application/octet-stream as the content type.
Your code must be able to transfer both ASCII and binary data, though you do not explicitly have to distinguish between the two.
You may not use 3rd party libraries.
You may not use in-built classes or features designed to process HTTP requests (e.g. HttpListener in C#)
If your code will only work on a specific OS due to the socket APIs you've used, please state this.

Solutions must include an image showing it serving a HTML page to a browser.

If you've got any questions, please feel free to ask! :)

Bash+netcat: 354 characters

Two script files are used.
No URL decoding, thus file names with spaces and special characters not supported.
Single threaded, so concurrent requests may fail.
Tested on Linux, works nicely with Firefox and Opera.

webserver.sh (33 characters):
while :;do nc -lp36895 -e./w;done

w (321 characters):
read m p v
p=/var/www$p
t=text/plain
[[ -r $p ]]||s='500 Server Error'
[[ -e $p ]]||s='404 Not Found'
[[ $m != GET ]]&&s='405 Not Supported'
[[ $s||-d $p ]]||case ${p##*.} in
txt);;html)t=text/html;;*)t=application/octet-stream;;esac
echo "$v ${s-200 Ok}
Content-Type:$t
"
[[ $s ]]&&echo $s||{ [[ -d $p ]]&&echo||cat $p;}

Sample run:
bash-4.2$ ./webserver.sh

Sample visit (Firefox 19.0):


Calculate your stack exchange reputation Background:
I often find that, when browsing a Stackexchange site, I begin to wonder how people get the amount of reputation that they have. I know I can always count on codegolf SE to solve my problems, so here it is:
Create a program that will accept a positive integer which represents a person's reputation. We will ignore bounties, and say that these are the only ways to gain/lose rep on SE (full table here):

Every account starts out with 1 rep and cannot go below that
Your question is upvoted = +5
Your answer is upvoted = +10
Your question is downvoted = -2
Your answer is downvoted = -2
You downvote an answer = -1
Your answer is accepted = +15
You accept an answer = +2

Your program must figure out how many of those actions occurred on that user's account to get to the rep they have. It must figure out the shortest number of actions to get to this level of rep. Examples:

Input: 11
Output: 1 answer upvote
Input: 93
Output: 6 answer accepts, 1 answer accepted

In these examples when I say 'question upvote', it means that person's queston got upvoted. When I say 'answer downvoted', it means they downvoted someone else's answer.
Rules:
code-golf, so the shortest code that can do this wins.

Bash, 247 202 192 bytes

n=$1 bash <(sed 's/E/)echo /;s/C/ Aaccept/;s/A/answer /
s/.*)/((&)\&\&/'<<<'a=(n+1)/15,a-1)s=s;q=question
aE$aC$s
r=n%5,r-4)d=d&&
r>1E1Ced
1-r%2E1 Adownvote$d
n-=15*a,n>8)q=A
n>3E1 $q upvote')

How it works

After the sed command does it job, the following bash script gets executed:

((a=(n+1)/15,a-1))&&s=s;q=question
((a))&&echo $a answer accept$s
((r=n%5,r-4))&&d=d&&
((r>1))&&echo 1 answer accepted
((1-r%2))&&echo 1 answer downvote$d
((n-=15*a,n>8))&&q=answer
((n>3))&&echo 1 $q upvote

To obtain the optimal solution (minimal number of events to get n reputation), it suffices to compute the number of accepted answers (a) necessary to get to a reputation below 16 (1 answer accept) and handle the residue as follows:

1  (no rep change)
2  answer accepted, answer downvoted
3  answer accepted
4  question upvote, answer downvote
5  question upvote, answer downvoted
6  question upvote
7  question upvote, answer accepted, answer downvoted
8  question upvote, answer accepted
9  answer upvote, answer downvote
10 answer upvote, answer downvoted
11 answer upvote
12 answer upvote, answer accepted, answer downvoted
13 answer upvote, answer accepted
14 answer accept, answer downvote
15 answer accept, answer downvoted


Sloping Binary Numbers Given an integer n, output the first n sloping binary numbers, either 0- or 1-indexed. They are called this because of how they are generated:

Write numbers in binary under each other (right-justified):

........0
........1
.......10
.......11
......100
......101
......110
......111
.....1000
.........

Then, you need to take each diagonal from bottom-left to top-right, such that each final digit is the final digit of a diagonal. Here's the fourth diagonal (zero-indexed) marked with x's, which is 100:

........0
........1
.......10
.......11
......10x
......1x1
......x10
......111
.....1000
.........

The upward-sloping diagonals in order are:

0
11
110
101
100
1111
1010
.......

Then, convert to decimal, giving 0, 3, 6, 5, 4, 15, 10, ...

OEIS A102370

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

JavaScript (ES6), 53 bytes

n=>[...Array(n)].map(g=(j=1,i)=>j>i?0:j&i|g(j+j,i+1))

0-indexed. It's not often I get to use a recursive function as a parameter to map.


Chaining Words Together Given two words and a list as input, your program must (in as few characters as possible, of course) find the shortest way to "chain" the first word to the last using the ones in the list. Two words are "chained" if their first and last letters are the same, e.g. "Food" and "Door".

Your program will take input as a string with words separated by spaces, and output a list (in whatever format is most convenient: string, array/list type, etc) of the completed chain.

Examples:

Input: joke corn tan disc need eat
Output: joke eat tan need disc corn

The first two words in the input list are the first and last words in the chain, and the rest are the constituent words.

Input: best fry easy elf mean tame yam nice
Output: best tame elf fry
NOT: best tame easy yam mean nice elf fry

Input: rug gunned orange purple gains pore soup emo ending
Output: rug gunned

Input: %3gioxl? 6699-4 !f!!&+ ?4; ;78! +6
Output: %3gioxl? ?4; ;78! !f!!&+ +6 6699-4
The "words" don't have to be real words; for the purpose of the challenge, any ASCII character except the space will count as part of a word.

Input: mouth rich frame inspire item sold
Output when the first and last word are impossible to chain is undefined, so handle it however's shortest.

Pyth, 51 48 bytes
FGITW.
=cQdMqeGhHL++hQb@Q1holN{+Fmf.AgVTtTyM+]Y._d.p>Q2

Test suite.


JavaScript (Node.js),  504 481  474 bytes
Builds a BigInt from a string encoded in base 126 and converts it to base 3.
Because the data string contains many unprintable characters, it is not shown at all below.

_=>0+Buffer(`...`).reduce((n,v)=>n*126n+BigInt(v-1),0n).toString(3)

Try it online!
The theoretical length of the string is:
$$\left\lceil\frac{\log(3^{1777})}{\log(126)}\right\rceil=404$$
Because a few characters need to be escaped, we actually need \$410\$ bytes to store it in the source.