Smallest region of the plane that contains all free n-ominoes On Math Stack Exchange, I asked a question about the smallest region that can contain all free n-ominos.

I'd like to add this sequence to the On-Line Encyclopedia of Integer Sequences once I have more terms.

Example

A nine-cell region is the smallest subset of the plane that can contain all twelve free 5-ominoes, as illustrated below. (A free polyomino is one that can be rotated and flipped.)

(A twelve-cell region is the smallest subset of the plane the can contain all 35 free 6-ominoes.)

The Challenge

Compute upper bounds on the smallest regions of the plane that can contain all n-ominoes as a function of n.

Such a table begins:

n | size
--+-------
1 | 1*
2 | 2*
3 | 4*
4 | 6*
5 | 9*
6 | 12*
7 | 37
8 | 50
9 | 65

*These values are the smallest possible.

Example submission

1-omino: 1
#

2-omino: 2
##

3-omino: 4
###
 #

4-omino: 6
####
 ##

5-omino: 9
 #
#####
 ###

6-omino: 12
####
######
  ##

7-omino: <= 37
#######
######
######
######
######
######

Scoring

Run your program for as long as you'd like, and post your list of upper bounds together with the shapes that achieve each.

The winner will be the participant whose table is lexicographically the earliest (with "infinity" appended to the shorter submissions.) If two participants submit the same results, then the earlier submission wins.

For example, if the submissions are

Aliyah: [1,2,4,6,12,30,50]
Brian:  [1,2,4,6,12,37,49,65]
Clare:  [1,2,4,6,12,30]

then Aliyah wins. She beats Brian because 30 < 37, and she beats Clare because 50 < infinity.

In the interest of getting the process started, here's a quick (but not very optimal) answer.

Pattern:

n = 8:
########
 ######
  #####
   ####
    ###
     ##

Take a triangle with length n - 1, stick an extra square onto the corner, and cut off the bottom square.

Proof that all n-ominos fit:

Note that any n-omino can fit in a rectangle with length + width at most n + 1.

If an n-omino fits in a rectangle with length + width at most n, it fits nicely in the triangle (which is the union of all such rectangles). If it happens to use the cut-off square, transposing it will fit in the triangle.

Otherwise, we have a chain with at most one branch.  We can always fit one end of the chain into the extra square (prove this with casework), and the rest fits into a rectangle with length + width at most n, reducing to the case above.

The only case where the above doesn't work is the case where we use both the extra square and the cut-off square.  There's only one such n-omino (the long L), and that one fits inside the triangle transposed.

Code (Python 2):

def f(n):
    if n < 7:
        return [0, 1, 2, 4, 6, 9, 12][n]
    return n * (n - 1) / 2

Table:

 1:   1
 2:   2
 3:   4
 4:   6
 5:   9
 6:  12
 7:  21
 8:  28
 9:  36
10:  45
11:  55
12:  66
13:  78
14:  91
15: 105
16: 120
17: 136
18: 153
19: 171
20: 190
... more cases can be generated if necessary.


Partition and Restructure Given two contiguous shapes of the same area, determine the optimal way to divide the first shape into a minimum number of contiguous segments such that they can be rearranged to form the second shape. In other words, find the minimum number of segments required that can form both of the shapes.

"Contiguous" means that every square in the shape can be reached from any other square by walking across edges. Shapes and segments are allowed to have holes.

"Rearrange" means you move the segments around; you can translate, rotate, and reflect them.

The shapes are contained on a grid; in other words, each shape consists of a collection of unit squares joined by their corners/edges.

Input Specifications

The input will be provided in some reasonable format - list of points, array of strings representing each grid, etc. You can also take the sizes of the grid if requested. The grids will have the same dimensions and the two shapes are guaranteed to have the same area, and the area will be positive.

Output Specifications

The output should just be a single positive integer. Note that there will always be a positive answer because in the worst case scenario, you just divide the shapes into N unit squares.

Examples

The examples are presented as a grid with . representing a blank and # representing part of the shape.

Case 1

Input

.....
.###.
.#.#.
.###.
.....

###..
..#..
..#..
..###
.....

Output

2

Explanation

You can divide it into two L-shaped blocks of 4:

#
###

Case 2

Input

#...
##..
.#..
.##.

.##.
####
....
....

Output

2

Explanation

You can split the shapes like so:

A...
AA..
.A.
.BB.

.AA.
BBAA
....
....

You could also do:

A...
AA..
.B..
.BB.

.AB.
AABB
....
....

Case 3

Input

#....#
######

.####.
.####.

Output

2

Explanation

A....B
AAABBB

.ABBB.
.AAAB.

(This test case demonstrates the necessity to rotate/reflect shapes for optimal output)

Case 4

Input

.###.
..#..

.##..
.##..

Output

2

Explanation

No matter how you select blocks, selecting a 2x1 from the first shape necessarily prevents the other two from being grouped together; thus, you can use one 2x1 and two 1x1s. However, (thanks @Jonah), you can split it into a 3-block L shape and a single square like so:

.AAB.
..A..

.AA..
.BA..

Python 3.6, 799 791 bytes

7 bytes saved by Jonathan Frech and motavica

B=frozenset
M=min
X={}
T=lambda s:((x,y)for y,x in s)
N=lambda s:B((x-M(s)[0],y-M(T(s))[0])for x,y in s)
G=lambda s:{(x,y):s&{(x-1,y),(x+1,y),(x,y-1),(x,y+1)}for(x,y)in s}
C=lambda g,s,i=0:i<=len(g)and(len(g)==len(s)or C(g,s.union(*map(g.get,s)),i+1))
F=lambda s:N([(-x,y)for x,y in s])
P=lambda s,i=4:M([N(s),F(s),P(F(T(s)),i-1)],key=list)if i else s
S=lambda s,t=B(),i=0:t|S(s,B().union(u|{p}for u in t for p in s-u if C(G(u|{p}),{p}))if i else B([B([next(iter(s))])]),i+1)if-~i<len(s)else t
def U(s):
 k=P(s)
 if k in X:return
 j=[t for t in S(k)if C(G(k-t),{next(iter(k-t))})];X[k]={P(t):B()for t in j}
 for t in j:X[k][P(t)]|=B([B(P(k-t))]);U(t);U(k-t)
V=lambda s,t:1+M(V(v,w)for u in B(X[s])&B(X[t])for v in X[s][u]for w in X[t][u])if s^t else 1
A=lambda s,t:U(s)or U(t)or V(P(s),P(t))

Try it online!

Usage

A(s, t) takes in two shapes where each shape is given by a list of x, y grid positions.

A helper function to convert the graphical representation to a list of positions is below:

def H(g):
 g=g.split("\n")
 return[(x,y)for x in range(len(g[0]))for y in range(len(g))if"#"==g[y][x]]

Example:

case1_1 = \
""".....
.###.
.#.#.
.###.
....."""

case1_2 = \
"""###..
..#..
..#..
..###
....."""

print(A(H(case1_1), H(case1_2))) # Prints 2

Explanation

The algorithm used here is a little better than brute force by caching sub-shapes. For a given shape, it caches all the ways to split that shape into two contiguous shapes, I then normalise these shapes (shift the coordinates so it starts at the origin, then find a rotation/reflection of it which is used in the cache) and store them in the cache to look up quickly later. All sub-shapes then have their sub-shapes cached as well until it gets to the single block shape.

These sub-shapes are generated by converting it to a graph adjacency list and using a BFS to generate all sub-graphs. We can then filter these subgraphs to ones where the vertices which weren't included are a connected component. Determining whether the graph is connected is done with another BFS.

After the cache is complete, the solution is found by comparing the two shapes to find the sub-shapes that it has in common. Once it has these list of sub-shapes, it takes the pair of sub-shapes left over after removing the common shape and recursively applies the same algorithm again to find the minimum number of blocks needed to reconstruct the shape. This then returns the sub-shape with the minimum of all those values and we have our solution.

I've put an annotated version below to kinda explain what each line is doing.

B=frozenset
M=min
# Shapes are stored as a frozenset of tuples where each tuple represents an (x, y) position
# Cache of shape partitions. This is a two-level dictionary where the outer key is a shape, and the inner key is a sub-shape where the value is a list of the shapes left when the sub-shape is removed.
# there may be multiple shapes in the inner-most list if the sub-shape appears multiple times
X={}
# Transpose list of coords (flip around diagonal axis)
T=lambda s:((x,y)for y,x in s)
# Translate shape so its upper-left corner is at the origin
N=lambda s:B((x-M(s)[0],y-M(T(s))[0])for x,y in s)
# Convert shape to graph in adjacency list form
G=lambda s:{(x,y):s&{(x-1,y),(x+1,y),(x,y-1),(x,y+1)}for(x,y)in s}
# Check if graph is connected given a set of nodes, s, known to be connected
C=lambda g,s,i=0:i<=len(g)and(len(g)==len(s)or C(g,s.union(*map(g.get,s)),i+1))
# Flip shape around vertical axis
F=lambda s:N([(-x,y)for x,y in s])
# Converts shape to the minimal reflection or rotation. rotation is equivalent to transpose then flip.
P=lambda s,i=4:M([N(s),F(s),P(F(T(s)),i-1)],key=list)if i else s
# returns all the contiguous sub-shapes of s that contain the first pos, given by next(iter(s))
S=lambda s,t=B(),i=0:t|S(s,B().union(u|{p}for u in t for p in s-u if C(G(u|{p}),{p}))if i else B([B([next(iter(s))])]),i+1)if-~i<len(s)else t
# updates the sub-shape cache, X, recursively for an input shape s
def U(s):
 k=P(s)
 if k in X:return
 j=[t for t in S(k)if C(G(k-t),{next(iter(k-t))})];X[k]={P(t):B()for t in j}
 for t in j:X[k][P(t)]|=B([B(P(k-t))]);U(t);U(k-t)
# Gets the minimum number of partitions for two shapes
V=lambda s,t:1+M(V(v,w)for u in B(X[s])&B(X[t])for v in X[s][u]for w in X[t][u])if s^t else 1
# The function to run, will update the cache for the two input shapes then return the minimum number of partitions
A=lambda s,t:U(s)or U(t)or V(P(s),P(t))


Implementing the SHA-1 hash algorithm The goal of this code-golf is to create a program that takes a string as input, and you have to output the SHA-1 hash value as a hexadecimal number. You can find the pseudocode for SHA-1 here

Other rules:

No network access
You're not allowed to run external programs
You're not allowed to use built-in methods to hash the input
The shortest code wins
It's only necessary to handle ASCII input
Output can be either lowercase or uppercase
The input can be provided using:

Prompting for input
Using command-line arguments
Using STDIN

Test cases:

Input: The quick brown fox jumps over the lazy dog
Output: 2fd4e1c67a2d28fced849ee1bb76e7391b93eb12
----------------------------------------------------------
Input: The quick brown fox jumps right over the lazy dog
Output: 1c3aff41d97ada6a25ae62f9522e4abd358d741f
------------------------------------------------------------
Input: This is a code golf challenge
Output: f52ff9edd95d98e707bd16a7dead459cb8db8693


Is my barcode valid? An EAN-8 barcode includes 7 digits of information and an 8th checksum digit.

The checksum is calculated by multiplying the digits by 3 and 1 alternately, adding the results, and subtracting from the next multiple of 10.

For example, given the digits 2103498:

Digit:        2   1   0   3   4   9   8
Multiplier:   3   1   3   1   3   1   3
Result:       6   1   0   3  12   9  24

The sum of these resulting digits is 55, so the checksum digit is 60 - 55 = 5

The Challenge

Your task is to, given an 8 digit barcode, verify if it is valid - returning a truthy value if the checksum is valid, and falsy otherwise.

You may take input in any of the following forms:

A string, 8 characters in length, representing the barcode digits
A list of 8 integers, the barcode's digits
A non-negative integer (you can either assume leading zeroes where none are given, i.e. 1 = 00000001, or request input with the zeroes given)

Builtins that compute the EAN-8 checksum (i.e, take the first 7 digits and calculate the last) are banned.
This is code-golf, so the shortest program (in bytes) wins!

Test Cases

20378240 -> True
33765129 -> True
77234575 -> True
00000000 -> True

21034984 -> False
69165430 -> False
11965421 -> False
12345678 -> False

JavaScript (ES6), 41 40 38 bytes
Saved 2 bytes thanks to @ETHProductions and 1 byte thanks to @Craig Ayre.
s=>s.map(e=>t+=e*(i^=2),t=i=1)|t%10==1

Takes input as a list of digits.
Determines the sum of all digits, including the checksum.
If the sum is a multiple of 10, then it's a valid barcode.
Test Cases

let f=

s=>s.map(e=>t+=e*(i^=2),t=i=1)|t%10==1

console.log(f([2,0,3,7,8,2,4,0]));
console.log(f([3,3,7,6,5,1,2,9]));
console.log(f([7,7,2,3,4,5,7,5]));
console.log(f([0,0,0,0,0,0,0,0]));

console.log(f([2,1,0,3,4,9,8,4]));
console.log(f([6,9,1,6,5,4,3,0]));
console.log(f([1,1,9,6,5,4,2,1]));
console.log(f([1,2,3,4,5,6,7,8]));


MATL, 20 15 13 12 bytes

t1Y6Z+tuX>=)

Saved 5 bytes thanks to Emigna, 2 thanks to Giuseppe, and another thanks to Luis Mendo.
Try it online!

Explanation

t1Y6Z+tuX>=)
t                  Duplicate the (implicit) input.
 1Y6               Push the array [0 1 0; 1 0 1; 0 1 0].
    Z+             Convolve with the input.
       uX>         Get the maximum unique element...
      t   =        ... and compare elementwise.
           )       Index into the input.


Element of string at specified index Given a string s and a non-negative number n less than the length of s, output the character at the n-th position of s.

0-indexing and 1-indexing are allowed. For 1-indexing, n will be positive and less than or equal to the length of s.

s will consist of printable characters only.

Any reasonable input/output is permitted. Standard loopholes apply.

Testcases (0-indexing):

n s        output
0 "abcde"  a
1 "abcde"  b
2 "a != b" !
3 "+-*/"   /
4 "314159" 5

Testcases (1-indexing):

n s        output
1 "abcde"  a
2 "abcde"  b
3 "a != b" !
4 "+-*/"   /
5 "314159" 5

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

MATL, 1 byte

)

Try it online!

Well, hard to make it much simpler. ) indexes the first input, using the second input value. This is 1-indexed.


The Non-Zero Digital Product Challenge Originally the Multiplicative digital root
Challenge
Basically do what the title says
Method
Given a positive integer  1 <= N <= 100000000 through one of our standard input methods, multiply every digit together, ignoring zeroes.
Ex: Take a number, say 361218402:

3 * 6 = 18
18 * 1 = 18
18 * 2 = 36
36 * 1 = 36
36 * 8 = 288
288 * 4 = 1152
1152 * 1 (ignore zeroes or turn them into ones) = 1152
1152 * 2 = 2304

The output for 361218402 is 2304
Test Cases

1 => 1
every other digit > 0 => itself
10 => 1
20 => 2
100 => 1
999 => 729
21333 => 54
17801 => 56
4969279 => 244944
100000000 => 1

Standard Loopholes are disallowed, and this is code-golf, so shortest byte count wins!
Congrats to Jo King who got the bounty with his 70 byte brain-flak answer!

Haskell, 27 bytes

foldr((*).max 1.read.pure)1

Try it online!

Ungolfed with UniHaskell and -XUnicodeSyntax

import UniHaskell

f ∷ String → Int
f = product ∘ map (max 1 ∘ read ∘ pure)

Explanation

I'll start with what I initially had:

product.map(max 1.read.pure)

This is a point-free expression that evaluates to a function taking a string (or a list of characters) s ("301") as an argument. It maps max 1.read.pure over s, essentially taking each character i, injecting it into a list (which makes it a string) (["3", "0", "1"]), then reading it, which evaluates the string ([3, 0, 1]) and finally taking the greater of i and 1 ([3, 1, 1]). Then it takes the product of the resulting list of integers (3).

I then golfed it by a byte with:

foldr((*).max 1.read.pure)1

This works because product is equivalent to foldr (*) 1. Instead of mapping and folding, I combined the two by folding with (*).max 1.read.pure which takes each non-zero digit and multiplies it with the accumulator.


Sorting a list of strings without using any built-in sort method The goal of this Code Golf is to create a program that sorts a list of strings (in ascending order), without using any built-in sort method (such as Array.Sort() in .NET, sort() in PHP, ...).  Note that this restriction excludes using a built-in method that sorts an array descending, and then reversing the array.

Some details:

Your program should prompt for input, and this input is a list of strings containing only ASCII lower-case alphabetic characters a-z, comma-separated without spaces. For example:

code,sorting,hello,golf

The output should be the given list of strings, but sorted in ascending order, still comma-separated without spaces. For example:

code,golf,hello,sorting

Ruby 76 54 51 chars

x=gets.scan /\w+/;$><<x.dup.map{x.delete(x.min)}*?,


Make my pseudocode real I've got some Java pseudocode that uses whitespace instead of curly braces, and I want you to convert it.
I/O
Your program should take an input file along with a number designating how many spaces are used to indent a block. Here's an example:

$ convert.lang input.p 4
// Convert using 4 spaces as the block delimiter
$ convert.lang input.p 2
// Convert using 2 spaces as the block delimiter

It should then convert the result using the specified block delimiter and output the result to stdout.
The meat of the program
Blocks open with : and each line within the block is indented using the block delimiter, like Python code.

while(true):
    System.out.println("Test");

Each : is replaced with a  {, and a } is appended to the end of the block.

while(true) {
    System.out.println("Test");
}

Examples
Input:

public class Test:
    public static void main(String[] args):
        System.out.println("Java is verbose...");
Output:

$ convert Test.pseudojava 4
public class Test {
    public static void main(String[] args) {
        System.out.println("Java is verbose...");
    }
}
Input:

main():
  printf("Hello World");

Output:

$ convert test.file 2
main() {
  printf("Hello World");
}
Input:
def generic_op(the_stack, func):
    # Generic op handling code
    b = the_stack.pop()
    if isinstance(b, list):
        if b:
            return
        top = b.pop(0)
        while b:
            top = func(top, b.pop(0))
        the_stack.push(top)
    else:
        a = the_stack.pop()
        return func(a, b)
Output:

$ convert code.py 4
def generic_op(the_stack, func){
    # Generic op handling code
    b = the_stack.pop()
    if isinstance(b, list) {
        if b {
            return
        }
        top = b.pop(0)
        while b {
            top = func(top, b.pop(0))
        }
        the_stack.push(top)
    }
    else {
        a = the_stack.pop()
        return func(a, b)
    }
}

Scoring
The code with the least amount of bytes wins!

Perl, 41 bytes

#!perl -p0
1while s/( *).*\K:((
\1 .*)+)/ {\2
\1}/

Counting the shebang as two, input is taken from stdin. A command line argument need not be provided. Any valid nesting context can be determined (and matched) without knowing the indentation size.

Regex Break-Down

( *)                   # as many spaces as possible (\1)
    .*                 # as many non-newline characters as possible \
                         (greediness ensures this will always match a full line)
      \K               # keep all that (i.e. look-behind assertion)
        :              # colon at eol (newline must be matched next)
         (
          (
           \n\1        # newline with at least one more space than the first match
                .*     # non-newlines until eol
                  )+   # as many of these lines as possible
                    )  # grouping (\2)

Sample Usage

in1.dat

public class Test:
    public static void main(String[] args):
        System.out.println("Java is verbose...");

Output

$ perl py2java.pl < in1.dat
public class Test {
    public static void main(String[] args) {
        System.out.println("Java is verbose...");
    }
}

in2.dat

main():
  printf("Hello World");

Output

$ perl py2java.pl < in2.dat
main() {
  printf("Hello World");
}

in3.dat

def generic_op(the_stack, func):
    # Generic op handling code
    b = the_stack.pop()
    if isinstance(b, list):
        if b:
            return
        top = b.pop(0)
        while b:
            top = func(top, b.pop(0))
        the_stack.push(top)
    else:
        a = the_stack.pop()
        return func(a, b)

Output

$ perl py2java.pl < in3.dat
def generic_op(the_stack, func) {
    # Generic op handling code
    b = the_stack.pop()
    if isinstance(b, list) {
        if b {
            return
        }
        top = b.pop(0)
        while b {
            top = func(top, b.pop(0))
        }
        the_stack.push(top)
    }
    else {
        a = the_stack.pop()
        return func(a, b)
    }
}


Help the architects visualize the skyline As part of a city planning project, you've gotten the assignment of creating a program or function that will display the city skyline, given some input from the architects. The project is only in the startup phase, so a very rough sketch is sufficient. The easiest approach is of course to simply draw the skyline in ASCII-art.

All buildings will be by the river, thus they are all aligned. The architects will give the height of each building as input, and your code should display the skyline.

The input from the architects will either be an integer or a half-integer. If the number is an integer, the building will have a flat roof, while a half-integer will result in a pitched roof. A zero will just be flat ground. The walls of a building are 3 characters apart, while a zero will be a single character wide. Adjacent buildings share walls.

For details and clarifications regarding the output, please have a look at the examples below:

N = 3
 ___
|   |
|   |
|___|

N = 3.5
  _
 / \
|   |
|   |
|___|

N = 6
 ___
|   |
|   |
|   |
|   |
|   |
|___|

n = 0
_

Example input: 3 3.5 0 2

      _
 ___ / \
|   |   |  ___
|   |   | |   |
|___|___|_|___|

Example input: 0 0 2.5 3 0 4 1

             ___
    _  ___  |   |
   / \|   | |   |
  |   |   | |   |___
__|___|___|_|___|___|

Louisville, 0 2 1 3.5 0 4 2 4 2 4 6 1 6 0 5 1

                                    ___     ___
                                   |   |   |   |  ___
           _    ___     ___     ___|   |   |   | |   |
          / \  |   |   |   |   |   |   |   |   | |   |
  ___    |   | |   |___|   |___|   |   |   |   | |   |
 |   |___|   | |   |   |   |   |   |   |___|   | |   |___
_|___|___|___|_|___|___|___|___|___|___|___|___|_|___|___|

The ASCII-characters used are: newline, space, and /\_| (code points 10, 32, 47, 92, 95, 124).

Rules:

It's optional to make a program that only take integers as input, by multiplying all numbers by two. So, instead of taking 3 3.5 2, your program may take 6 7 4. If the second input format is chosen, an input of 6 should result in a 3 story building, 7 should be a 3 story building with pitched roofs etc.
The output should be exactly as described above, but trailing spaces and newlines are OK.
The exact format of the input is optional. Whatever is best in your language.
The result must be displayed on the screen, so that the architects can have a look at it.
You can assume there will be at least one integer given, and that only valid input will be given.

This is codegolf, so the shortest code in bytes win.

MATLAB, 219 209 203 bytes
i=input('');x=1;c=0;m(1:4*numel(i))='_';for a=i;b=fix(a);m(1:b,x)='|';s=95;if a~=b;m(b+2,x+2)=95;s='/ \';end;m(b+1,x+(1:3))=s;x=x+(a>0)*3+1;m(1:b,x)='|';x=x+(a<1&c>0);c=a;end;disp(flipud(m(:,1:x-(a<1))))

This unfortunately doesn't work on Octave. Not entirely sure why, seems to be something to do with the disp/flipud bit that breaks.
Also, there is currently no definition of what a 0.5 height building looks like, nor any mention of them, so in this code I assume that they are disallowed.
The following is the code in a slightly more readable way:
i=input(''); %e.g. [0 0 2 1 3.5 0 4 2 4 2 4 6 1 6 0 5 1 0 0 1 0]
x=1;
c=0;
m(1:4*numel(i))='_';
for a=i;
    b=fix(a);
    m(1:b,x)='|';
    s=95;
    if a~=b;
        m(b+2,x+2)=95;
        s='/ \';
    end;
    m(b+1,x+(1:3))=s;
    x=x+(a>0)*3+1;
    m(1:b,x)='|';
    x=x+(a<1&c>0);
    c=a;
end;
disp(flipud(m(:,1:x-(a<1))))

First we take an input as an array, and do some variable initialisation.
i=input(''); %e.g. [0 0 2 1 3.5 0 4 2 4 2 4 6 1 6 0 5 1]
x=1;
c=0;

Because the zero height buildings are a pain - they basically end up with a width which is dependent on what they are next to (though what is printed doesn't change), we simplify things by drawing enough ground for all of the buildings. We assume each building will be 4 characters wide (because adjacent buildings merge together) - zero height ones aren't, but the excess will be trimmed later.
m(1:4*numel(i))='_';

Now we draw out each building in turn.
for a=i

First we get the integer part of the height as this will determine how many '|' we need.
    b=fix(a);

Now draw in the wall for this building - if there are two adjacent buildings, the wall for this new one will be in the same column as the wall from the last one.
    m(1:b,x)='|';

Check to see if this is a half height building. If it is, then the roof will be different. For the half heights, the roof is going to be / \ whereas full height ones it will be ___ (Matlab will implicitly replicate this from a single underscore, so save a couple of bytes there). There is an extra bit of roof one row higher for the half height buildings, so that is added as well.
    s=95;
    if a~=b;
        m(b+2,x+2)=95;
        s='/ \';
    end;

Draw in the roof
    m(b+1,x+(1:3))=s;

Now move to the start of the next building and draw in the shared wall (if the wall is too short at this point, it will be made larger when the next building is drawn). Note that zero height buildings are 1 wide, normal buildings are 4 wide, so we simplify what would otherwise be an if-else by treating (a>0) as a decimal number not a Boolean.
    x=x+(a>0)*3+1;
    m(1:b,x)='|';

Next comes a bit of hackery to work with zero height buildings. Basically what this says is if this building was zero height, and the one before that wasn't, it means the place of the next building needs incrementing by 1 because a zero height building sandwiched between two other buildings is effectively twice as wide - this accounts for the extra wall which is normally shared with an adjacent building. We also keep track of this building height for doing this check next time.
    x=x+(a<1&c>0);
    c=a;
end;

Once done, flip the building matrix to be the correct way up, and display it. Note that we also trim off any excess ground here as well.
disp(flipud(m(:,1:x-(a<1))))

So, when we run this script, we are asked for our input, for example:
[0 0 2 1 3.5 0 4 2 4 2 4 6 1 6 0 5 1 0 0 1 0]

It then generates the building and displays the result. For the above input, the following is generated:
                                     ___     ___
                                    |   |   |   |  ___
            _    ___     ___     ___|   |   |   | |   |
           / \  |   |   |   |   |   |   |   |   | |   |
   ___    |   | |   |___|   |___|   |   |   |   | |   |
  |   |___|   | |   |   |   |   |   |   |___|   | |   |___    ___
__|___|___|___|_|___|___|___|___|___|___|___|___|_|___|___|__|___|_


Elastic collisions between blocks The 3Blue1Brown Youtube channel released a video a year ago called "Why do colliding blocks compute pi?" which describes a model where a block A of mass \$a\$ slides into a block B of mass \$b\$, which then pushes block B into a wall, causing it to bounce off the wall and then collide again with block A.

The miracle of this process is that if \$a/b = 10^{2n-2}\$ the number of total collisions (both between A and B and between B with the wall) is given by the first \$n\$ digits of \$\pi\$.

Example output

+-------+---+--------+
| a     | b | output |
+-------+---+--------+
| 1     | 1 | 3      |
| 2     | 1 | 5      |
| 3     | 1 | 5      |
| 4     | 1 | 6      |
| 5     | 1 | 7      |
| 10    | 3 | 6      |
| 7     | 2 | 6      |
| 9     | 2 | 7      |
| 1     | 2 | 3      |
| 1     | 5 | 2      |
| 100   | 1 | 31     |
| 10000 | 1 | 314    |
+-------+---+--------+

(These values were calculated using this web applet from Reddit user KyleCow1. Please let me know if I've made any mistakes.)

Challenge

Your challenge is to take two positive integers \$a, b \in \mathbb N_{>0}\$, and output the number of collisions in this scenario. Your program should be able to handle all \$a, b \leq 10\,000\$. This is a code-golf challenge, so the shortest program wins.

APL (Dyalog Classic), 18 16 bytes

¯1+⌈○÷¯3○.5*⍨⎕÷⎕

Try it online!

rendered as the equivalent {¯1+⌈○÷¯3○.5*⍨⍵÷⍺} in the tio link, to facilitate testing; ⎕ means evaluated input; ⍺ and ⍵ are the arguments to an anonymous function

$$\left\lceil\frac\pi{\textrm{arctg}\sqrt\frac ba}\right\rceil-1$$

(that's the formula from the video. i recommend watching it. it's well explained and the animations are great for building intuition.)


Golfed+Fast sorting in C [Latest update: benchmark program and preliminary resuls available, see below]

So I want to test the speed/complexity tradeoff with a classic application: sorting.

Write an ANSI C function that sorts an array of floating point numbers in increasing order.

You can't use any libraries, system calls, multithreading or inline ASM.

Entries judged on two components: code length and performance. Scoring as follows: entries will be sorted by length (log of #characters without whitespace, so you can keep some formatting) and by performance (log of #seconds over a benchmark), and each interval [best,worst] linearly normalised to [0,1]. The total score of a program will be the average of the two normalised scores. Lowest score wins. One entry per user.

Sorting will have to (eventually) be in place (i.e. the input array will have to contain sorted values at return time), and you must use the following signature, including names:

void sort(float* v, int n) {

}

Characters to be counted: those in the sort function, signature included, plus additional functions called by it (but not including testing code).

The program must handle any numeric value of float and arrays of length >=0, up to 2^20.

I'll plug sort and its dependencies into a testing program and compile on GCC (no fancy options). I'll feed a bunch of arrays into it, verify correctness of results and total run time. Tests will be run on an Intel Core i7 740QM (Clarksfield) under Ubuntu 13.
Array lengths will span the whole allowed range, with a higher density of short arrays. Values will be random, with a fat-tail distribution (both in the positive and negative ranges). Duplicated elements will be included in some tests.
The test program is available here: https://gist.github.com/anonymous/82386fa028f6534af263
It imports the submission as user.c. The number of test cases (TEST_COUNT) in the actual benchmark will be 3000. Please provide any feedback in the question comments.

Deadline: 3 weeks (7 April 2014, 16:00 GMT). I will post the benchmark in 2 weeks.
It may be advisable to post close to the deadline to avoid giving away your code to competitors.

Preliminary results, as of benchmark publication:
Here are some results. The last column shows the score as a percentage, the higher the better, putting Johnny Cage in first place. Algorithms that were orders of magnitude slower than the rest were run on a subset of tests, and time extrapolated. C's own qsort is included for comparison (Johnny's is faster!). I'll perform a final comparison at closing time.

150 character

Quicksort.

/* 146 character.
 * sizeup 1.000; speedup 1.000; */
#define REC_SIZE    \
    sort(l, v+n-l); \
    n = l-v;

/* 150 character.
 * sizeup 1.027; speedup 1.038; */
#define REC_FAST  \
    sort(v, l-v); \
    n = v+n-l;    \
    v = l;

void sort(float* v, int n)
{
    while ( n > 1 )
     {
       float* l = v-1, * r = v+n, x = v[n/2], t;
L:
       while ( *++l < x );
       while ( x < (t = *--r) );

       if (l < r)
        {
          *r = *l; *l = t;
          goto L;
        }
       REC_FAST
     }
}

Compressed.

void sort(float* v, int n) {
while(n>1){float*l=v-1,*r=v+n,x=v[n/2],t;L:while(*++l<x);while(x<(t=*--r));if(l<r){*r=*l;*l=t;goto L;}sort(v,l-v);n=v+n-l;v=l;}
}


ASCII Hangman in Progress (inspired by a question over on Code Review)

Suppose two people are playing Hangman, but you've only overheard the game and want to draw the current status.

Given two words as input, where the words each match [A-Z]+ or [a-z]+ (your choice), output the current state of the hangman game as ASCII art, following the below rules.

The first word is the word to be guessed, and the second word is the already-guessed letters. These can be taken as input in any order.
The word to be guessed is guaranteed non-empty, but the already-guessed letters may be empty (i.e., as if it's the start of the game).
The game will always be a valid hangman game (i.e., guessed letters won't be duplicated, letters won't be guessed past the end of the game, you'll only receive letters as input, etc.).
Below the hangman drawing must be the word to be guessed, with _ in place of letters yet unknown, separated by spaces. For example, if the word to be guessed was BOAT, then below the hangman drawing must be _ _ _ _. If the word was BOAT with A guessed, then below the drawing must be _ _ A _.
Below the word to be guessed must be letters already guessed that are not in the word. These can be in any order, and can be separated by any non-alphabetical separator, if so desired.

Here are the states of the hangman game, from initial start to game end. Each wrongly guessed letter advances the state by one. So the first wrongly guessed letter makes the head O appear, the next makes the body | appear, etc.

  +---+
  |   |
      |
      |
      |
      |
=========

  +---+
  |   |
  O   |
      |
      |
      |
=========

  +---+
  |   |
  O   |
  |   |
      |
      |
=========

  +---+
  |   |
  O   |
 /|   |
      |
      |
=========

  +---+
  |   |
  O   |
 /|\  |
      |
      |
=========

  +---+
  |   |
  O   |
 /|\  |
 /    |
      |
=========

  +---+
  |   |
  O   |
 /|\  |
 / \  |
      |
=========

Input

Two strings in any convenient format, with the first guaranteed non-empty.
You can take the input in either order (e.g., word to guess and then guessed letters, or vice versa). Please state in your submission the input order.

Output

The resulting ASCII art representation of the hangman game in progress, as described above, again in any convenient format.

Rules

Leading or trailing newlines or whitespace are all optional, so long as the characters themselves line up correctly.
Either a full program or a function are acceptable. If a function, you can return the output rather than printing it.
If possible, please include a link to an online testing environment so other people can try out your code!
Standard loopholes are forbidden.
This is code-golf so all usual golfing rules apply, and the shortest code (in bytes) wins.

Examples

#1

BOAT and ATG

  +---+
  |   |
  O   |
      |
      |
      |
=========
_ _ A T
G

#2

ZEPPELIN and

  +---+
  |   |
      |
      |
      |
      |
=========
_ _ _ _ _ _ _ _

#3

ZEPPELIN and EATOLINSHR

  +---+
  |   |
  O   |
 /|\  |
 / \  |
      |
=========
_ E _ _ E L I N
A T O S H R

#4

RHYTHM and ABCDE

  +---+
  |   |
  O   |
 /|\  |
 /    |
      |
=========
_ _ _ _ _ _
EDCBA

#5

BOAT and ATOB

  +---+
  |   |
      |
      |
      |
      |
=========
B O A T

#6

AIRPLANE and AJKEI

  +---+
  |   |
  O   |
  |   |
      |
      |
=========
A I _ _ _ A _ E
KJ

Python 2, 215 192 184 183 bytes

-8 bytes thanks to Raphaël Côté
-1 byte thanks to Jonathan Frech

a,b=input()
j=' '.join
s=b-set(a)
print"""  +---+
  |   |
  %s   |
 %s%s%s  |
 %s %s  |
      |
=========
"""%tuple('O/|\/\\'[:len(s)].ljust(6)),j(['_',i][i in b]for i in a),'\n',j(s)

Try it online!


Repeat a rhyme and loop on the vowels Vowels rhyme: Apples and Bananas

There is a traditional children's song that repeats the same text over and over, only each time every vowel is replaced with a random vowel, but constant across the current stanza.

Challenge

The objective is to propose the shortest code that performs such a transformation on an input text.

Rules

You must print the rhyme as many times as there are distinct vowels in it.
Each print must be separated with a line break (platform-specific combo of \n and \r is accepted).
For iteration i, replace each vowel with the ith distinct vowel in the original text.
The input text is a sequence of printable ASCII characters (range [32, 126].
Input will not contain embedded line breaks.
Only vowels characters must be affected, other must be output exactly as input.
Only vowels characters count: nasal vowels, although sounding like vowels (like in French "Tintin"), must not be handled as a single vowel.
Case matters for the output, but is positional (replacing an uppercase vowel is done with the uppercase replacement vowel)
Uppercase vowels are not distinct from their lowercase counterpart (ie a <=> A)
Consecutive vowels are always considered separately (ie. Boat yields both Boot and Baat)
Since the letter y represents either a vowel or consonant soun (as we're speaking English), handling it as a vowel or a consonant is allowed, however answers must explicitly state whether they handle y as a vowel or not.

Examples:

Hello world

Hello world!

gives:

Helle werld!
Hollo world!

Excerpt from the original French text (translated), with y handled as a vowel:

An elephant that was rambling all gently in the woods...

gives:

An alaphant that was ramblang all gantla an tha waads...
En elephent thet wes rembleng ell gentle en the weeds...
In iliphint thit wis rimbling ill gintli in thi wiids...
Yn ylyphynt thyt wys rymblyng yll gyntly yn thy wyyds...
On olophont thot wos romblong oll gontlo on tho woods...

Note the behaviour on leading uppercase vowel: case is kept at its index (rules 8 and 9).

Vowelless example

Input that does not contain any vowel, like:

lgn@hst:~$ rm -rf ./* ~ /

must produce no output, or a single line break.

Single-vowel input

Input containing a single vowel is output as is.

Dad sat at a car and saw a fat bat.

gives:

Dad sat at a car and saw a fat bat.

This is code-golf, so fewest bytecount code wins (nothing but eternal PPCG glory)!

Retina, 45 bytes

~(K`A\EI\OU
L$`\\?(.)
./$1/i&$*\T`Vv`5*$&$L$&

Try it online! Does not count y as a vowel. Explanation:

K`A\EI\OU

Replaces the text with the literal string A\EI\OU.

L$`\\?(.)

Matches each letter optionally preceded by a backslash.

./$1/i&$*\T`Vv`5*$&$L$&

Outputs a line of Retina code for each letter.

~(

Evaluates the generated code (shown below) using the original input. The . causes the code not to output the (final) buffer. The /<vowel>/i& causes the rest of the line to run only if the input contains the given vowel (case-insensitively). The * causes the result of the line to be ignored, so that the next vowel can be tested. The \ causes the result to be printed on its own line before it is ignored. The T`Vv`AAAAAa transliterates uppercase Vowels to AAAAAs and all lowercase vowels to a. \A is an escape that refers to ASCII 07 (BEL), but E, O and o are built-in character classes that needs to be escaped to give their literal values (e is not a character class, but fortunately it is also not an escape.)

./A/i&*\T`Vv`AAAAAa
./E/i&*\T`Vv`\E\E\E\E\E\e
./I/i&*\T`Vv`IIIIIi
./O/i&*\T`Vv`\O\O\O\O\O\o
./U/i&*\T`Vv`UUUUUu


Sort a string, sort of If you sort a string you'll typically get something like:
         ':Iaaceeefggghiiiiklllllmnnooooprrssstttttuuyyyy

Yes, that was the first sentence sorted.
As you can see, there are a lot of repeated characters, aa, eee, ttttt, 9 spaces and so on.
If we add 128 to the ASCII-value of the first duplicate, 256 to the second, 384 to the third and so on, sort it again and output the new string (modulus 128 to get the same characters back) we get the string:
 ':Iacefghiklmnoprstuy aegilnorstuy egilosty iloty lt

(Note the single leading space and the 4 trailing spaces).
The string is "sequentially sorted" <space>':I....uy, <space>aeg....uy, <space>egi....ty, <space>iloty, <space>lt, <space>, <space>,<space>, <space>.
It might be easier to visualize this if we use a string with digits in it. The string 111222334 will when "sorted" be: 123412312.
Challenge:
To no surprise, the challenge is to write a code that sorts a string according to the description above.
You can assume that the input string will contain only printable ASCII-characters in the range 32-126 (space to tilde).

Test cases:
**Test cases:**
 *:Tacest*es*s*

If you sort a string you'll typically get something like:
 ':Iacefghiklmnoprstuy aegilnorstuy egilosty iloty lt

Hello, World!
 !,HWdelorlol

#MATLAB, 114 bytes
 #,14ABLMTbesty 1A

f=@(s)[mod(sort(cell2mat(cellfun(@(c)c+128*(0:nnz(c)-1),mat2cell(sort(s),1,histc(s,unique(s))),'un',0))),128),''];
'()*+,-0128:;=@[]acdefhilmnoqrstuz'(),0128@acefilmnorstu'(),12celmnostu'(),12celnstu(),clnst(),cls(),cs(),()()()()

This is code-golf, so the shortest code in each language counted in bytes will winref.

Pyth, 5 bytes

s.T.g

Test suite

Very straightforward: Group and sort, transpose, concatenate.

s.T.g
s.T.gkQ    Implicit variables
   .gkQ    Group the input input lists of elements whose values match when the
           identity function is applied, sorted by the output value.
 .T        Transpose, skipping empty values. This puts all first characters into
           a list, then all second, etc.
s          Concatenate.


Find the area of the largest convex polygon Given a list of integer coordinates, find the area of the biggest convex polygon you can construct from the list such that -

every vertex is in the list
no element of the list is contained within the polygon.

Example:

  (0, 0) (8, 0) (0, 1) (3, 1) (7, 1) (1, 2) (5, 2) (9, 2) (2, 3) (5, 3) (7, 3) (3, 4) (5, 5) (11, 5)

Visualized:

o       o
o  o   o
 o   o   o
  o  o o
   o
     o     o

The biggest convex polygon you can make from this is this:

o
o  o
 o   o
  o  o
   o
     o

With an area of 12.

You may take the list of coordinates in any reasonable format, and should output (in an appropriate way for your language of choice) the area of the largest convex polygon, rounded to no less than 2 digits after the decimal point.

Additionally, you must employ some sort of algorithm, and not simply brute force all subsets of the points. To enforce this, your program must solve a list of 50 vertices in under a minute on a modern PC.

Shortest code in bytes wins.


Replace me by the sum of my cyclic successors! I have a simple challenge for you this time. Given an array of positive integers A (or the equivalent in your language), replace each entry Ai with the sum of the next Ai elements of A, cycling back from the beginning if there are not enough items.

As usual, you can compete in any programming language and can take input and provide output through any standard method and in any reasonable format, while taking note that these loopholes are forbidden by default. You may optionally take the size of A as input too. This is code-golf, so the shortest submission (in bytes) for every language wins.

Examples / Test Cases

Given [1,3,4,5], your code should output [3,10,13,14], because 1 is replaced by 3, 3 is replaced by 4+5+1=10 (notice how it wrapped back from the start), 4 by 5+1+3+4=13 and 5 by 1+3+4+5+1=14.

Given [3,2,1,9], your program should produce [12,10,9,33], because we substitute 3 with 2+1+9=12, 2 with 1+9=10, 1 with 9 and 9 with 3+2+1+9+3+2+1+9+3=33 (notice how we wrapped back from the start more than once).

Some more test cases for you to choose from:

[4,3,2,1]                       -> [10,7,5,4]
[3,2,1,9]                       -> [12,10,9,33]
[1,3,4,5]                       -> [3,10,13,14]
[4,4,3,2,2]                     -> [11,11,8,6,8]
[3,5,3,2,1]                     -> [10,14,6,4,3]
[3,2,4,3,2,1,1]                 -> [9,7,7,4,2,1,3]
[7,8,6,5,4,3,2,1,5]             -> [29,33,20,15,11,8,6,5,30]
[28,2,4,2,3,2,3,4,5,3]          -> [137,6,10,5,9,7,12,38,39,34]
[1,2,3,4,5,4,3,2,1,2,3,4,3,2,1] -> [2,7,13,14,12,8,5,3,2,7,9,7,4,2,1]

MATL, 10 9 bytes

"G@:X@+)s

Try it online!

	% implicit input
"	% for loop, iterate over the input array
G	% push input x
@	% push for loop index, x[i]
:	% range, push [1,...,x[i]]
X@	% push for loop index, i
+	% sum, so stack holds [i+1,...,i+x[i]]
)	% index, modularly, so gets the cyclic successors
s	% sum cyclic successors, leaving the sum on the stack
	% implicit end of for loop
	% implicit output of stack


Find the largest contiguous prime in a string In fairness, this is based on a StackExchange question - but its a good question.

The challenge is fairly simple:

Take a string of numerals
Find and print the largest contiguous prime number in the string

Scoring:

Lowest number of characters wins.
Victor will likely be a golfscript entry but we won't hold that against them, cause we all have fun and learn things, right.
Winner we be awarded when I notice that I haven't actually ticked the green button.

Assumptions:

The string is only numbers

If the string contains letters, you may have undefined behaviour

The string contains at least 1 prime

If the string does not contains 1 valid prime number, you may have undefined behaviour

Speed is not a constraint

Use a shorter prime algorithm over a faster one.
If your entry eventually finishes, thats ok, just make sure it will provable happen before the heat death of the universe.

The length of the string can be assumed less than 15 characters long

For example:

>> Input:  3571
<< Output: 3571

>> Input:  123
<< Output: 23

>> Input:  1236503
<< Output: 236503

>> Input:  46462
<< Output:  2

>> Input:  4684
<< Output: ValueError: max() arg is an empty sequence

>> Input:  460
<< Output: 0   # Note, zero is not a prime, but the above string has no valid prime

>> Input:  4601
<< Output: 601

>> Input:  "12 monkeys is a pretty good movie, but not as good as se7en"
<< Output: ValueError: Fight Club was also good, I find Brad Pitt to be a consistantly good actor.

Possible implementations:

Find all substrings of the input, check if they are prime. - Legostormtroopr (original)
Find all integers less than input, check if they are in the input then check if it is prime - Ben Reich
Take a list of all primes less than the input, check if it is in the input - daniero

GolfScript 40 37

.{`\`?)}+\~),\,{.,(;\{\%!}+,,1=},)\;

This looks at all numbers less than or equal to the the input, filters down to the ones that are substrings of the input, and then filters further down to the primes.  Then, it takes the largest such element (which is obviously guaranteed to have the most digits).

Let's break it down into two main sections:

.{`\`?)}+\~,\,

This part of the code filters down to all integers string contained in the input.  It uses grave accent to turn numbers into strings, and then ? to determine the index of the substring.  Since ? returns -1 in the case of no containment, increment using ) so that the output is 0 for non-substrings, which will behave nicely with the , filtering.

{.,(;\{\%!}+,,1=},

This part of the code filters down to the primes by counting the number of factors less than the given number (an integer is a factor only if number factor %! is 1.  A prime number will have exactly 1 factor strictly less than itself, so do 1=.

Since the numbers are in order, take the last one and clear the stack using )\;

This obviously isn't as efficient as possible (since it somewhat unnecessarily iterates over all integers less than the input), but it still terminates with big input like 1236503 relatively quickly on my computer (1 minute).


Are Pigs able to fly? Task

Your task is to write a function or a program in a language of your choice that analyzes a couple of statements and determines whether it can be concluded from those statements that pigs are able to fly.

Input

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

input = statement , {statement};
statement = (("Pigs are ", attribute) | ("Everything that is ", attribute, "is also ", attribute)), ". ";
attribute = [not], ("able to fly" | singleAttribute);
singleAttribute = letter, {letter};
letter = "a" | "b" | "c" | "d" | "e" | "f" | "g"
       | "h" | "i" | "j" | "k" | "l" | "m" | "n"
       | "o" | "p" | "q" | "r" | "s" | "t" | "u"
       | "v" | "w" | "x" | "y" | "z" ;

Example input (see more examples below):

Pigs are green. Everything that is green is also intelligent. Everything that is able to fly is also not intelligent. Pigs are sweet.

Output

The output can be returned by your function, be written to a file or print to STDOUT. There are 5 different cases to be handled:

The given statements are valid, consistent and have as a logical consequence that pigs can fly. In that case, you must output Yes.
The given statements are valid, consistent and have as a logical consequence that pigs can not fly. In that case, you must output No.
It can not be concluded from the given, valid and consistent statements whether pigs can fly or not. In that case, you must output Maybe.
The given statements are valid, but not consistent (i.e. there's a contradiction in the given statements). Since ex falso quodlibet, we decide to output Yes in that case.
The given statements are not valid, i.e. they are not formatted according to the given EBNF. In that case, you may do whatever you want.

Details

You may assume that the given attributes are independent from each other. So, for example, a pig may be young and old, green, red and blue at the same time without causing any inconsistency. However, a pig may not be 'green' and 'not green' at the same time, that's a contradiction and should be handled as described in (4).
For every attribute, assume that there is at least one object (not necessarily a pig) in the universe that has the given attribute, and one object that doesn't have it.

Example Inputs & Outputs

Input:

Pigs are green. Everything that is green is also intelligent. Everything that is able to fly is also not intelligent.

Output: Since Pigs are green and therefore intelligent, and everything that is able to fly is not intelligent, pigs cannot fly. Output is No.

Input:

Pigs are old. Everything that is not able to fly is also not old.

Output: If pigs were not able to fly, they were also not old. But as they are old, you must output Yes.

Input:

Everything that is sweet is also not old. Everything that is intelligent is also blue.

Output: Maybe.

Input:

Pigs are not able to fly. Everything that is red is also sweet. Everything that is sweet is also not red.

Output: Although the first statement implies that pigs can not fly, the following statements contradict each other and therefore the output must be Yes.

Input:

Pigs are very smart. Pigs are able to fly.

Output: Whatever you want, as the String doesn't match the criteria mentioned above.

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.

Perl, 363 353 350 347 343 297 266 264
$_=<>;s/able to fly/X/g;$m=' ?(not )?\b(P|\w+)';$h{$1?N.$2:$2}{$3?N.$4:$4}=$h{$3?$4:N.$4}{$1?$2:N.$2}=1while s/$m.{8}$m\.//;map{%x=0,r($_,$_)}%h;sub r{($a,$b)=@_;$e+=$h{$a}{N.$b};$x{$b}++or$h{$a}{$b}=1,map{r($a,$_)}%{$h{$b}}}print$e|$h{P}{X}?Yes:$h{P}{NX}?No:Maybe

Ungolfed/Explanation:
# Read one line from STDIN
$_=<>;
# Replaces special attribute with X
s/able to fly/X/g;
# Prepare attribute match
$m=' ?(not )?\b(P|\w+)';
# Match "Everything that is A is also B. "
#                        "\bA........ \bB\."
# Match "Pigs are B. "
#     "\bP........\bB\."
while(s/$m.{8}$m\.//)
{
  # Add facts for A => B and !B => !A, where A may equal "P" for "Pigs are"
  # Facts are stored as a hash of hashes %h; keys%h are the source attributes;
  # keys%{$h{$a}} are the attributes that follow from attribute $a
  # A "not attribute" is stored as "Nattribute", while a "attribute" is just stored as "attribute"
  $h{$1?N.$2:$2}{$3?N.$4:$4}=$h{$3?$4:N.$4}{$1?$2:N.$2}=1
}
# For all known source attributes ... (this should really be keys%h but we dont mind the extra hashrefs)
map{%x=0,r($_,$_)}%h;
sub r
{
  ($a,$b)=@_;
  # ... remember that we hit a negation and therefor an inconsistency ...
  # If we check/add $b and find an existing "N$b" that means that attribute $b is supposed to be true and not true at the same time
  # It is cheaper bytewise to just add up all consistency errors (remember each fact has a hard value of 1) than to exit right here
  $e+=$h{$a}{N.$b};
  # ... remember that we processed this attribute for the current source attribute so we prevent loops ...
  $x{$b}++or
  # ... add a new fact and then follow the chains (again omitting keys).
  $h{$a}{$b}=1,map{r($a,$_)}%{$h{$b}}
}
# Did we happen on an inconsistency? Do pigs fly? Dont pigs fly? Maybe (Bitwise or is okay too)
print$e|$h{P}{X}?Yes:$h{P}{NX}?No:Maybe


Tennis scores meets Code Golf In light of the 2014 Australian Open in Melbourne, and the win by Stanislas Wawrinka against Novak Djokovic, I propose the following code golf challenge!

Wawrinka and Djokovic are at it again for the basis of this CGC. Your challenge is to take a string consisting of 1's and 2's and determine the tennis scores based on the tennis scoring system. A "1" indicates that Wawrinka has scored a point, whereas a "2" indicates that Djokovic has scored a point.

For the sake of example: 1211222122111122111 will generate a two-line output:

Wawrinka 1 - 40
Djokovic 1 - 30

The longer the string, the further into the game the score is.

Rules:

Shortest code wins, pure and simple.
The scores when displayed must be right aligned and also column
aligned; e.g.
Sample alignment of output:

Wawrinka 7 5 3 -  0
Djokovic 6 7 4 - 15

If a game is in progress, the score must be displayed after the set scores. Game scores must follow set scores with a space-dash-space separator. If this happens to be the first game, a 0-0 set score must be displayed.

Wawrinka 0 -  0
Djokovic 0 - 15

A game will go in order of 0, 15, 30, 40, and game point. If a game reaches 40-40, a deuce is declared, and the score must display the deuce on the player row scoring the point:

Wawrinka 7 5 3 - 40
Djokovic 6 7 4 - 40 Deuce

If a deuce is reached, the next point will be an advantage to the player scoring the point:

Wawrinka 7 5 3 - Ad
Djokovic 6 7 4 - 40

The point after that, if scored by the advantaged player, wins the game, else the game goes back to deuce.
If more than one deuce is scored in between advantage points, the
number of the deuce will be indicated by a number in parentheses:

Wawrinka 7 5 3 - 40
Djokovic 6 7 4 - 40 Deuce (2)

A set is won if a player reaches 6 games or more and with a two game
margin in lead, e.g. 7-5, 6-4... 9-7 (In the case of last night's
fifth set)
Consecutive sets must be separated with a space.
There are tie breaks in the Australian Open, therefore if a 6-6 set is reached, a tie-break is established by the first player reaching seven points with a two point margin lead. Display of tie breaks are shown within square brackets as follows:

Wawrinka 7 6 [6]
Djokovic 6 6 [4]

The winner of the tie-break is said to have won the previous set 7-6.
If the fifth set reaches 6-6, play is continued without tie-break until a two game margin is reached with one player, that player being the winner of that set. There are NO tie-breaks in the fifth set.
If a player has won three sets, a third line will be displayed saying
Wawrinka wins or Djokovic wins depending on who has won and the code then terminates.

Wawrinka 2 6 6 3 9
Djokovic 6 4 2 6 7
Wawrinka wins

If the string ends such that the last point has won a game, set or
match, the game score is not displayed...

Wawrinka 7 5 3
Djokovic 6 7 4

If the string goes beyond a match being won, the rest of the string
is ignored, the score displayed and the winner declared.


Advent Challenge 4: Present Assembly Line! << Prev Next >>

Santa was able to remanufacture all of the presents that the elves stole overnight! Now he has to send them to the assembly line for packaging. He usually has a camera to supervise the assembly line both to make sure the elves are doing a good job and because assembly line pictures look nice on advertising posters [citation-needed]

Unfortunately, his camera broke, so he would like you to draw out a simulation of what the assembly line would look like!

In order to keep to assembly line working at maximum efficiency and to reduce the risk of error or failure, all present boxes have the same width so that they fit perfectly on the conveyor belt.

Challenge

Given a list of presents represented by their dimensions, output a conveyor belt with all of the presents.

A present is drawn like such:

  +----+
 /    /|
+----+ |
|    | +
|    |/
+----+

This present has width 1, height 2, and length 4. Note that the plus-signs don't count for the side-length, so a present with length 4 actually spans 6 positions.

All presents are drawn next to each other with one space between the closest two characters; that is, the bottom-left corners of the presents are spaced such that if a present box has length l and width w, the next present box's bottom-left corner will be exactly l + w + 4 positions right of the bottom-left corner of the previous box.

After all present boxes are drawn, the conveyor belt is drawn by replacing the space between boxes on each of the last width + 2 lines with underscores.

The final output for present boxes with (l, w, h) of [(4, 1, 2), (8, 1, 3), (1, 1, 1)] would be:

           +--------+
  +----+  /        /|
 /    /| +--------+ |   +-+
+----+ | |        | |  / /|
|    | +_|        | +_+-+ +
|    |/__|        |/__| |/
+----+___+--------+___+-+

Formatting Specifications

You can choose either to take a list of 3-tuples where one of the elements is consistent across the whole list (that would be the width), or you can take the present width and then a list of 2-tuples representing the length and height of each present. You can take the inputs in any order and in any reasonable format, but the presents must be displayed in the same order that they are given as input.

You may choose any reasonable output format for the ASCII-art (including returning from a function).

Test Cases

These test cases are given as [(l, w, h), ...] format.

[(4, 1, 2), (8, 1, 3), (1, 1, 1)]:

           +--------+
  +----+  /        /|
 /    /| +--------+ |   +-+
+----+ | |        | |  / /|
|    | +_|        | +_+-+ +
|    |/__|        |/__| |/
+----+___+--------+___+-+

[(5, 3, 4), (8, 3, 1), (1, 3, 7)]:

                               +-+
                              / /|
                             / / |
    +-----+                 / /  |
   /     /|                +-+   |
  /     / |                | |   |
 /     /  |     +--------+ | |   |
+-----+   |    /        /| | |   |
|     |   +___/        / +_| |   +
|     |  /___/        / /__| |  /
|     | /___+--------+ /___| | /
|     |/____|        |/____| |/
+-----+_____+--------+_____+-+

[(0, 0, 0)] (this is the most interesting test case ever :P)

 ++
+++
++

[(8, 3, 0), (0, 3, 8)] (more zero cases)

                   ++
                  //|
                 // |
                //  |
               ++   |
               ||   |
               ||   |
               ||   |
    +--------+ ||   |
   /        /+_||   +
  /        //__||  /
 /        //___|| /
+--------+/____||/
+--------+_____++

Rules

Standard Loopholes Apply
This is code-golf, so the shortest answer in bytes wins
No answer will be accepted

Note: I drew inspiration for this challenge series from Advent Of Code. I have no affiliation with this site

You can see a list of all challenges in the series by looking at the 'Linked' section of the first challenge here.

Charcoal, 96 81 bytes

ＮθＷＳ«→ＦυＧ↗→↙⁺²θ_≔Ｉ⪪ι υ≔⊟υπ≔§υ⁰ρ→↗Ｇ↑⊕π↗⊕θ→⊕ρ↓⊕π↙⊕θ ↑πＰ↗⊕θＰ←⊕ρ↓+↓πＦ²«↷⁴+ρ↷²+π↷¹+θ↶³

Try it online! Link is to verbose version of code. Input is the width on the first line, then the other dimensions on following lines, ending with a blank line. Explanation:

Ｎθ

Input the width.

ＷＳ«

Loop over the remaining lines until the blank line is reached.

→ＦυＧ↗→↙⁺²θ_

Draw the belt between presents. The u variable is predefined to an empty list, which therefore does nothing on the first pass, while later on it ends up with a single element, causing this code to run once. (Using an if would be less golfy.)

≔Ｉ⪪ι υ

Split the dimensions at the space, cast them to integer, and save them in u.

≔⊟υπ

Remove the last dimension and save it in p.

≔§υ⁰ρ

Copy the first dimension to r, but leave it in u so that the belt gets drawn on the next loop.

→↗Ｇ↑⊕π↗⊕θ→⊕ρ↓⊕π↙⊕θ

Erase the interior of the present, in case the belt overlaps it.

↑πＰ↗⊕θＰ←⊕ρ↓+↓π

Draw the interior lines of the present.

Ｆ²«↷⁴+ρ↷²+π↷¹+θ↶³

Draw halfway around the exterior of the present, then repeat for the other half.


Writing firewall rules Congratulations, you're now a network administrator! As your first task you will need to configure a firewall to stop any traffic to some blacklisted addresses.
Unfortunately, the only firewall at your disposal only takes in rules in this format:
x.y.z.t/m ALLOW
There's no DENY keyword. If you want to exclude a specific address, you'll have to write a lot of rules to allow everything except that address. If you want to exclude more than one address or a whole range, then you're in luck because these ALLOW rules will overlap to some degree.
The challenge
You are given a list of blacklisted IPs. Write a program that will print out rules for our firewall. Also, be sensible when writing rules: don't just enumerate all 256^4 and don't print out duplicates.
Code golf rules apply: shortest code wins
*this problem is inspired by a real life assignment; a friend actually needed this done
Example
To block address 0.1.2.3 you could write the following ALLOW rules (this is not the only solution possible, and it's certainly not the shortest):
0.1.2.0 ALLOW
0.1.2.1 ALLOW
0.1.2.2 ALLOW
0.1.2.4 ALLOW
...
0.1.2.255 ALLOW

0.1.0.0/24 ALLOW
0.1.1.0/24 ALLOW
0.1.4.0/24 ALLOW
...
0.1.255.0/24 ALLOW

0.0.0.0/16 ALLOW
0.2.0.0/16 ALLOW
...
0.255.0.0/16 ALLOW

1.0.0.0/8 ALLOW
...
255.0.0.0/8 ALLOW

Python3 - 325 chars

import sys
r=[(0,32)]
for b in (int('%02x'*4%tuple(int(x) for x in y.split('.')),16) for y in sys.stdin):
 i=0
 while i<len(r):l,q=r[i];o=2**q//2;m=l+o;h=m+o;k=l<=b<h;r[i:i+1]=[(l,q-k),(m,q-k)][0:k+1*(not l==h==b)];i+=1-k
for n,m in r:print('%s/%d ALLOW'%('.'.join(str(int(('%08x'%n)[i:i+2],16)) for i in range(0,8,2)),32-m))


Slowly turn a string into another The Challenge

Given two strings/an array of strings, output the first string slowly shrinking and expanding back into the second string.

You can assume the strings will always start with the same character.

Example

Input:
"Test", "Testing"

Output:
Test
Tes
Te
T
Te
Tes
Test
Testi
Testin
Testing

First you output the first word:

Test

Then you keep removing one letter until the string is one character long:

Tes
Te
T

Then keep adding one letter of the second word until it's done:

Te
Tes
Test
Testi
Testin
Testing

(if both strings are one character long, then just output one of them once.)

Test Cases

"Hello!", "Hi."
Hello!
Hello
Hell
Hel
He
H
Hi
Hi.

"O", "O"

O

"z", "zz"

z
zz

".vimrc", ".minecraft"

.vimrc
.vimr
.vim
.vi
.v
.
.m
.mi
.min
.mine
.minec
.minecr
.minecra
.minecraf
.minecraft

"     ", "   "

SSSSS
SSSS
SSS
SS
S
SS
SSS

"0123456789", "02468"

0123456789
012345678
01234567
0123456
012345
01234
0123
012
01
0
02
024
0246
02468

(note: on the space/fourth test case, replace the S with spaces)

Rules

This is code-golf, so shortest answer in bytes wins! Tiebreaker is most upvoted post. Winner will be chosen on 09/10/2016.
Standard loopholes are forbidden.

V, 14 bytes

òYp$xhòjòÄ$xhh

Try it online!

Explanation:

ò     ò     "Recursively:
 Yp         "  Yank the current line and paste it
   $        "  Move to the end of the current line
    x       "  Delete one character
     h      "  Move One character to the right.
            "  Because of the way loops work in V, this will throw an error if there
            "  Is only one character on the current line.

Now, the buffer looks like this:

0123456789
012345678
01234567
0123456
012345
01234
0123
012
01
0

We just need to do the same thing in reverse for the next line:

j           "Move down one line
 ò     ò    "Recursively (The second ò is implicit)
  Ä         "  Duplicate this line up
   $        "  Move to the end of the current line
    x       "  Delete one character
     hh     "  Move two characters to the right.
            "  Because of the way loops work in V, this will throw an error if there
            "  Is only two characters on the current line.

More interesting alternate solution:

òÄ$xhòç^/:m0
ddGp@qd


Fill a water balloon In this challenge, you must display ASCII art of a water balloon given the
amount of water that the balloon is filled with:

|  __||__  |
| / #   #\ |
| |######| |
| |######| |
| |######| |
| |######| |
| |######| |
| \######/ |
|          |
|          |
+----------+

How to draw the balloon

To display a balloon of size n, follow the following steps (note: whenever
the division symbol (/) is used, it represents integer division, rounding
down):

Draw a container consisting of ten vertical bars (|) on the left and right,
ten dashes (-) on the bottom, and a plus sign (+) in the bottom left and
bottom right corner. This makes the whole thing 12x11, and the "inside"
10x10.

|          |
|          |
|          |
|          |
|          |
|          |
|          |
|          |
|          |
|          |
+----------+

Draw two vertical bars (the opening of the balloon) centered in the middle
of the top row, with n/2 underscores (_) on either side (for this example,
n will be 5):

|  __||__  |
|          |
|          |
|          |
|          |
|          |
|          |
|          |
|          |
|          |
+----------+

Draw one slash (/) and one backslash (\) surrounding this top row, one
row below:

|  __||__  |
| /      \ |
|          |
|          |
|          |
|          |
|          |
|          |
|          |
|          |
+----------+

Draw n rows of identically-spaced vertical bars, and then one row of a
pair of (still identically-spaced) backslash and slash:

|  __||__  |
| /      \ |
| |      | |
| |      | |
| |      | |
| |      | |
| |      | |
| \      / |
|          |
|          |
+----------+

"Fill" the balloon with water, represented by a hash sign (#). Start at
the lowest row, and work upwards. If a row is not entirely filled, you may
place the hash marks wherever you want (in the below example, they are
placed randomly, but you could put them, say, all on the left side if you
want).

|  __||__  |
| / #   #\ |
| |######| |
| |######| |
| |######| |
| |######| |
| |######| |
| \######/ |
|          |
|          |
+----------+

The maximum n is 7, and the minimum is 0.

Input

The input will be an integer i, which is the amount of hash marks (water)
that must be drawn.

It will never be less than 2, or greater than 100.

Output

The output should be a balloon of size n containing i hash marks (units of
water), where n is the lowest possible size that can hold i units of water.
Since i will always be 2 or greater, n will always be 0 or greater.

The maximum possible size a balloon can be drawn at is n = 7. If a size 7
balloon cannot fit the amount of water specified, the balloon pops:

|          |
|          |
|##  #  ###|
|##########|
|##########|
|##########|
|##########|
|##########|
|##########|
|##########|
+----------+

(The above should be the output for input i = 76. Just like the unpopped
balloon, the six extra units of water on the top row may be arranged however
you please.)

Test cases

Why have one test case, when you can have all of them?

Here's an animated GIF of all inputs i from 2 to 100:

Scoring

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


Who's the king of the tournament? Background

Consider a round-robin tournament, in which each contestant plays one game against every other contestant.
There are no draws, so every game has a winner and a loser.
A contestant A is a king of the tournament, if for every other contestant B, either A beat B, or A beat another contestant C who in turn beat B.
It can be shown that every tournament has at least one king (although there may be several).
In this challenge, your task is to find the kings of a given tournament.

Input and output

Your input is an N × N boolean matrix T, and optionally the number N ≥ 2 of contestants.
Each entry T[i][j] represents the outcome of the game between contestants i and j, with value 1 representing a win for i and 0 a win for j.
Note that T[i][j] == 1-T[j][i] if i != j.
The diagonal of T consists of 0s.

Your output shall be the list of kings in the tournament that T represents, using either 0-based or 1-based indexing.
The order of the kings is irrelevant, but there should not be duplicates.

Both input and output can be taken in any reasonable format.

Rules and scoring

You can write a full program or a function.
The lowest byte count wins, and standard loopholes are disallowed.

Test cases

These test cases use 0-based indexing.
For 1-based indexing, increment each output value.

 2 [[0,0],[1,0]] -> [1]
 3 [[0,1,0],[0,0,0],[1,1,0]] -> [2]
 3 [[0,1,0],[0,0,1],[1,0,0]] -> [0,1,2]
 4 [[0,1,1,1],[0,0,1,0],[0,0,0,0],[0,1,1,0]] -> [0]
 4 [[0,1,1,0],[0,0,1,0],[0,0,0,1],[1,1,0,0]] -> [0,2,3]
 5 [[0,1,0,0,1],[0,0,0,0,1],[1,1,0,0,0],[1,1,1,0,1],[0,0,1,0,0]] -> [3]
 5 [[0,1,0,1,0],[0,0,1,1,1],[1,0,0,0,0],[0,0,1,0,1],[1,0,1,0,0]] -> [0,1,4]
 5 [[0,0,0,0,0],[1,0,1,1,0],[1,0,0,0,1],[1,0,1,0,1],[1,1,0,0,0]] -> [1,3,4]
 6 [[0,0,0,0,0,0],[1,0,1,1,0,0],[1,0,0,1,1,0],[1,0,0,0,1,1],[1,1,0,0,0,1],[1,1,1,0,0,0]] -> [1,2,3,4,5]
 6 [[0,0,1,1,1,0],[1,0,0,1,1,1],[0,1,0,0,1,0],[0,0,1,0,0,1],[0,0,0,1,0,1],[1,0,1,0,0,0]] -> [0,1,2,3,5]
 6 [[0,1,1,0,0,1],[0,0,0,1,0,1],[0,1,0,1,1,0],[1,0,0,0,1,1],[1,1,0,0,0,0],[0,0,1,0,1,0]] -> [0,1,2,3,4,5]
 8 [[0,0,1,1,0,1,1,1],[1,0,1,0,1,1,0,0],[0,0,0,1,1,0,0,0],[0,1,0,0,0,1,0,0],[1,0,0,1,0,1,0,0],[0,0,1,0,0,0,1,0],[0,1,1,1,1,0,0,1],[0,1,1,1,1,1,0,0]] -> [0,1,4,6,7]
20 [[0,0,1,1,0,1,1,0,0,0,0,1,1,0,1,1,1,1,0,1],[1,0,1,1,1,0,1,1,1,1,1,0,1,1,1,1,1,1,1,1],[0,0,0,1,0,0,0,1,1,0,1,0,1,0,0,0,0,0,1,1],[0,0,0,0,1,1,1,1,1,1,1,1,0,0,1,0,0,1,1,1],[1,0,1,0,0,0,0,1,1,0,1,1,1,0,1,1,1,1,0,1],[0,1,1,0,1,0,1,1,1,1,1,0,1,1,1,0,1,1,0,1],[0,0,1,0,1,0,0,1,1,0,1,0,1,1,1,1,1,0,1,0],[1,0,0,0,0,0,0,0,1,0,1,1,1,1,0,0,1,1,1,0],[1,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,0,1,1],[1,0,1,0,1,0,1,1,0,0,1,0,0,0,0,1,0,1,1,1],[1,0,0,0,0,0,0,0,0,0,0,1,1,1,0,1,0,0,0,0],[0,1,1,0,0,1,1,0,0,1,0,0,1,1,1,1,1,0,1,1],[0,0,0,1,0,0,0,0,0,1,0,0,0,0,1,1,0,1,1,1],[1,0,1,1,1,0,0,0,0,1,0,0,1,0,1,1,1,1,1,1],[0,0,1,0,0,0,0,1,0,1,1,0,0,0,0,1,1,0,0,1],[0,0,1,1,0,1,0,1,0,0,0,0,0,0,0,0,0,1,1,1],[0,0,1,1,0,0,0,0,0,1,1,0,1,0,0,1,0,0,1,1],[0,0,1,0,0,0,1,0,1,0,1,1,0,0,1,0,1,0,1,1],[1,0,0,0,1,1,0,0,0,0,1,0,0,0,1,0,0,0,0,0],[0,0,0,0,0,0,1,1,0,0,1,0,0,0,0,0,0,0,1,0]] -> [0,1,3,4,5,7,8,11,15,17,18]

Matlab, 36 35 29 bytes
@(T,N)find(sum(T*T>-T,2)>N-2)

Let us find out if i is a king. Then for each j the value T[i][j]==1 OR there is a k such that T[i][k] * T[k][l] == 1. But the second condition can also be replaced by sum_over_k(T[i][k] * T[k][l])>0, but this is just an entry of the matrix T*T (if you consider T as a matrix). The OR can then be replayed by adding T to that result, so we just have to check if n-1 values of the row i of T*T+T are greater than zero, to see whether i is king. This is exactly what my function does.
(This is MATLAB, so the indices are 1-based.)
The MATLAB matrices should be encoded with semicolons as line delimiters:
[[0,0,0,0,0];[1,0,1,1,0];[1,0,0,0,1];[1,0,1,0,1];[1,1,0,0,0]]


Happiness is Mandatory If you're sad, that's wrong. We need to scrub out ALL sadness.

This is a sad face, for reference:

  ......
  .S..S.
 ........
 ...SS...
..SS..SS..
.S......S.
 ........

Where S is a consistent pixel, . is any pixel other than S, and   is any pixel. Note that the sad face is not a perfect square, only the . should be considered. Theoretical sad face overlap in the corners is possible, but overwriting one sad face has a chance to eliminate the other, e.g. if it was in a . character and is overwritten with an S.

Input

An image, in any acceptable format. I would recommend a color matrix.

Output

The same image, but take all those treasonous sad faces and replace their S characters with randomized data. The data should be either random RGB values, or values taken from the palette of the image. You just need to have a nonzero probability of all outputs; you do not need to make it uniform.

Rules

S can be any pixel, as long as it's the same pixel throughout the formation.
Remove ALL sad faces. If the removal makes a new sad face, then remove that too.
You should only modify S pixels. Unauthorized modification of pixels is insubordination, punishable by disqualification.
The shortest answer in bytes wins.

Test Cases

These have one sad face each:

This has 2 sad faces, on the left and right:

This has 2 sad faces overlapping:

This has 2 sad faces, in the top-left and bottom-right; the bottom-left and top-right have S characters in the place of . characters:


Straddling Checkerboard Cipher The Straddling Checkerboard is a method for converting letters to numbers and was part of a pencil an paper cipher known as VIC
To convert letters to numbers first you have to make a checkboard like this:
    0   1   2   3   4   5   6   7   8   9
   ---------------------------------------
    E   T       A   O   N       R   I   S
2 | B   C   D   F   G   H   J   K   L   M
6 | P   Q   #   U   V   W   X   Y   Z   .

Is a 10 x 3 table filled with 28 different simbols and two blanks on the first row.
The labels of second and third row are the position of the blanks on the first one.
To cipher a message you have to replace each letter with the column label.
If it is not on the first row, prepend row label:
G -> 24
O -> 4
L -> 28
F -> 23

The extra simbols # and . are used to escape numbers and to indicate full-stop.
Task
Input:

0 to 26 unsorted unique letters (key)
4 digits, #1 != #2 and #3 != #4
Alphanumeric message to be encoded

Output:

Digits representing the encoded message

Implementation:
The table will be filled with the 26 character recived by input. If lengh is less than 26, the remaining spaces will be filled with the missing letters in alphabetical order.
The first two integers represent the blank spaces on the first row (and labels for second and third row).Next two integers represent the position of # and . on the third row.

Example:
Input: codeglf , 4 6 8 9 , "programming puzzles are gr8."
Yields this table:
   0 1 2 3 4 5 6 7 8 9
   -------------------
   c o d e   g   l f a
4| b h i j k m n p q r
6| s t u v w x y z # .

Output: 47491549945454246547727777637094935496886869

Note1: Spaces are not encoded and not included in the output.
Note2: Original message may contain letters, numbers, spaces and . (assume same capitalisation as the key)
Note3: If there is a number in the original message you have to output the corresponding code number for # followed by the number then another # code (68 in the example) and then continue with the letters.

Example2:
Input: toearly , 2 8 6 1 , "wake up at 06.am"
   0 1 2 3 4 5 6 7 8 9
   -------------------
   t o   e a r l y   b
2| c d f g h i j k m n
8| p . q s u v # w x z

w  a  k e  u  p a t  # 0 6  #  . a  m
87 4 27 3 84 80 4 0 86 0 6 86 81 4 28

Output: 87427384804086068681428

This is the complete VIC cipher question.

PHP>=7.1, 226 Bytes

for([,$c,$a,$b,$d,$e,$t]=$argv,$c.=join(preg_grep("#[^$c]#",range(a,z)));$p<30;)$x[in_array($y=["",$a,$b][$p/10].$p++%10,[$a,$b,$b.$d,$b.$e])?"__#."[$m++]:$c[$i++]]=$y;for(;a&$w=$t[$k++];)echo is_numeric($w)?$x["#"].$w:$x[$w];

Online Version

Expanded

for([,$c,$a,$b,$d,$e,$t]=$argv #short variables in input array
,$c.=join(preg_grep("#[^$c]#",range(a,z))) # join the rest of alphabet
;$p<30;) # loop 30 times
  $x[in_array($y=["",$a,$b][$p/10].$p++%10 # is actual position reserved?
  ,[$a,$b,$b.$d,$b.$e]) # reserved positions
    ?"__#."[$m++] # set reserved positions with chars underscore instead spaces to avoid encoding
    :$c[$i++]] # set alpabetic characters
  =$y; # make encoding array
for(;a&$w=$t[$k++];) # loop through string which shall be encoded
  echo is_numeric($w)
    ?$x["#"].$w # printing for digits
    :$x[$w]; #printing for the other characters


Write a program that finds the most occurring paired letter in a string The program must output the letter that is paired the most. For example, if your program was given the following string:

"Sally's friend Bobby searched for seashells."

it must output L because "ll" occurs twice, which is more frequent than the other pair "bb".

Rules:

If more than one letter has 1st place for occurrences, then output all of them in alphabetical order (e.g. "Sally's friends Jimmy and Bobby rummaged for seashells." should output both L AND M [or "LM" if you please] because they both occur more frequently than other pairs.)
Letters which are tripled, quadrupled, etc. count as one pair (e.g. "lll" in "willless" is counted as only one pair of L.)
Letter pairs must be in one word (e.g. "Sally's sociable friends Sammy and Bobby searched for fabulous seashells." should output L and not S because despite "ss" having more occurrences than "ll", they are separated by spaces.)
Count only letters from the English alphabet
Case does not matter (e.g. "Ss" is the same as "SS" or "ss", and all are counted as one pair of S.)

You may read your input from wherever you please. Shortest code wins.

Bash + GNU coreutils, 133

grep -Eo '([A-Z])\1+'<<<"${1^^}"|cut -c1|sort|uniq -c|sort -rn|while read n l
do((a-n&&a-0))&&exit||echo $l&&a=$n
done|sort|tr -d \\n

Testcases:

$ for t in "Sally's friend Bobby searched for seashells." \
> "Sally's friends Jimmy and Bobby rummaged for seashells." \
> "willless" \
> "Sally's sociable friends Sammy and Bobby searched for fabulous seashells." \
> "11ss11aa"
> do
> ./mostpaired.sh "$t"
> echo
> done
L
LM
LS
L
AS
$


Generate every ASCII string Description

There are an infinite number of ASCII strings. Write a program that will output every possible ASCII string exactly once.

The ordering does not matter, but you must be able to show that for any possible ASCII string s, there exists an integer n such that s is the nth string in the output. This restriction means that you cannot output 'a', 'aa', 'aaa', 'aaaa', ..., since the string 'b' will never occur.

The simplest ordering (shown here in terms of letters so I don't have to type unprintables) is:

'', 'a', 'b', 'c', ..., 'z', 'aa', 'ab', ..., 'az', 'ba', 'bb', 'bc', ... 'zz', 'aaa', ...

Essentially, this is counting in base 128 using ASCII characters.

Rules

The empty string is required
You may use any valid ordering you want
All possible strings using ASCII must be known to occur in the output
The ordering does not need to be deterministic, as long as you can show that every string will be guaranteed to occur. Be careful if you use randomness for each string, because at some point your bits of entropy may not be enough to guarantee a unique string.

Example orderings

Note that, again, I'm showing only letters for the examples, but you have to include all ASCII characters.

Valid:

'', 'a', 'b', 'c', ..., 'z', 'aa', 'ab', ..., 'az', 'ba', 'bb', 'bc', ... 'zz', 'aaa', ...

'', 'z', 'y', 'x', ..., 'a', 'zz', 'zy', ...

'', 'a', 'b', 'ab', 'ba', 'c', 'ac', 'ca', 'bc', 'cb', ...

Invalid:

'', 'a', 'aa', 'aaa', 'aaaa', 'aaaaa', ...

'', 'a', 'ab', 'abc', 'abcd', ..., 'abc...xyza', ...

Python 2, 69 62 bytes

a=0
while 1:
 k=a
 while k:print chr(k%128),;k>>=7
 print;a+=1

-7 bytes thanks to @notjagan

Try it online!


Fourth of July Edition: Print lines of a file containing multiples of a specific number Create a program which takes one command-line argument, n, which will be an integer less than 2147483648 (2^31), and then reads a file input.txt and prints the lines of input.txt which contain any substring which is a positive (non-zero) multiple of n. You may choose to ignore multiples greater than 2147483647.

Test case

If input.txt contains

1. Delaware Dec. 7, 1787
2. Pennsylvania Dec. 12, 1787   1682
3. New Jersey   Dec. 18, 1787   1660
4. Georgia  Jan. 2, 1788    1733
5. Connecticut  Jan. 9, 1788    1634
6. Massachusetts    Feb. 6, 1788    1620
7. Maryland Apr. 28, 1788   1634
8. South Carolina   May 23, 1788    1670
9. New Hampshire    June 21, 1788   1623
10. Virginia    June 25, 1788   1607
11. New York    July 26, 1788   1614
12. North Carolina  Nov. 21, 1789   1660
13. Rhode Island    May 29, 1790    1636
14. Vermont Mar. 4, 1791    1724
15. Kentucky    June 1, 1792    1774
16. Tennessee   June 1, 1796    1769
17. Ohio    Mar. 1, 1803    1788
18. Louisiana   Apr. 30, 1812   1699
19. Indiana Dec. 11, 1816   1733
20. Mississippi Dec. 10, 1817   1699
21. Illinois    Dec. 3, 1818    1720
22. Alabama Dec. 14, 1819   1702
23. Maine   Mar. 15, 1820   1624
24. Missouri    Aug. 10, 1821   1735
25. Arkansas    June 15, 1836   1686
26. Michigan    Jan. 26, 1837   1668
27. Florida Mar. 3, 1845    1565
28. Texas   Dec. 29, 1845   1682
29. Iowa    Dec. 28, 1846   1788
30. Wisconsin   May 29, 1848    1766
31. California  Sept. 9, 1850   1769
32. Minnesota   May 11, 1858    1805
33. Oregon  Feb. 14, 1859   1811
34. Kansas  Jan. 29, 1861   1727
35. West Virginia   June 20, 1863   1727
36. Nevada  Oct. 31, 1864   1849
37. Nebraska    Mar. 1, 1867    1823
38. Colorado    Aug. 1, 1876    1858
39. North Dakota    Nov. 2, 1889    1812
40. South Dakota    Nov. 2, 1889    1859
41. Montana Nov. 8, 1889    1809
42. Washington  Nov. 11, 1889   1811
43. Idaho   July 3, 1890    1842
44. Wyoming July 10, 1890   1834
45. Utah    Jan. 4, 1896    1847
46. Oklahoma    Nov. 16, 1907   1889
47. New Mexico  Jan. 6, 1912    1610
48. Arizona Feb. 14, 1912   1776
49. Alaska  Jan. 3, 1959    1784
50. Hawaii  Aug. 21, 1959   1820

then find_multiples 4 will print the entire file, and find_multiples 40 will print

10. Virginia    June 25, 1788   1607
17. Ohio    Mar. 1, 1803    1788
21. Illinois    Dec. 3, 1818    1720
32. Minnesota   May 11, 1858    1805
40. South Dakota    Nov. 2, 1889    1859
41. Montana Nov. 8, 1889    1809

Perl, 67 chars

open F,"input.txt";print grep/(\d+)(?(?{!$^N+$^N%$ARGV[0]})(*F))/,<F>

Please note that the given character count is taking advantage of one of Perl's more horrific features, namely that a special variable of the form $^X can be written in two characters instead of three, by replacing the ^X with a literal ctrl-X character.

And, of course, this solution wouldn't be possible without a couple of Perl's arguably-equally-terrifying regex extensions that allows one to embed actual code inside of a regex pattern. (But at least those features are clearly documented as being potentially scary.)

[EDITED to fix bug in argument-handling due to not reading the description carefully enough.]


Sigmafy the expression For those who didn't know, Sigma  is a Greek letter which is heavily used in mathematics as the summation sign. Given a string representing an expression depending on \$k\$ that we will denote \$E(k)\$, compute the sum of the results for \$E(k)\$, for each \$k\in\{1,2,3,4,5\}\$. Concisely, you should find \$S\$ such that:

$$S=\sum^5_{k=1}E(k)$$

An example of an expression: \$E(k)=\frac k 2 + k^2\$

Specs

You are guaranteed:

that the expression is valid, so it contains no errors, and that it's dependent of the syntax chosen (e.g: if you only support 2*k, there will be no 2k)
to only have defined values amongst your results, so no values like 1/0, inf or nan will appear

You can assume that the expression above is fitting the limits of the programming language of your choice, so it won't result in overflows or any other limit-related errors
Any other non-whitespace ASCII Character instead of k can be chosen
Your program must support the following operations:

addition (+, plus(),add(),sum())
subtraction (-, minus(), subtract())
exponentiation (**,^,pow() or others, should be specified), with support to negative bases and exponents
square root in the form of sqrt(k), k^0.5, k**0.5, or however else you wish
multiplication and division

The submission can either be a full program or a function, while mentioning its usage
Any trailing / leading whitespace is allowed when outputting
Minimum precision: 2 decimal places

Test Cases (with k)

+---------------+--------------+
|  Input = E(k) |    Output    |
|---------------+--------------|
|2*k            | 30           |
|---------------+--------------|
|sqrt(k)        | 8.38         | (* with minimum decimal precision)
|---------------+--------------|
|k+k/2+k**2     | 77.5         |
|---------------+--------------|
|k**2           | 55           |
+---------------+--------------+

The score will be the number of bytes (of the source + compiler flags). The lowest scoring valid submission wins, while taking note that these loopholes are strictly forbidden. Here is a Python pseudo-code, to make things clearer.

Mathematica, 17 14 13 bytes

Thanks to Ian Miller for saving 3 bytes.

Thanks to LegionMammal978 for saving 1 byte.

#~NSum~{k,5}&

The input should be an actual expression containing k, e.g.:

#~NSum~{k,5}&[Sqrt[k]^3+4]


Google's doodle on kids coding: shortest program solving all the levels Today's Google doodle is about Celebrating 50 years of Kids Coding:
The goal is program the path of a little bunny so that it can eat all the carrots. There are 4 types of blocks (see pictures below):

From left to right:

O("...", k) = orange piece: these are for loops which executes k times the program "...".
G = green piece: go one step forward if you can, otherwise do nothing
Bl = blue piece: turn right and stay on the same block
Br = blue piece: turn left and stay on the same block

The code above can be written as

O(O(G G Br, 4) Bl Bl, 23)

Each block (G, Bl, Br, O(...,k)) counts as 1 unit, so this program is of length 7. Note than the value of k is included inside the 1 unit of O.

There are 6 levels. To finish a level you need to eat all the carrots. It is not a problem if your program is not fully executed, the level finishes directly when you eat the last carrot.

We assume that all the 4 types of blocks are available in every level.

  Your task is to find a single program which solves every level of the game.
   Shortest program in blocks wins.

Screen shots of each level:
Level 1:
Level 2:
Level 3:
Level 4:
Level 5:
Level 6:

Not my answer

6 blocks

The user Alex found a shorter solution, of length 6. I can confirm that their solution works:

O(O(Br G G, 6) Br, 5)

They attempted to edit this question to add this answer, so I'm assuming they want it to be displayed here. I don't like how the reputation system works around here.

The message they left:

  The editor doesn't have 10 rep, but does have a solution of length 6. O(O(RGG,6)R,5)

After a few days they responded again via editing the post with: "Thanks for doing this. Editing this was the only way I saw to get a message. I am happy it exists at all. Feel free to bring it into a new post if you want though."

Old answer

7 Blocks

O(O(G G Br, 4) G Br, 100)

Patience required.

Edit: The image was wrong.


Generate information cards with titles You must take input in the form of

title|line1|line2|(...)|line[n]

And output an information card. It's hard to explain how to make the card, so here's a quick example:

Input

1234567890|12345|1234567890123|pie|potato|unicorn

Output

/===============\
|  1234567890   |
|===============|
| 12345         |
| 1234567890123 |
| pie           |
| potato        |
| unicorn       |
\---------------/

Detailed specifications:

The title must be centered (if there are an odd number of characters you can decide whether to put an extra space after or before it).
The remaining lines must be left-aligned.
All of them must have at least one space of padding before and after.
Each line must be the same length.
The lines must be the smallest length possible in order to fit all of the text.
The first and last character of each row (except for the first and last rows) must be a |.
There must be a /, a row of =s, and a \ in the line right before the title. (the first line)
There must be a |, a row of =s. and a | in the line right after the title. (the third line)
There must be a \, a row of -s, and a / in the last line.
For the example input provided, your program's output must exactly match the example output provided.
The input will always contain at least one |; your programs behaivior when a string like badstring is input does not matter.

This is code-golf so the shortest code in character count wins.

Ruby, 153 147 140 characters

h,*d=s=gets.chop.split(?|)
puts"/%s\\
|%s|
|%s|"%[e=?=*k=2+l=s.map(&:size).max,h.center(k),e]
d.map{|x|puts"| %%-%ds |"%l%x}
$><<?\\+?-*k+?/

Double format string in the second-to-last line :D


Find five friends to eat chicken with Paul Paul is one of your Belgian acquaintances, and he would like you to create a program that outputs at least one of the following five strings:

12496=>14288=>15472=>14536=>14264

14264=>12496=>14288=>15472=>14536

14536=>14264=>12496=>14288=>15472

15472=>14536=>14264=>12496=>14288

14288=>15472=>14536=>14264=>12496

It represents the friends he's most proud of, and he would like to eat with them. Paul also thinks that the number 6 is perfect, and that is the only number worth using. So you cannot use any other digit than "6" in your code (0 to 5 and 7 to 9 are forbidden). Your program cannot take any inputs. The output can contain garbage before and/or after the string but should contain at least one of the above strings.

For example this is a valid output :

220frefze
f**14288=>15472=>14536=>14264=>12496**fczfe fz**15472=>14536=>14264=>12496=>14288**zfe
fzehth

I "ligthly" hinted in the question as how I expect this to be resolved, but how knows ? Maybe there is a better way... Hope you have fun.

This is code-golf : lowest score in bytes wins.

05AB1E, 18 17 bytes

•w[•Y·FDÑ¨O})„=>ý

Try it online!

Explanation

•w[•                # base 214 encoding of 12496
    Y·F             # loop 2*2 times
       D            # duplicate top of stack
        Ñ           # push divisors
         ¨          # remove the last element (itself)
          O         # sum
           }        # end loop
            )       # wrap in list
             „=>ý   # join list on "=>"

In short, we calculate each number as f(n+1) = sum(divisors(f(n)) - f(n)


Tips for golfing in Haxe What general tips do you have for golfing in Haxe? I'm looking for ideas which can be applied to code-golf problems and which are also at least somewhat specific to Haxe (e.g. "remove comments" is not an answer).

Please post one tip per answer.

Haxe can be run online here!

String interpolation

Haxe supports string interpolation on single-quote strings. Like template strings in JavaScript ES6, you can include an expression in a string with ${...}:

trace('2 + 2 = ${2 + 2}');

Unlike ES6, however, you can omit the curly brackets when the expression is a single variable:

var x = 2 + 2;
trace('2 + 2 = $x');

Both of these examples print 2 + 2 = 4.


Generate a valid sequence of numbers with specific rules The challenge

The program must return a valid sequence of numbers into some rules

Rules

x is the size of the sequence;
x cannot be less than 4 or greater than 9 (Thanks David Carraher);
Digits of the sentence can't repeat, each one must appear once;
All digits between 1 to x must be in the sequence;
A valid sequence never begins nor ends with 1 or x;
Into the sequence, numbers can never appear "together";

Examples

If x=4:
2413 valid
3142 valid

1423 not valid, because begins with 1 and 23 are "together".
2134 not valid, because ends with x and 34 are "together".

Still don't get it?
Other example:

If x=8:
28375146 valid, because don't start with 1 nor x(8), don't end with 1 nor x, and no numbers are "together"(no numbers touches, no numbers are the next or previous)

Sorry, I really don't know how to explain the last rule. Hope the example make it understandable.

Additional Information

x does not need to be an input, you can show the outputs for x=4 and x=9 working;
Since any language will be accepted and, I don't know how all of them work, I will ask you people to help me with this;
The winner will be the one who got more up-votes in 1 week, so please, vote the answer you find the best; I will mark it as the Correct one;

Good, luck. =)

GolfScript (17 16 chars)

Assuming input on stdin and output on stdout.

~:^),(;{-2\^%?}$

Almost alphanumeric-free...


Create an "H" from smaller "H"s Challenge
Create a function or program that, when given an integer size, does the following:
If size is equal to 1, output
H H
HHH
H H

If size is greater than 1, output
X X
XXX
X X

where X is the output of the program/function for size - 1
(If you prefer, you may have the base case correspond to 0, so long as you specify in your answer)
Any of the following output formats are acceptable, whichever is more convenient for you:

A string of the required structure with any two distinct characters corresponding to H and space

A two-dimensional array with the required structure, with any two distinct values corresponding to H and space

An array/list of strings, with one line of the output in each string, with any two distinct values corresponding to H and space

Leading spaces are allowed, as long as there is a constant amount of leading spaces on each line. The two distinct output characters can be dependent on anything you choose, as long as they are different.
Specify what output format your code is returning.
Test Cases
1
H H
HHH
H H

2
H H   H H
HHH   HHH
H H   H H
H HH HH H
HHHHHHHHH
H HH HH H
H H   H H
HHH   HHH
H H   H H

3
H H   H H         H H   H H
HHH   HHH         HHH   HHH
H H   H H         H H   H H
H HH HH H         H HH HH H
HHHHHHHHH         HHHHHHHHH
H HH HH H         H HH HH H
H H   H H         H H   H H
HHH   HHH         HHH   HHH
H H   H H         H H   H H
H H   H HH H   H HH H   H H
HHH   HHHHHH   HHHHHH   HHH
H H   H HH H   H HH H   H H
H HH HH HH HH HH HH HH HH H
HHHHHHHHHHHHHHHHHHHHHHHHHHH
H HH HH HH HH HH HH HH HH H
H H   H HH H   H HH H   H H
HHH   HHHHHH   HHHHHH   HHH
H H   H HH H   H HH H   H H
H H   H H         H H   H H
HHH   HHH         HHH   HHH
H H   H H         H H   H H
H HH HH H         H HH HH H
HHHHHHHHH         HHHHHHHHH
H HH HH H         H HH HH H
H H   H H         H H   H H
HHH   HHH         HHH   HHH
H H   H H         H H   H H

This is code-golf, so the lowest byte count for each language wins!

Wolfram Language (Mathematica), 46 bytes

Nest[ArrayFlatten@{r={#,0,#},{#,#,#},r}&,1,#]&

Returns a 2d array of 0s and 1s.

Try it online!


My Word can beat up your Word PROBLEM

Given two words, find the winner in a digital root battle.

Define the digital root of a word this way:

Each letter of the alphabet is assigned a number:  A = 1, B = 2, C = 3, ..., Z = 26
Add the values for each letter to total the word. Take "CAT", for example. C+A+T = 3+1+20 = 24
Add all the single digits that make up that result: 24 => 2 + 4 = 6
Repeat step #3 until you reach a single digit. That single digit is the digital root of the word.

Rules:

A winner is declared if its digital root is larger than the other.
If the digital root values are equal, shorten the words by removing every instance of the highest value letter from both words and recalculating.
Repeat steps #1 and #2 until there is a winner or one of the words has only a single letter (or no letters) remaining.
If the digital root values are equal after going through the shortening process, the longer word is declared the winner.
If the words are of equal length and no winner is found after going through the shortening process, no winner is declared.

Special rules:

No use of modulus is allowed in the calculation of the digital root itself. It can be used anywhere else.
Assume words will consist only of uppercase letters - no punctuation, no spaces, etc.

INPUT

Pull the words in through stdin (comma-separated). method parameters, or however you want. Make it clear in your solution or the code how the words are parsed or prepared.

OUTPUT

Display the winning word. If there is no winner, display "STALEMATE".

Examples:

intput: CAN,BAT

CAN = 18 = 9
BAT = 23 = 5

output: CAN

intput: ZOO,NO

ZOO = 56 = 11 = 2
NO = 29 = 11 = 2

OO = 30 = 3
N = 14 = 5

output: NO

UPDATE: Input must be read using stdin with the words as a comma-separated string.

UPDATE: Added a couple examples to test against.

UPDATE: clarified the removal of the highest valued letter in the case of a tie - this also alters slightly the stop condition as well - if a word is one letter or zero letters long, the shortening process is stopped

J, 100

z=:"."0@":@(+/)^:9@(64-~a.i.])@(#~' '&i.)"1
f=:*@-/"2@(z@((]#~]i.~{.@\:~)"1^:([:=/z))){'STALEMATE'&,

runs like this:

f 'NO',:'ZOO'
NO
f 'CAN',:'BAT'
CAN
f 'FAT',:'BANANA'
FAT
f 'ONE',:'ONE'
STALEMATE

it doesn't yet accept input exactly as asked.