Make An ASCII Poker Chip Stack Arrangement Poker has etiquette in how you arrange your chips, often enforced in tournaments - your chips may not be "hidden" from your opponents by being behind others, mostly to not hide some large denomination chip(s).

The Challenge

We are going to be playing poker in ASCII, so we need to write a function or program that will draw our ASCII chip stack arrangement given its total value, n.

Input
- A positive integer, n (up to 2**32-1 should be handled)

Output
- An ASCII representation of the stack arrangement as defined below.
This may contain white-space to the right of each line such that no line is longer than one more character than the length used by printable characters in the longest (bottom) line;
This may contain a single trailing new line; and
The characters representing chips may be in lowercase if you prefer.

The stack arrangement will:

Contain the fewest chips possible, given the denominations (see below);
Will have equal valued chips in "stacks" (columns);
Be ordered such that the shorter stacks are to the right of taller stacks; and
Be ordered such that stacks with greater denomination chips will be to the right of equal sized stacks of lower denominations (representing that they are visible to our opponent(s) on the right)

The chips themselves are to be represented as individual characters identifying their colour:

    White : 1    = W
      Red : 5    = R
    Green : 25   = G
    Black : 100  = B
   Yellow : 500  = Y
     Pink : 1K   = P
   Orange : 5K   = O
     Cyan : 25K  = C
  Magenta : 100K = M
Aqua-blue : 500K = A
 Lavender : 1M   = L
   Indigo : 5M   = I
Turquoise : 25M  = T
   Violet : 100M = V
   Silver : 500M = S

Example

For n = 276,352 the smallest number of chips would be:

2 * 100K + 3 * 25K + 1 * 1K + 3 * 100 + 2 * 25 + 2 * 1
    MM         CCC       P        BBB       GG       WW

The single P must go on the far right,
then the three stacks of size 2 must go next,
- but the MM must go furthest to the right followed by the GG and then the WW since 100K > 25 > 1
then the two stacks of size 3 go on the left,
- but the CCC must go to the right of the BBB since 25K > 100

Now we must place these chips into actual stacks, to make our output:

BC
BCWGM
BCWGMP

Test Cases

Input:
1

Output:
W

Input:
9378278

Output:
L
LWGPCM
LWGPCMB
LWGPCMBI

Input:
22222222

Output:
ROI
ROI
ROIWBPML
ROIWBPML

Input:
1342185143

Output:
WRCIV
WRCIVOLS
WRCIVOLSGBMT

Input:
2147483647

Output:
RMIS
RMISPC
RMISPCWL
RMISPCWLGBYOTV

Input:
4294967295

Output:
S
S
S
S
SRML
SRMLGOIT
SRMLGOITBPCV
SRMLGOITBPCVA

This is code-golf, so shortest code in bytes wins. No loopholes, yada yada, you know the drill.

JavaScript (ES6), 185 177 ... 171 bytes

f=(a,s='')=>(a=(a[0]?a:[...(m='25455')+m+m].map((m,i)=>(a-=(k=a/(v/=m)|0)*v,k*16+i),v=1E9).sort((a,b)=>b-a)).map(n=>n>15&&(s+='SVTILAMCOPYBGRW'[n&15],n-16)),s&&f(a)+`
`+s)

Formatted and commented

(a, s = '') => (                           // a = bankroll OR array of chip stacks
  a = (                                    // s = string of chip initials for this iteration
    a[0] ?                                 // if 'a' already is an array:
      a                                    // use it as-is
    :                                      // else, 'a' is the bankroll:
      [...(m = '25455') + m + m]           // for each 'm' in [ 2, 5, 4, 5, 5, ... ] (x3)
      .map((m, i) =>                       // v = current chip value = previous value / m
        (                                  // k = floor(a / v) = number of these chips
          a -= (k = a / (v /= m) | 0) * v, // update remaining bankroll: a = a - k * v
          k * 16 + i                       // saved in array: chip index in bits 0-3
        ),                                 // and number of chips in bits 4+
        v = 1E9                            // initial chip value = 1 billion
      )                                    // (1B / 2 -> 500M, 500M / 5 -> 100M, etc.)
      .sort((a, b) => b - a)               // sort the chip stacks
  )                                        //
  .map(n =>                                // for each chip stack:
    n > 15 &&                              // if there's at least one remaining chip of
    (                                      // this kind:
      s += 'SVTILAMCOPYBGRW'[n & 15],      // append its initial to the string
      n - 16                               // decrement the number of chips in this stack
    )                                      //
  ),                                       // process recursive call if there was at least
  s && f(a) + '\n' + s                     // one non-empty chip stack (the next lines are
)                                          // appended at the beginning of the final string)

Demo

let f=(a,s='')=>(a=(a[0]?a:[...(m='25455')+m+m].map((m,i)=>(a-=(k=a/(v/=m)|0)*v,k*16+i),v=1E9).sort((a,b)=>b-a)).map(n=>n>15&&(s+='SVTILAMCOPYBGRW'[n&15],n-16)),s&&f(a)+`
`+s)

function update() {
  document.getElementById('o').innerHTML = f(+document.getElementById('i').value);
}
update();
<input id="i" value="1342185143" oninput="update()">


Robots! Collect these pickles! I seem to have gotten myself into a bit of a pickle. Literally. I dropped a bunch of pickles on the floor and now they're all scattered about! I need you to help me collect them all. Oh, did I mention I have a bunch of robots at my command? (They're also all scattered all over the place; I'm really bad at organizing things.)

You must take input in the form of:

P.......
..1..2..
.......P
........
P3PP...4
.......P

i.e., multiple lines of either ., P (pickle), or a digit (robot's ID). (You may assume that each line is of equal length, padded with ..) You can input these lines as an array, or slurp from STDIN, or read in a comma-separated single line, or read a file, or do whatever you would like to take the input.

Your output must be in the form of n lines, where n is the highest robot ID. (Robot IDs will always be sequantial starting at 1.) Each line will contain the robot's path, formed from the letters L (left), R (right), U (up), and D (down). For example, here's an example output for that puzzle:

LLU
RDR
LRRR
D

It can also be

LLU RDR LRRR D

Or

["LLU","RDR","LRRR","D"]

Or any format you would like, as long as you can tell what the solution is supposed to be.

Your goal is to find the optimal output, which is the one that has the least steps. The amount of steps is counted as the greatest amount of steps from all of the robots. For example, the above example had 4 steps. Note that there may be multiple solutions, but you only need to output one.

Scoring:

Your program will be run with each of the 5 (randomly generated) test cases.
You must add the steps from each run, and that will be your score.
The lowest total, cumulative score will win.
You may not hard-code for these specific inputs. Your code should also work for any other input.
Robots can pass through each other.
Your program must be deterministic, i.e. same output for every run. You can use a random number generator, as long as it's seeded and consistently produces the same numbers cross-platform.
Your code must run within 3 minutes for each of the inputs. (Preferrably much less.)
In case of a tie, most upvotes will win.

Here are the test cases. They were randomly generated with a small Ruby script I wrote up.

P.......1.
..........
P.....P...
..P.......
....P2....
...P.P....
.PP..P....
....P....P
PPPP....3.
.P..P.P..P

....P.....
P....1....
.P.....PP.
.PP....PP.
.2.P.P....
..P....P..
.P........
.....P.P..
P.....P...
.3.P.P....

..P..P..P.
..1....P.P
..........
.......2P.
...P....P3
.P...PP..P
.......P.P
..P..P..PP
..P.4P..P.
.......P..

..P...P...
.....P....
PPPP...P..
..P.......
...P......
.......P.1
.P..P....P
P2PP......
.P..P.....
..........

......PP.P
.P1..P.P..
......PP..
P..P....2.
.P.P3.....
....4..P..
.......PP.
..P5......
P.....P...
....PPP..P

Good luck, and don't let the pickles sit there for too long, or they'll spoil!

Oh, and why pickles, you ask?

Why not?

Ruby, 15+26+17+26+17 = 101

Robot Finds Pickles!

Okay, here's a baseline to get people started, using the following super-naive algorithm:

Each tick, each robot will act in numeric order, performing the following steps:

Identify the closest (Manhattan distance) pickle that no other robots are targeting.
Figure out which adjacent squares are available to move to.
Choose one of those squares, preferring directions that move it closer to the selected pickle.

Here's what it looks like for Test Case #1:

Obviously this isn't very good but it's a start!

Code:

Tile = Struct.new(:world, :tile, :x, :y) do
    def passable?
        tile =~ /\.|P/
    end

    def manhattan_to other
        (self.x - other.x).abs + (self.y - other.y).abs
    end

    def directions_to other
        directions = []
        directions << ?U if self.y > other.y
        directions << ?D if self.y < other.y
        directions << ?L if self.x > other.x
        directions << ?R if self.x < other.x
        directions
    end

    def one_step direction
        nx,ny = case direction
            when ?U then [self.x, self.y - 1]
            when ?D then [self.x, self.y + 1]
            when ?L then [self.x - 1, self.y]
            when ?R then [self.x + 1, self.y]
        end

        self.world[nx,ny]
    end

    def move direction
        destination = one_step(direction)
        raise "can't move there" unless destination && destination.passable?

        destination.tile, self.tile = self.tile, ?.
    end
end

class World
    DIRECTIONS = %w(U D L R)

    def initialize s
        @board = s.split.map.with_index { |l,y| l.chars.map.with_index { |c,x| Tile.new(self, c, x, y) }}
        @width = @board[0].length
    end

    def [] x,y
        y >= 0 && x >= 0 && y < @board.size && x < @board[y].size && @board[y][x]
    end

    def robots
        tiles_of_type(/[0-9]/).sort_by { |t| t.tile }
    end

    def pickles
        tiles_of_type ?P
    end

    def tiles_of_type type
        @board.flatten.select { |t| type === t.tile }
    end

    def inspect
        @board.map { |l| l.map { |t| t.tile }*'' }*?\n
    end
end

gets(nil).split("\n\n").each do |input|
    w = World.new(input)
    steps = Hash[w.robots.map { |r| [r.tile, []] }]
    while (pickles_remaining = w.pickles).size > 0
        current_targets = Hash.new(0)

        w.robots.each do |r|
            target_pickle = pickles_remaining.min_by { |p| [current_targets[p], r.manhattan_to(p)] }

            possible_moves = World::DIRECTIONS.select { |d| t = r.one_step(d); t && t.passable? }
            raise "can't move anywhere" if possible_moves.empty?

            direction = (r.directions_to(target_pickle) & possible_moves).first || possible_moves[0]

            current_targets[target_pickle] += 1
            steps[r.tile] << direction
            r.move(direction)
        end
    end

    puts steps.values.map &:join
    p steps.values.map { |v| v.size }.max
end

Takes input on STDIN in exactly the format of the test case code-block in the original question.  Here's what it prints for those test cases:

DDLLDLLLLULLUUD
LDLRRDDLDLLLLDR
URDDLLLLLULLUUL
15
ULDLDDLDRRRURRURDDDDDDDLLL
UUULDDRDRRRURRURDLDDDDLDLL
ULUURURRDDRRRRUUUDDDDLDLLL
26
URRRDRUDDDDLLLDLL
RUUUDLRRDDDLLLDLL
LDRDDLDDLLLLLLLUU
RUUURDRDDLLLLLUUU
17
DULLUUUUULDLDLLLLLDDRUUUUR
UDLRRRURDDLLLUUUUURDRUUUUD
26
LDDLDUUDDDUDDDDDR
ULUULDDDDDRDRDDDR
LULLDUUDDDRDRDDDR
UUUURDUURRRRDDDDD
LDLLUDDRRRRRRUDRR
17


Output diagonal positions of me squared Given a number n, Output an ordered list of 1-based indices falling on either of the diagonals of an n*n square matrix.

Example:

For an input of 3:

The square shall be:

1 2 3
4 5 6
7 8 9

Now we select all the indices represented by \, / or X (# or non-diagonal positions are rejected)

\ # /
# X #
/ # \

The output shall be:

[1,3,5,7,9]

Test cases:

1=>[1]
2=>[1,2,3,4]
3=>[1,3,5,7,9]
4=>[1,4,6,7,10,11,13,16]
5=>[1,5,7,9,13,17,19,21,25]

There will be no accepted answer. I want to know the shortest code for each language.

Octave, 28 bytes

@(n)find((I=eye(n))+flip(I))

Anonymous function that inputs a number and outputs a column vector of numbers.

Try it online!


Rotate an ASCII art image Out of all of the ASCII characters, it is easy to tell that some of them form groups that are rotations of the same basic character. For example, V > ^ <. This allows the possibility to construct ASCII art that can be rotated by multiples of 90 degrees and still remain ASCII art.

The Challenge

Your goal is to golf a program that accepts ASCII art and the number of degrees to rotate it from STDIN, and prints the rotated ASCII art to STDOUT.

On the first line of input, your program will receive a number N. This number represents the width and height of the ASCII art.

You will then receive N more lines of exactly N characters each (the newline is not counted in this number). The size of the art will always be a square, although it may have padding in the form of spaces to make it a square.

You will then receive one more number on a final line: 90, 180, or 270. This represents how many degrees clockwise the picture should be rotated.

Note: The inputted image will only contain characters that can be rotated by the correct amount. If the input does not match these requirements exactly, no specific behavior is required.

As output, your program should print exactly N lines of N characters, with newlines after each line. The image should be rotated so that each character in the original has been replaced by a rotated version and has been moved to the correct place in the image.

Examples (not very beautiful ASCII art)

Input

5
<- ||
|  |V
+->+
   |O
<--+
90

Output

^ +-^
| | |
| V
+-+--
 O <-

(Rotations by 90 and 270 won't look very good because the characters are not squares)

Input

6
+ /\ +
| \ \|
(  \/|
 \   )
I \ /
:) V $
180

Output

$ ^ (:
 / \ I
(   \
|/\  )
|\ \ |
+ \/ +

Required Supported Characters

For all rotations (90, 180, and 270), the program should be able to rotate:

Spaces, +, @, X and O which never change
V  > < ^
| - and \ / (rotated by 180 they stay the same)

For 180 degree rotation, these additional characters must be supported

I N Z % : 0 = S ~ $ # which stay the same
P d, ( ), [ ], { }, M W, and 9 6


Dictionary Code Golf New to code golf and enjoying it. I have a problem that I cannot figure out and am curious if others can solve it.

Start with two dictionaries, y and z:

y = {'a': 1, 'c': 3, 'e': 5, 'g': 7}
z = {'b': 2, 'd': 4, 'f': 6, 'h': 8}

y and z both map length-1 strings to numbers, where each number is between 1 and 26 (inclusive) and represents an English letter: a = 1, b = 2, c = 3, d = 4 , ... , z = 26.

The goal is as follows:

Double each number (i.e. value) in y, and replace the key with the letter corresponding to the new number.
Do the same for z, but triple each number instead.
Populate a dictionary x with the keys and values from both y and z in descending numerical order, for instance:

x = {'x': 24, 'n':18, 'm': 14, 'l':12, 'j': 10, 'f': 6, 'b':2}

Good luck!

Example:

Starting state:

y = {'a': 1, 'c': 3, 'e': 5, 'g': 7}
z = {'b': 2, 'd': 4, 'f': 6, 'h': 8}

After y operations:

y = {'b':2, 'f': 6, 'j': 10, 'm': 14}

After z operations:

z = {'f': 6, 'l': 12, 'n': 18, 'x': 24}

Python, 174 155 113 86 70 68 66 bytes

It's actually my first time here and here's my attempt. Let me know if I am doing anything wrong.

lambda y,z:{chr(v*(3-v%2)+96):v*(3-v%2)for v in{**y,**z}.values()}

EDIT: After OP's edit and @Rod 's comment I noticed I have some mistakes. I also took out the sorting attempts because it simply can't work with Python dictionaries.

EDIT2: -16bytes thanks to @JonathanAllan

Try it online!


Collatz sequence on a two counter machine The Collatz sequence starting from a positive integer n is defined in this way:

if n is even then divide it by 2 (n' = n / 2)
if n is odd then multiply it by 3 and add 1 (n' = 3n + 1)

Repeat the above iteration until n reaches 1.
It is not known (it's a major unsolved problem in number-theory) if the sequence will eventually reach the number 1, regardless of which positive integer is chosen initially.
A Two Counter Machine (2CM) is a machine equipped with two registers that can hold a non-negative integer value and can be programmed with the following instruction set:
INCX    increase the value of register X
INCY    increase the value of register Y
JMP n   jump to instruction n
DJZX n  if register X is zero jump to instruction n,
        otherwise decrement its value
DJZY n  if register Y is zero jump to instruction n,
        otherwise decrement its value
HALT    halt (and accept)
PRINTX  print the content of register X

A 2CM program is simply a sequence of instructions, for example the following program simply copies the content of register X to register Y:
cp:   DJZX end
      INCY
      JMP cp
end:  HALT

Note that a 2CM is Turing Complete (i.e. it can compute every computable function with a suitable input encoding, but it is irrelevant here). Also note that the instruction set is a little bit different from the one in the Wikipedia article.
The challenge
Write the shortest 2CM program, that computes and prints the collatz sequence up to 1 and halts (the register X initially contains the starting value n and register Y initially contains 0). Note that the length of a 2CM program is the number of instructions used (not the length of the text).
For example, when started from X=3 it must print: 3 10 5 16 8 4 2 1 and HALT.
So you can use your favourite language to build a 2CM simulator/interpreter, but the final (shortest) code that you put in the answer must be in the 2CM language.

18 instructions

I was a bit disappointed that I arrived late on scene, as the minimalistic nature of the problem and the language make there (seemingly) only one general approach for a good answer. I got a 19-instruction answer fairly quickly, but I didn't feel like it brought enough to the table to post it. But after much head scratching, my hacky z80 assembly experience came through and I found a way to save an instruction by reusing a block of code for a purpose it wasn't meant for!

# Let N be the previous number in the Collatz sequence.

# Print N, and if N==1, halt.
# X=N, Y=0
Main:           PRINTX          # Print N.
                DJZX Done       # X=N-1 (N shouldn't be zero, so this never jumps)
                DJZX Done       # If N-1==0, halt. Otherwise, X=N-2.

# Find the parity of N and jump to the proper code to generate the next N.
# X=N-2, Y=0
FindParity:     INCY
                DJZX EvenNext   # If N%2==0, go to EvenNext with X=0, Y=N-1.
                INCY
                DJZX OddNext    # If N%2==1, go to OddNext with X=0, Y=N-1.
                JMP FindParity

# Find the next N, given that the previous N is even.
# X=0, Y=N-1
EvenNext:       INCX
                DJZY Main       # Y=Y-1 (Y should be odd, so this never jumps)
                DJZY Main       # If Y==0, go to Main with X=(Y+1)/2=N/2, Y=0.
                JMP EvenNext

# Find the next N, given that the previous N is odd.
# X=0, Y=N-1
OddNext:        INCX
                INCX
                INCX
                DJZY EvenNext   # If Y==0, go to EvenNext with X=(Y+1)*3=N*3, Y=0.
                JMP OddNext     # ^ Abuses EvenNext to do the final INCX so X=N*3+1.

# Halt.
Done:           HALT


Optimum Letter Cards for Spelling Words Let's say you have a list of words and you want to be able to use letter cards to spell each word. For example, to spell cat, you would use three cards labelled C, A, T.

Assuming each card is double-sided, submit a program to define a minimum number of cards that can be used to spell the entire list of words.

Input is the word list, it can be file-based, hard-coded, command line, whatever. Output is the list of cards, formatted and ordered as you see fit, provided it is clear how the cards are labelled.

Case is not significant: Golf, golf and GOLF are equivalent.

Some hints:

the number of cards can be no less than the length of the longest word
it makes no sense for a card to have the same letter on both sides
while case is not significant, recommend lower case to take advantage of certain symmetries

Examples, these take advantage of certain symmetries:

Input: ben, bog, bug, den, do, doe, dog, due, dug, Ed, end, gob, God, Ned, ode, pen, Poe, pug

Output: b/d, e/g, o/n

Input: an, and, ape, are, be, bed, bud, bur, Dan, Deb, dub, ear, Ed, era, nap, pan, pea, pub, Rae, ran, rub

Output: a/b, d/r, e/n

Making it a popularity contest, so elegance of code, run-time performance, and cleverness (including rule-bending & loopholes) are important!

Addition: Some have asked about "allowed" symmetries, whether special fonts can be used, and whether the cards can be folded.

Allowed symmetries are any letters which look similar to each other after 0, 90, 180 or 270 degrees rotation. This includes b/q, d/p and n/u. I would also say M/W, Z/N, and of course I/l (capital i, lowercase L). I'm probably scratching the surface, so if there are any others you're unsure about, just ask.

To keep it simple, please restrict to a standard sans-serif font, say that used in SE.

As far as folding, while you can do some amazing substitutions, e.g. B can be D, E, F, I, P, or R, and maybe C or L if you fold really creatively, I think that's bending, literally, too much!

I came up with this problem while playing with some similar cards with my kids. I noted how easy it was to come up with single-sided cards vs. how difficult it was to come up with double-sided cards.

Addition: Have provided a bounty to be awarded to the most popular answer. If there's a tie, will award to the one who submitted first.

Another hint:

solving the single-sided problem will give you an idea of the minimum number of cards needed (e.g. 20 single-sided cards translates to at least 10 double sided-cards needed)

Addition: Oh bother, I was busy and forgot about the bounty expiring. It ended up going to no one because the only answer was submitted before the bounty started! Sorry about that.

C# - CardChooser

Summary

This application uses a brute force method to attempt to solve each list. First I create a list of potential cards to select from, then I determine which is a best fit(removes the most chars + shortens long words most), add this to a result list and continue with this process until I have selected enough potential cards to remove every word in the list, then I  rematch those cards to each word and print the output.

If you would like to see a more limited version of this code without downloading and building the provided windows forms application you can use the link provided to run my program on smaller sets of data, please note that this is the console application version so the resulting cards are NOT rotated:
http://ideone.com/fork/VD1gJF

Revision History

Current - Added better result optimization suggested by @Zgarb

Update 3 - More code cleanup, more bugs fixed, better results

Update 2 - Windows Forms, More verbose output

Update 1 - New/Better support for character symmetries

Original - Console Application

Examples

acr, aft, ain, sll, win, say, said, fast, epic

hes, will, with, wont, would, wouldve, wouldnt, yet, you, youd, youll

aaaa, bbbb, cccc

Code

I still need to combine this into one larger project with the ConsoleApp and WindowsForms code all sharing the same classes and methods, then split out the different regions in the RunButton_Click method so I can write units around them, anyway whenever I find time to do that I will, for now this is what I have:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace CardChooserForms
{
    public partial class CardChooser : Form
    {
        private class Solution : IEquatable<Solution>
        {
            public List<string> Cards { get; set; }
            public List<string> Remaining { get; set; }

            public int RemainingScore
            {
                get
                {
                    return this.Remaining.Sum(b => b.ToCharArray().Count());
                }
            }

            public bool Equals(Solution other)
            {
                return new string(Cards.OrderBy(a => a).SelectMany(a => a).ToArray()) == new string(other.Cards.OrderBy(a => a).SelectMany(a => a).ToArray());
            }

            public override int GetHashCode()
            {
                return (new string(Cards.OrderBy(a => a).SelectMany(a => a).ToArray())).GetHashCode();
            }
        }
        private class Symmetry
        {
            public char Value { get; set; }
            public Int16 RotationDifference { get; set; }
        }

        /// <summary>
        /// This is where Symmetries are stored, right now it only has support for pairs(two values per array)
        /// </summary>
        private static Symmetry[][] _rotatableCharacters = new Symmetry[][] {
                new Symmetry[] { new Symmetry {Value = 'Z'}, new Symmetry {Value = 'N', RotationDifference = 90}},
                new Symmetry[] { new Symmetry {Value = 'd'}, new Symmetry {Value = 'p', RotationDifference = 180 }},
                new Symmetry[] { new Symmetry {Value = 'u'}, new Symmetry {Value = 'n', RotationDifference = 180 }},
                new Symmetry[] { new Symmetry {Value = 'm'}, new Symmetry {Value = 'w', RotationDifference = 180 }},
                new Symmetry[] { new Symmetry {Value = 'b'}, new Symmetry {Value = 'q', RotationDifference = 180 }},
                new Symmetry[] { new Symmetry {Value = 'l'}, new Symmetry {Value = 'I', RotationDifference = 0}},
            };

        //These all control the output settings
        private readonly static int _defualtSpacing = 25;
        private readonly static int _defualtFontSize = 8;
        private readonly static Font _defualtFont = new Font("Microsoft Sans Serif", _defualtFontSize);
        private readonly static Brush _defualtBackgroundColor = Brushes.Beige;
        private readonly static Brush _defualtForegroundColor = Brushes.Black;

        public CardChooser()
        {
            InitializeComponent();
        }

        private void RunButton_Click(object sender, EventArgs e)
        {
            #region Input Parsing
            //Get input
            string input = InputRichTextBox.Text;

            if (!input.Contains(","))
                throw new ArgumentException("Input must contain more than one value and must be seprated by commas.");

            //Parse input
            var inputLowercasedTrimedTransformed = input.Split(',').Select(a => a.ToLowerInvariant().Trim()).ToArray();
            var inputSplitTrimIndex = input.Split(',').Select(a => a.Trim()).ToArray().Select((a, index) => new { value = a, index }).ToArray();
            #endregion Input Parsing

            #region Card Formation
            var inputCharParsed = inputLowercasedTrimedTransformed.Select(a => a.ToCharArray()).ToArray();
            var possibleCards = GetAllCasesTwoLengthArrayElements(
                UniqueBiDirection(
                //Get unique characters
                    inputCharParsed
                    .SelectMany(a => a)
                    .Distinct()
                    .Select(a => new
                    {
                        Character = a,
                        PossibleCharacters = inputCharParsed.SelectMany(b => b).Where(b => b != a).ToList()
                    })
                //Now get distinct cards(ie NB == BN, NB != NE)
                    .SelectMany(a => a.PossibleCharacters.Select(b => new string(new char[] { a.Character, b })).ToArray()).ToArray()
                    ).ToArray()
                ).ToArray();

            //Now get every possible character each card can eliminate
            var possibleCharsFromCards = GetAllPossibleCharsFromACards(possibleCards).ToArray();

            //Now set up some possibilities that contain only one card
            var possibleCardCombinations = possibleCards.Select((a, index) => new Solution
            {
                Cards = new List<string> { a },
                //Use the index of each card to reference the possible characters it can remove, then remove them per card to form a initial list of cards
                Remaining = inputLowercasedTrimedTransformed.Select(b => b.RemoveFirstInCharArr(possibleCharsFromCards[index].ToLowerInvariant().ToCharArray())).ToList()
            })
            //Take the best scoring card, discard the rest
            .OrderBy(a => a.RemainingScore)
            .ThenBy(a => a.Remaining.Max(b => b.Length))
            .Take(1).ToList();
            #endregion Card Formation

            #region Card Selection
            //Find best combination by iteratively trying every combination + 1 more card, and choose the lowest scoring one
            while (!possibleCardCombinations.Any(a => a.Remaining.Sum(b => b.ToCharArray().Count()) == 0) && possibleCardCombinations.First().Cards.Count() < possibleCards.Count())
            {
                //Clear the list each iteration(as you can assume the last generations didn't work
                var newPossibilites = new List<Solution>();
                var currentRoundCardCombinations = possibleCardCombinations.ToArray();
                possibleCardCombinations.Clear();

                foreach (var trySolution in currentRoundCardCombinations)
                    foreach (var card in possibleCards.Select((a, index) => new { value = a, index }).Where(a => !trySolution.Cards.Contains(a.value)).ToArray())
                    {
                        var newSolution = new Solution();
                        newSolution.Cards = trySolution.Cards.ToList();
                        newSolution.Cards.Add(card.value);
                        newSolution.Remaining = trySolution.Remaining.ToList().Select(a => a.RemoveFirstInCharArr(possibleCharsFromCards[card.index].ToLowerInvariant().ToCharArray())).ToList();
                        newPossibilites.Add(newSolution);
                    }

                //Choose the highest scoring card
                possibleCardCombinations = newPossibilites
                    .OrderBy(a => a.RemainingScore)
                    .ThenBy(a => a.Remaining.Max(b => b.Length))
                    .Distinct().Take(1).ToList();
            }
            var finalCardSet = possibleCardCombinations.First().Cards.ToArray();
            #endregion Card Selection

            #region Output
            using (var image = new Bitmap(500, inputSplitTrimIndex.Count() * _defualtSpacing + finalCardSet.Count() * (_defualtFontSize / 2) + _defualtSpacing))
            using (Graphics graphic = Graphics.FromImage(image))
            {
                //Background
                graphic.FillRectangle(_defualtBackgroundColor, 0, 0, image.Width, image.Height);

                //Header
                graphic.DrawString("Total Number of Cards Required: " + finalCardSet.Count(), _defualtFont, _defualtForegroundColor, new PointF(0, 0));
                graphic.DrawString(
                    "Cards: " + String.Join(", ", finalCardSet.Select(a => a[0] + "/" + a[1])),
                    _defualtFont,
                    _defualtForegroundColor,
                    new RectangleF(0, _defualtSpacing, image.Width - _defualtSpacing, finalCardSet.Count() * 5));

                //Results
                foreach (var element in inputSplitTrimIndex)
                {
                    //Paint the word
                    graphic.DrawString(element.value + " -> ", _defualtFont, _defualtForegroundColor, new PointF(0, element.index * _defualtSpacing + finalCardSet.Count() * (_defualtFontSize / 2) + _defualtSpacing));

                    //Now go through each character, determining the matching card, and wether that card has to be flipped
                    foreach (var card in GetOrderedCardsRequired(inputLowercasedTrimedTransformed[element.index].ToLowerInvariant(), finalCardSet.ToArray()).ToArray().Select((a, index) => new { value = a, index }))
                        using (var tempGraphic = Graphics.FromImage(image))
                        {
                            //For cards that need to flip
                            if (Char.ToUpperInvariant(element.value[card.index]) != Char.ToUpperInvariant(card.value[0]) &&
                                Char.ToUpperInvariant(element.value[card.index]) != Char.ToUpperInvariant(card.value[1]))
                            {
                                //TODO this is hacky and needs to be rethought
                                var rotateAmount = _rotatableCharacters
                                    .OrderByDescending(a => a.Any(b => b.Value == Char.ToLowerInvariant(element.value[card.index])))
                                    .First(a => a.Any(b => Char.ToUpperInvariant(b.Value) == Char.ToUpperInvariant(element.value[card.index])))
                                    [1].RotationDifference;

                                //Rotate
                                tempGraphic.TranslateTransform(
                                    _defualtSpacing * (_defualtFontSize / 2) + card.index * _defualtSpacing + (rotateAmount == 90 ? 0 : _defualtSpacing / 2) + (rotateAmount == 180 ? -(_defualtSpacing / 4) : 0),
                                    finalCardSet.Count() * (_defualtFontSize / 2) + _defualtSpacing + element.index * _defualtSpacing + (rotateAmount == 180 ? 0 : _defualtSpacing / 2));
                                tempGraphic.RotateTransform(rotateAmount);

                                //Print string
                                tempGraphic.DrawString(
                                String.Join("/", card.value.ToCharArray().Select(a => new string(new char[] { a })).ToArray()),
                                _defualtFont,
                                Brushes.Black,
                                new RectangleF(-(_defualtSpacing / 2), -(_defualtSpacing / 2), _defualtSpacing, _defualtSpacing));
                            }
                            else
                                tempGraphic.DrawString(
                                     String.Join("/", card.value.ToCharArray().Select(a => new string(new char[] { a })).ToArray()),
                                     _defualtFont,
                                     _defualtForegroundColor,
                                     new RectangleF(
                                         _defualtSpacing * (_defualtFontSize / 2) + card.index * _defualtSpacing,
                                         finalCardSet.Count() * (_defualtFontSize / 2) + _defualtSpacing + element.index * _defualtSpacing,
                                         _defualtSpacing, _defualtSpacing));
                        }
                }

                OutputPictureBox.Image = new Bitmap(image);
            }
            #endregion Output
        }

        private IEnumerable<string> GetAllPossibleCharsFromACards(string[] cards)
        {
            return cards.Select(a =>
                new string(a.ToCharArray().Concat(_rotatableCharacters
                                    .Where(b => b.Select(c => c.Value).Intersect(a.ToCharArray()).Count() > 0)
                                    .SelectMany(b => b.Select(c => c.Value))
                                    .Distinct().ToArray()).Distinct().ToArray()));
        }

        private IEnumerable<string> GetOrderedCardsRequired(string word, string[] cards)
        {
            var solution = new List<string>();
            var tempCards = GetAllPossibleCharsFromACards(cards).Select((a, index) => new { value = a, index }).ToList();

            foreach (var letter in word.ToCharArray())
            {
                //TODO this still could theoretically fail I think
                var card = tempCards
                    //Order by the least number of characters match
                    .OrderBy(a => word.ToLowerInvariant().Intersect(a.value.ToLowerInvariant()).Count())
                    .ThenByDescending(a => tempCards.Sum(b => b.value.ToLowerInvariant().Intersect(a.value.ToLowerInvariant()).Count()))
                    //Then take the least useful card for the other parts of the word
                    .First(a => a.value.ToLowerInvariant().Contains(Char.ToLowerInvariant(letter)));
                solution.Add(cards[card.index]);
                tempCards.Remove(card);
            }
            return solution;
        }

        private static IEnumerable<string> UniqueBiDirection(string[] input)
        {
            var results = new List<string>();
            foreach (var element in input)
                if (!results.Any(a => a == new string(element.ToCharArray().Reverse().ToArray()) || a == element))
                    results.Add(element);
            return results;
        }

        private static IEnumerable<string> GetAllCasesTwoLengthArrayElements(string[] input)
        {
            if (input.Any(a => a.Length != 2))
                throw new ArgumentException("This method is only for arrays with two characters");

            List<string> output = input.ToList();
            foreach (var element in input)
            {
                output.Add(new string(new char[] { Char.ToUpperInvariant(element[0]), Char.ToUpperInvariant(element[1]) }));
                output.Add(new string(new char[] { element[0], Char.ToUpperInvariant(element[1]) }));
                output.Add(new string(new char[] { Char.ToUpperInvariant(element[0]), element[1] }));
            }
            return output;
        }

        private void SaveButton_Click(object sender, EventArgs e)
        {
            using (var image = new Bitmap(OutputPictureBox.Image))
                image.Save(Directory.GetCurrentDirectory() + "Output.png", ImageFormat.Png);
        }
    }

    public static class StringExtensions
    {
        public static string RemoveFirstInCharArr(this string source, char[] values)
        {
            var tempSource = source.ToUpperInvariant();
            foreach (var value in values)
            {
                int index = tempSource.IndexOf(Char.ToUpperInvariant(value));
                if (index >= 0) return source.Remove(index, 1);
            }
            return source;
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace CardChooserForms
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new CardChooser());
        }
    }
}

namespace CardChooserForms
{
    partial class CardChooser
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.InputRichTextBox = new System.Windows.Forms.RichTextBox();
            this.EnterInputLabel = new System.Windows.Forms.Label();
            this.RunButton = new System.Windows.Forms.Button();
            this.OutputPictureBox = new System.Windows.Forms.PictureBox();
            this.OutputPanel = new System.Windows.Forms.Panel();
            this.SaveButton = new System.Windows.Forms.Button();
            ((System.ComponentModel.ISupportInitialize)(this.OutputPictureBox)).BeginInit();
            this.OutputPanel.SuspendLayout();
            this.SuspendLayout();
            //
            // InputRichTextBox
            //
            this.InputRichTextBox.Location = new System.Drawing.Point(60, 40);
            this.InputRichTextBox.Name = "InputRichTextBox";
            this.InputRichTextBox.Size = new System.Drawing.Size(400, 100);
            this.InputRichTextBox.TabIndex = 0;
            this.InputRichTextBox.Text = "";
            //
            // EnterInputLabel
            //
            this.EnterInputLabel.AutoSize = true;
            this.EnterInputLabel.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.EnterInputLabel.Location = new System.Drawing.Point(57, 20);
            this.EnterInputLabel.Name = "EnterInputLabel";
            this.EnterInputLabel.Size = new System.Drawing.Size(81, 17);
            this.EnterInputLabel.TabIndex = 1;
            this.EnterInputLabel.Text = "Enter Input:";
            //
            // RunButton
            //
            this.RunButton.Font = new System.Drawing.Font("Microsoft Sans Serif", 20F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.RunButton.Location = new System.Drawing.Point(60, 147);
            this.RunButton.Name = "RunButton";
            this.RunButton.Size = new System.Drawing.Size(180, 52);
            this.RunButton.TabIndex = 2;
            this.RunButton.Text = "Run";
            this.RunButton.UseVisualStyleBackColor = true;
            this.RunButton.Click += new System.EventHandler(this.RunButton_Click);
            //
            // OutputPictureBox
            //
            this.OutputPictureBox.Location = new System.Drawing.Point(3, 3);
            this.OutputPictureBox.Name = "OutputPictureBox";
            this.OutputPictureBox.Size = new System.Drawing.Size(500, 500);
            this.OutputPictureBox.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize;
            this.OutputPictureBox.TabIndex = 3;
            this.OutputPictureBox.TabStop = false;
            //
            // OutputPanel
            //
            this.OutputPanel.AutoScroll = true;
            this.OutputPanel.Controls.Add(this.OutputPictureBox);
            this.OutputPanel.Location = new System.Drawing.Point(4, 205);
            this.OutputPanel.Name = "OutputPanel";
            this.OutputPanel.Size = new System.Drawing.Size(520, 520);
            this.OutputPanel.TabIndex = 4;
            //
            // SaveButton
            //
            this.SaveButton.Font = new System.Drawing.Font("Microsoft Sans Serif", 20F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.SaveButton.Location = new System.Drawing.Point(280, 147);
            this.SaveButton.Name = "SaveButton";
            this.SaveButton.Size = new System.Drawing.Size(180, 52);
            this.SaveButton.TabIndex = 5;
            this.SaveButton.Text = "Save";
            this.SaveButton.UseVisualStyleBackColor = true;
            this.SaveButton.Click += new System.EventHandler(this.SaveButton_Click);
            //
            // CardChooser
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(534, 737);
            this.Controls.Add(this.SaveButton);
            this.Controls.Add(this.RunButton);
            this.Controls.Add(this.EnterInputLabel);
            this.Controls.Add(this.InputRichTextBox);
            this.Controls.Add(this.OutputPanel);
            this.Name = "CardChooser";
            this.Text = "Card Chooser";
            ((System.ComponentModel.ISupportInitialize)(this.OutputPictureBox)).EndInit();
            this.OutputPanel.ResumeLayout(false);
            this.OutputPanel.PerformLayout();
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.RichTextBox InputRichTextBox;
        private System.Windows.Forms.Label EnterInputLabel;
        private System.Windows.Forms.Button RunButton;
        private System.Windows.Forms.PictureBox OutputPictureBox;
        private System.Windows.Forms.Panel OutputPanel;
        private System.Windows.Forms.Button SaveButton;
    }
}


Find a numeric coincidence when representing numbers in various bases Recently, when doing some code-golf challenge, I came up with with two solutions, in 69 and 105 bytes. It's a remarkable coincidence, because:

69 (decimal) = 105 (octal)
69 (hexadecimal) = 105 (decimal)

What other numbers have this property (using different bases)? You should help me answer this question!

Write a program or a subroutine that receives as input 3 numbers (base1, base2, base3, in ascending order), and prints two sequences of digits d1 d2 d3 ... and D1 D2 D3 ... that reproduce this numerical coincidence for the specified bases.

To make sure the various fine points are covered:

Evaluate one sequence as a number in base base1, and the other sequence in base base2 -- you must get the same number
Evaluate one sequence as a number in base base2, and the other sequence in base base3 -- you must get the same number
Both sequences must have finite length, which is greater than 1
Separate the sequences of digits with whitespace or in any other unambiguous way
Output to stdout or other similar output device
All digits must be between 0 and base-1; leading zeros are not allowed
If a digit is greater than 9, use a or A for 10, b for 11, ..., z for 35
You may assume that all bases are different, come in ascending order and are in the range 2...36; are represented in the most natural way for your language
If there is no answer, your code must signal it in some way (e.g. outputting nothing)
If there is an answer whose larger number is less than 1679616 (364), your code must find it; otherwise, it may output as if no solution exists
Code-golf: shortest code wins!

Example input:

8, 10, 16

Example output:

69 105

or

104 68

Or any other solution.

I'll be happy if you provide theoretical insights into this problem (How to determine whether a solution exists? Is there an infinite number of solutions?).

Python 2, 158 bytes

Came a bit too easily, so I might be missing something obvious!

s=lambda n,b:(n/b and s(n/b,b)or'')+chr(48+n%b+39*(n%b>9))
def f(a,b,c):
 for n in range(b,36**4):
  x=s(n,a);y=s(n,b)
  if int(x,b)==int(y,c):print x,y;break

The base conversion function is lovingly stolen from @ugoren's solution to Print integers in any base up to 36. The code simply tries all possible values for the smaller number and the rest is fully determined. We start counting from base2 to ensure both sequences are at least length 2.

>>> f(8, 10, 16)
100 64
>>> f(8, 10, 17)
>>> f(16, 20, 24)
20 1c


Simple golfing interpreter Challenge:

Your job is to create a simple interpreter for a simple golfing language.

Input:

Input will be in the form of string separated by spaces.

You can replace space separation with what you want

Output:

Output the result (a number or a string) obtained after performing all operations. If there are more than one output join the together to give a single result (no separators). The variable's initial value is always zero. i.e: It start at 0

Language Syntax :

The language has following operators :

inc  ---> add one to variable
dec  ---> remove one from variable
mult ---> multiply variable by 2
half ---> divide the variable by 2
Pri  ---> print the variable to console (or whatever your language has)
exit ---> end the program (anything after this is ignored)

Examples:

inc inc inc dec Pri exit                 ---> 2
dec inc mult inc inc Pri                 ---> 2
inc inc inc mult half Pri exit inc       ---> 3
inc Pri inc Pri inc Pri exit half mult   ---> 123
Pri exit                                 ---> 0
inc half Pri exit                        ---> 0.5

Restriction:

This is code-golf so shortest code in bytes for each language will win.

Note:

Input will always be valid . (string of operators separated with space)
You can round down to nearest integer if you don't want decimal places.

shell + sed + dc, 56 61 bytes

sed '1i0
s/.//2g;y"idmhe"+-*/q";i1
/[*/]/i1+
/P/crdn'|dc

Try it online!
Converts the program into a dc program, then evaluates it as dc code. This takes the input separated by newlines. Note that dc is stack-based and uses reverse polish notation, so 5 2- gives 3, and numbers are always rounded down.
The input is first piped to sed
1i0 on the first line of input, insert (prepend) a 0, this will be the accumulator
s/.//2g remove everything but the first character on each line
y"idmhe"+-*/q" transliterate idmhe into +-*/q respectively, + - * / are the arithmetic commands and q quits the program
i1 on every line insert a 1 - this satisfies addition and subtraction
/[*/]/ on every line containing * or /, i1+ additionally insert 1+ because of the preceding 1, which dc will eventually evaluate into 2
/P/ on every line containing P, crdn change it into rdn, equivalent to reverse the top two elements, to rid the inserted 1, and duplicate and output as a number without newline (whilst popping it, hence the earlier duplicate) in dc
Now this is evaluated as a dc expression.


Calculate a square and a square root! You must make a polyglot that outputs the square of the input in one language and the square root of the input in another. The shortest answer in bytes wins!

You must have a precision of at least 3 decimal places, and the input will always be a positive float.

C and C++, 68 65 bytes

#include<math.h>
float f(float n){auto p=.5;return pow(n,2-p*3);}

Original answer:

#include<math.h>
float f(float n){return pow(n,sizeof('-')-1?2:.5);}

For both versions, C produces n^2 and C++ produces sqrt(n).


Expand an encoded string There's the classic run length encoding and decoding.

input   output
a3b2c5  aaabbccccc

And that's fairly straight forward and done before.

The challenge is to also account for a non-standard behavior when multiple characters precede the run length (a single digit from 0-9). Each character before the run length digit (the last digit before a non-digit or end of the string) has that value applied to it individually and printed out in order.

Some test input and output including some edge cases:

input   output
ab3c5   aaabbbccccc
a0b3    bbb
13b1    111b
a13b1   aaa111b
a123b1  aaa111222b
aa2a1b1 aaaaab

A character sequence ([a-zA-Z0-9]+) must be followed by its run length length ([0-9])
Only valid input needs to be considered (([a-zA-Z0-9]+[0-9])*)

yes, empty string is valid input.

Input is via standard input, output via standard output

This is code golf, number of bytes determines the winner.

Perl/Bash 54 40+1 = 41 bytes

perl -pe's:(\D*\d*)(\d):"\$1=~s/./\$&x$2/egr":ege'

It's basically a regex within a regex. And a bit of magic.

Explanation

The outer regex /(\D*\d*)(\d)/g extracts each run-length encoded group. We capture the stuff to repeat in $1 and the number of repetitions in $2. Now we substitute each such group with the expansion of that group. For that, we evaluate the code "\$1=~s/./\$&x$2/egr" two times (as by the /ee flag on the outer substitution).

The first evaluation will only interpolate the number of repetitions into the string – the other variables are protected by a backslash. So assuming the input a14, we would now have the code $1=~s/./$&x4/egr, which will be evaluated again.

This will apply the substitution to the contents of $1 (the stuff to repeat a1). The substitution matches each character .. The $& variable holds the whole match, which we repeat x4 times. We do this /globally for each match and /return the substituted string rather than modifying the $1 variable (which is read-only). So the result of the inner substitution is aaaa1111.

The -p flag applies the substitution to each input line and prints out the result.


Distributing Numbers In this challenge you'll be using be distributing a product over sums and differences of numbers, as explained here.

Examples

  Input      |     Output
-------------|-------------
23(12+42)    | (23*12)+(23*42)
9(62-5)      | (9*62)-(9*5)
4(17+8-14)   | (4*17)+(4*8)-(4*14)
15(-5)       | -(15*5)
2(3)         | (2*3)
8(+18)       | +(8*18)
8(-40+18)    | -(8*40)+(8*18)

Specification

The input will be a string of the form n(_), with a single positive unsigned integer n followed by a parenthesized expression _. This expression _ will consist of sums and difference of one of more positive-integer terms separated by + and - signs. The first term may be preceded by a + sign, a - sign, or by no sign.

In the output, the initial number n should be distributed to multiply each of the terms. Each term of a should be left-multiplied by n to produce the parenthesized expression (n*a), and these new terms should be combined with + and - signs in exactly the same way as the original terms were.

Invalid Inputs

These are examples of inputs you don't have to handle.

3(5 plus 3)
6(5 13)
(5+8)(6+6)
(5+3)8

Winning

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

JavaScript 65 bytes

s=>(q=s.split(/[()]/))[1].replace(/(\D?)(\d+)/g,`$1(${q[0]}*$2)`)

This will take the input. Get the + or -, then the digits, then replace it in the correct order.

Explanation

s=>   // Function with argument "s"
  (q= // Set q to...
    s.split(/[()]/) // Splits on parenthesis, returns array
  )
  [1] // Gets second match or text inside brackets
  .replace(/ // Replaces string
     (\D?)  // Try to match a non-digit, the +-/* (group 1)
     (\d+)  // Then match one or more digits (group 2)
  /,
      // $1 is group 1 and $2 is group 2 q[0] is the text before the parenthesis
  `$1(${q[0]}*$2)`
  )

Usage

This only works in Firefox and Safari Nightly maybe Edge? because it uses ES6 features. You can run it by:

var t=s=>(q=s.split(/[()]/))[1].replace(/(\D?)(\d+)/g,`$1(${q[0]}*$2)`)

t("5(-6+7+3-8+9)"); // -(5*6)+(5*7)+(5*3)-(5*8)+(5*9)


Draw Concentric ASCII Hexagons Write the shortest program possible that takes in a set of distinct positive integers and outputs an ASCII rendering of concentric hexagons with those side lengths, made from slashes, underscores, spaces, and newlines.
The shortest program in bytes as counted by https://mothereff.in/byte-counter wins.
Examples
(They look better with less line spacing.)
If the input is 1 the output should be the hexagon with side length 1:
 __
/  \
\__/

Notice that two underscores are used for the top and bottom of the hexagon so it is better proportioned.
In general, the size N hexagon contains N slashes on each angled side and 2*N underscores on on both the top and bottom.
If the input is 1 2 the output should be the concentric hexagons with side length 1 and 2:
  ____
 / __ \
/ /  \ \
\ \__/ /
 \____/

If the input is 1 3 the output should be:
   ______
  /      \
 /   __   \
/   /  \   \
\   \__/   /
 \        /
  \______/

If the input is 1 3 2 the output should be:
   ______
  / ____ \
 / / __ \ \
/ / /  \ \ \
\ \ \__/ / /
 \ \____/ /
  \______/

etc.
I/O Rules
Input must come from either the command line or stdin but may be in whatever format is most convenient.
For example, you might give each number as a command line argument: > myprogram 1 3 2, or you might prompt the user to input the numbers as a preformatted list: [1, 3, 2].
Output must go to stdout or your language's closest equivalent.
Additional Rules

The input will always be a set of distinct positive integers, not necessarily in any order.
The output must...

not contain any characters besides /\ _ and newlines.
have no trailing spaces or unnecessary leading spaces.
not contain extraneous leading newlines but may have one optional trailing newline.

If nothing is input then output nothing (except possibly one newline).
If it helps you may assume that the input integers are less than 216.


How many atoms in the hydrocarbon? How many atoms in the hydrocarbon?
A hydrocarbon is a chemical compound which consists of only hydrogen and carbon atoms. For this challenge, we will only consider the three simplest kinds of hydrocarbons: alkanes, alkenes, and alkynes with no branches.
An alkane with \$n\$ carbon atoms contains \$2n+2\$ hydrogen atoms. An alkene with \$n\$ carbon atoms contains \$2n\$ hydrogen atoms. An alkyne with \$n\$ carbon atoms contains \$2n-2\$ hydrogen atoms.
Each kind of hydrocarbon is named with a prefix indicating the number of carbon atoms it contains, followed by the suffix ane, ene, or yne if it is an alkane, alkene, or alkyne respectively. The numerical prefixes are as follows:
1  <-> meth
2  <-> eth
3  <-> prop
4  <-> but
5  <-> pent
6  <-> hex
7  <-> hept
8  <-> oct
9  <-> non
10 <-> dec

For example, we can see propane has 3 carbon and 8 hydrogen atoms, and heptyne has 7 carbon and 12 hydrogen atoms.
Challenge
Your task is to write a function or program that receives a string or list of characters representing the name of a hydrocarbon, and produces or outputs the number of carbon and hydrogen atoms in a molecule of that hydrocarbon.
For each of the 30 hydrocarbon names, the code must accept at least one possible capitalization of that name. For example, it is fine if your code works for mEthane but not methane, and ETHAnE but not ETHANE, and Propane but not propane. The inputs methene and methyne may give undefined output since those are not real chemicals.
The input and output can be in any convenient format. You don't need to label which number represents carbon and which represents hydrogen, just keep the order of the numbers consistent.
You may assume the input will correspond to a valid hydrocarbon, and there are at most 10 carbon atoms.
Examples
Possible Input -> Possible Output
Methane        -> 1 4
propane        -> 3 8
Heptyne        -> 7 12
Decene         -> 10 20

Rules

No standard loopholes.
Shortest code in bytes wins.

05AB1E,  27 26  24 bytes

Saved 1 byte thanks to @KevinCruijssen
Saved 2 bytes thanks to @Grimmy

Note: This code was based on my understanding that only the capitalization of the first letter was customizable. It has since been clarified that it applies to all letters, leading to this significantly shorter answer by Grimmy.

Expects mEpBPhHond for the capitalization of the first letter.

ćC•>·¿*•s÷θD>,₂I3(èH÷+·,

Try it online!

How?

We define the following magic constant:

$$M=1902159854$$

The number of carbon atoms is given by:

$$c=\left(\left\lfloor\frac{M}{n}\right\rfloor\bmod 10\right)+1$$

where \$n\$ is the first character of the input turned into an 05AB1E code point (0-9, A-Z, a-z, ...).

 input |  n  | floor(M/n) | mod 10
-------+-----+------------+--------
 meth- |  48 |   39628330 |   0
 Eth-  |  14 |  135868561 |   1
 prop- |  51 |   37297252 |   2
 But-  |  11 |  172923623 |   3
 Pent- |  25 |   76086394 |   4
 hex-  |  43 |   44236275 |   5
 Hept- |  17 |  111891756 |   6
 oct-  |  50 |   38043197 |   7
 non-  |  49 |   38819588 |   8
 dec-  |  39 |   48773329 |   9

Commented

                         # example input: 'Heptyne'
ć                        # extract the first character -> 'H'
 C                       # turn it into an integer -> 17
  •>·¿*•                 # push the magic constant 1902159854
        s÷               # swap + integer division -> 1902159854 / 17 = 111891756
          θ              # keep the last digit (therefore a modulo 10) -> 6
           D>            # duplicate and increment the copy
             ,           # print the number of carbon atoms
              ₂          # push 26
               I         # push the input string
                3(è      # extract the 3rd to last character -> 'y'
                   H     # parse it as base-36 -> 34
                    ÷    # integer division -> 26 / 34 = 0
                     +   # add to the number of carbon atoms - 1 -> 6
                      ·  # double
                       , # print the number of hydrogen atoms


Create a version series The Definition

Given an integer x, a version series is a set of digits (base 10) from which any x-length subset of consecutive members is unique compared to all other possible subsets of the same length (a unique "version").

The Task

Write a function which, when passed some subset length x, produces a version series, considering a scoring determined by the sum of the total number of characters outputted by inputs 1 through 10 (so, f(1) + f(2) + ... + f(10)).

Further rules

The output must always be the same for a specific x.
Please do not change your algorithm (except for corrections) after posting and try to avoid using others' work.

Examples

Let f(x) be the function which returns the version series.

>>> f(3)
0010111

Note that this is a valid version series as all possible consecutive subsets of length 3 (001, 010, 011, 111) are unique. This would obviously be a terrible score, however.

>>> f(3)
0123456789876543210

This is another valid version series, with a slightly better score. This is valid for the same reasoning as before.

>>> f(3)
001010011110111

This is clearly not valid; the subsets 001, 010, 101, 111 all occur more than once.

Trivia

I have referred to this as a version series as it may be used to identify a range of compatible versions by taking a larger subset of consecutive values within the full set to identify a range of compatible versions that lie therein.

Verifier (in Java)

import java.util.Scanner;
import java.util.ArrayList;

public class Checker {
    public static void main(String[] args) throws Exception {
        int substringLength = Integer.parseInt(args[0]);

        Scanner sc = new Scanner(System.in);
        sc.useDelimiter("");

        ArrayList<Character[]> active = new ArrayList<Character[]>();

        Character[] current = new Character[substringLength],
            compare, prev;

        for (int i = 0; i < substringLength; i++) {
            current[i] = sc.next().charAt(0);
        }

        for (int index = 0; sc.hasNext(); index++) {
            for (int k = 0; k < index; k++) {
                boolean differ = false;
                compare = active.get(k);
                for (int j = 0; j < substringLength; j++) {
                    differ = differ || compare[j].compareTo(current[j]) != 0;
                }
                if (!differ)
                    throw new Exception("Match found for subset " + index);
            }
            active.add(current);
            prev = current;
            current = new Character[substringLength];
            for (int k = 1; k < substringLength; k++) {
                current[k - 1] = prev[k];
            }
            current[substringLength - 1] = sc.next().charAt(0);
        }

        System.out.println("Input is a valid version series.");
    }
}

Compile this as Checker.java, and call with program <x> | java Checker <x>, where x is your input (obviously, the input to your program is flexible).

If you are unable (or unwilling) to use Java, you may implement your own verifier, as long as you post it with your answer and show that it works.

Python 2, score: 11111111155
Score: sum(10**x+x-1 for x in range(1,11))
This program obtains the maximum possible score for any given x.
def f(x):
    s="0"*x
    while 1:
        for c in "1234567890":
            p=s+c
            if p[len(p)-x:]not in s:
                s=p
                break
        else:
            break
    return s

Try it online
This takes a long time to run for large inputs (like 6), because it's building strings thousands or millions of characters long. It also maintains a set of substrings and checks if a possible next substring is contained in it. It's not very efficient. I first tried a recursive solution, as well as a solution with a fixed number of iterations or something, but this was my working one.
Explanation:
I solved this by recognizing a pattern in the optimal solutions for x=1,2, which I created by hand as below. I roughly implemented the method I used to create f(2) in the function above, except that I just did zero last altogether.
1   0123456789
2   00102030405060708091121314151617181922324252627282933435363738394454647484955657585966768697787988990

This algorithm tries every number in order, with zero last. Failing to do zero last will result in an early termination. f(2), for example, would stop at 00102030405060708090, because all possible values starting with 0 have been exhausted. When doing this by hand, I simply started with f(1), added zeros between each digit, then went to every combination starting with a 1 (leaving out zero), then twos (leaving out zero and one), etc. Essentially, the algorithm must try the digit that you started with last.
The score is sum(10**x+x-1 for x in range(1,11)).
I used this formula to compute the score, because the output for all values 1-10 would probably take many days (months?) to complete. The highest I received the output for was f(6), which took ~10-15 minutes. It'd take at least 10000 times that for f(10). The lengths of s and p go from 1 to 10**x. The for loop runs exactly 10 times, no matter what.
Output:
They are slightly different than above because zeros are done last:
1   0123456789
2   00112131415161718191022324252627282920334353637383930445464748494055657585950667686960778797088980990
3   000111211311411511611711811911012212312412512612712812912013213313413513613713813913014214314414514614714814914015215315415515615715815915016216316416516616716816916017217317417517617717817917018218318418518618718818918019219319419519619719819919010210310410510610710810910022232242252262272282292202332342352362372382392302432442452462472482492402532542552562572582592502632642652662672682692602732742752762772782792702832842852862872882892802932942952962972982992902032042052062072082092003334335336337338339330344345346347348349340354355356357358359350364365366367368369360374375376377378379370384385386387388389380394395396397398399390304305306307308309300444544644744844944045545645745845945046546646746846946047547647747847947048548648748848948049549649749849949040540640740840940055565575585595505665675685695605765775785795705865875885895805965975985995905065075085095006667668669660677678679670687688689680697698699690607608609600777877977078878978079879979070870970088898808998908098009990900

I was going to make a pastebin of f(6), but it's past the maximum size limit a guest can create.
Validator - Counts how many unique subsets there are. If the result is 10**x, it's correct.


Shortest ELF for "Hello world\n"? Is it possible to write (pack) a shorter than 145 bytes version of a program with "Hello world" (plus new line) output if the length of the program is measured as a number of bytes in program's ELF (x86) representation? Reduction technique in mind is described here:

http://timelessname.com/elfbin/
http://www.muppetlabs.com/~breadbox/software/tiny/teensy.html

Please reply with providing a code example. Note, 1 says "Hi world" and [2] returns 42 instead of an output, hence I assume current solution to be 142 + (len("Hello") - len("Hi")) which is 145.

[EDIT]

Limits of ELF: syntactically a program translated into ELF is determined by its interpreter (libc), which is a combination of:

Target architecture (Generic, AMD64, ARM, IA-32, MIPS, etc.)
OS kernel (which communicates with implementation of ELF interpreter and often is itself packed into an ELF binary)

From TIS spec. 1.2

  There is one valid program interpreter for programs conforming to the
  ELF specification for the Intel architecture: /usr/lib/libc.so.1

In theory - all clear - multiple combinations times version differences (Arch, OS) are possible. In practice - because standard is less strict than any BNF for CFG or other finer (smaller) formal language - there can be implementation differences (options) including shorter length of the program.

On one hand, because ELF is not that precise (one naturally expects) it is much more difficult to do code-golf with it. Hence a "Hello world\n" program is expected to be by default in TIS ELF 1.2, x86 (Generic Intel), Linux 2.6.(20+). On the other hand having a shorter ELF that runs e.g. on *BSD seems like an extremely valuable knowledge to me!

For example ELF64 (latest draft) is much more interesting incl. the differences with ELF(x86). So, please share a solution that can be accepted with correction to specific configuration.

Motivation: It is the practical part that is interesting for me and code-golf is a very nice way to show how tricky it is to come up with any machine- (or even byte) code in general and why ELF does apparently such a good job (in my understanding). Thus a golf solution is not only cool per say but also can provide a practical knowledge of unexpected interpretation differences of ELF (if an alternative combination is given).

Even if you require full adherence to the ELF specification, you can squeeze it into 98 bytes:

            org     0x04B34000
            db      0x7F, "ELF", 1, 1, 1, 0 ; e_ident
            dd      0, 0
            dw      2                       ; e_type
            dw      3                       ; e_machine
            dd      1                       ; e_version
            dd      _start                  ; e_entry
            dd      phdr - $$               ; e_phoff
            dd      0                       ; e_shoff
            dd      0                       ; e_flags
            dw      0x34                    ; e_ehsize
            dw      0x20                    ; e_phentsize
phdr:       dd      1                       ; e_phnum       ; p_type
                                            ; e_shentsize
            dd      0                       ; e_shnum       ; p_offset
                                            ; e_shstrndx
            db      0                                       ; p_vaddr
_start:     inc     eax
            mov     bl, 4
            mov     dl, 12                                  ; p_paddr
            jmp     short part2
            dd      filesize                                ; p_filesz
            dd      filesize                                ; p_memsz
            dd      5                                       ; p_flags
            dd      0x1000                                  ; p_align
str:        db      'Hello world', 10
part2:      mov     ecx, str
again:      xchg    eax, ebx
            int     0x80
            jmp     short again
filesize    equ     $ - $$

Or if you prefer hex bytes:
7F 45 4C 46 01 01 01 00 00 00 00 00 00 00 00 00 02 00 03 00 01 00 00 00 35 40 B3 04 2C 00 00 00 00 00 00 00 00 00 00 00 34 00 20 00 01 00 00 00 00 00 00 00 00 40 B3 04 B2 0C EB 1C 62 00 00 00 62 00 00 00 05 00 00 00 00 10 00 00 48 65 6C 6C 6F 20 77 6F 72 6C 64 0A B9 4C 40 B3 04 93 CD 80 EB FB

The ELF specification explicitly permits different sections to overlap, so it is perfectly legal to let the program segment header table share bytes with the ELF header. Furthermore, the x86 version of the ELF standard states that the p_paddr field is ignored, as opposed to merely being unused (which typically comes with the requirement that it be set to zero. Thus it is safe to contain arbitrary bytes.

Finally, three more bytes are saved by overlapping the code with the load address.


Multiplying substrings Write a program that takes two integers as an input; the first can be any integer and the second is less than or equal to the number of digits in the first number. Let these numbers be a and b respectively.

The program will do the following

Concatenate a minimal number of 1s to the end of a so the number of digits in a is divisible by b.
Split a along every b digits.
Multiply the digits in each section together.
Concatenate the products together (if one of the numbers is zero, then concatenate 0).
Repeat this process until a number with strictly fewer than b digits is formed. Print this as the output, as well as the number of the process is repeated. Units are not necessary, but some form of separation between the final number and number of iterations is.

In the following test cases, the individual steps are shown for the purpose of understanding. It is not necessary for your program to display the steps.

Test case 1

1883915502469, 3

Steps

1883915502469          //Iteration 1
188391550246911
188 391 550 246 911
64 27 0 48 9
64270489               //Iteration 2
642704891
642 704 891
48 0 72
48072                  //Iteration 3
480721
480 721
0 14
014                    //Iteration 4
0

Sample Output: 0, 4

Test case 2

792624998126442, 4

Steps

792624998126442        //Iteration 1
7926249981264421
7926 2499 8126 4421
756 648 96 32
7566489632             //Iteration 2
756648963211
7566 4896 3211
1260 1728 6
126017286              //Iteration 3
126017286111
1260 1728 6111
0 112 6
01126                  //Iteration 4
01126111
0112 6111
0 6
06

Sample Output: 06, 4

The program must return an error (or just not print anything) if b>len(a). Also, b cannot equal 1 or the program will result in an infinite loop.

This is code golf, so standard rules apply. Shortest code in bytes wins.


What is the area of this polygon? Calculate the area of a polygon.

Inspired by this shoelace algorithm video.

Task

Your job is to create a program or function that calculates the area of a polygon. Program or function is defined according the the default definition in meta.

Input

You will receive the X and Y coordinates of each vertex of the polygon. You can take the input as a list of tuples ([[x1, y1], [x2, y2], etc]), a matrix, or a flat list ([x1, y1, x2, y2, etc]). Two lists containing x and y coordinates respectively are allowed as well. The vertices are numbered counterclockwise and the first vertex is the same as the last vertex provided, thus closing the polygon.

If you want you can take the input without the last vertex (so receive each coordinate just once).

You can assume that the edges of the polygons don't intersect. You can also assume that all vertices have integer coordinates.

Output

The area of the polygon. All standard output methods are allowed. If your language does not allow for float division and the solution would not be an integer, you are allowed to return a fraction. The fraction does not necessarily have to be simplified, so returning 2/4 would be allowed.

Winning criterium

Shortest code wins!

Test cases

[[4,4],[0,1],[-2,5],[-6,0],[-1,-4],[5,-2],[4,4]]
55

[[1,1],[0,1],[1,0],[1,1]]
0.5
1/2


Concatenating Primes Challenge:

You are given a string containing only digits. Your task is to output the minimum number of primes which must be concatenated to form the string. If this is impossible, output 0.

Test Cases:

Input -> Output:

252 -> 3
235 -> 2
92 -> 0
31149 -> 2

JavaScript (ES6), 123 121 120 bytes

f=(s,v)=>(p=n=>--n-1?s%n&&p(n):1)(s)||[...s].map((_,i)=>!(n=i&&(a=f(s.slice(0,i)))&&(b=f(s.slice(i)))&&a+b)|n>v?0:v=n)|v

Saved a byte thanks to @Neil!

Explanation

Takes a single string as input. Due to the prime checking method (recursive trial division), the greatest number that can be safely checked is 13840. Some numbers above this will fail due to the maximum call stack size being exceeded. It does, however, finish instantly for every case it can handle.

f=(s,v)=>
  (p=n=>--n-1?s%n&&p(n):1)(s) // if s is prime, return 1
  ||[...s].map((_,i)=>        // else for each index in s, split s into 2
    !(n=i&&                   // v = return value (initialised to undefined)
      (a=f(s.slice(0,i)))&&
      (b=f(s.slice(i)))&&
      a+b
    )|n>v?0:v=n               // if i, a, b and n are all > 0 and !(n > v), v = n
  )|v                         // cast v to an integer and return it

// Test
var testCases = [ "252", "235", "92", "3149", "24747" ];
document.write("<pre>" + testCases.map(c => c + ": " + f(c)).join("\n"));


How can I use cmp(a,b) with Python3? I was told that using the cmp function can be very useful in code-golf. But unfortunately, Python 3 doesn't have a cmp function.

So what's the shortest equivalent of cmp that works in python 3?

Python 3 does not have cmp. For golfing, you can do

11 chars

(a>b)-(a<b)

which loses 3 chars over cmp(a,b).

Amusingly, this is also an "official" workaround. The What's New in Python 3 page says "(If you really need the cmp() functionality, you could use the expression (a > b) - (a < b) as the equivalent for cmp(a, b).)"


Stacking Pythagorean Triangles Background
A Pythagorean triangle is a right triangle where each side length is an integer (that is, the side lengths form a Pythagorean triple):

Using the sides of this triangle, we can attach two more non-congruent Pythagorean triangles as follows:

We can continue with this pattern as we see fit, so long as no two triangles overlap, and connecting sides have equal length:

The question is, how many non-congruent Pythagorean triangles can we fit in a given space?
The Input
You will receive two integers as input, W and H, through function arguments, STDIN, strings, or whatever you like. The integers may be received as decimal, hexadecimal, binary, unary (good luck, Retina), or any other integer base. You may assume that max(W, H) <= 2^15 - 1.
The Output
Your program or function should calculate a list of non-overlapping connected non-congruent Pythagorean triangles and output a list of sets of three coordinates each, where the coordinates in a set form one of the Pythagorean triangles when connected by lines. Coordinates must be real numbers in our space (x must be in the interval [0, W] and y must be in the interval [0, H]), and distance should be accurate to machine precision. The order of the triangles and the exact format of each coordinate is not important.
It must be possible to "walk" from one triangle to any other only stepping over connected boundaries.
Using the above diagram as an example, let our input be W = 60, H = 60.
Our output could then be the following list of coordinates:
(0, 15), (0, 21), (8, 15)
(0, 21), (14.4, 40.2), (8, 15)
(0, 15), (8, 0), (8, 15)
(8, 0), (8, 15), (28, 15)
(8, 15), (28, 15), (28, 36)
(28, 15), (28, 36), (56, 36)

Now, 6 triangles is most certainly not the best we can do given our space. Can you do better?
Rules and Scoring

Your score for this challenge is the number of triangles your program generates given the input of W = 1000, H = 1000. I reserve the right to change this input if I suspect someone hardcoding this case.

You may not use builtins that calculate Pythagorean triples, and you may not hardcode a list of more than 2 Pythagorean triples (if you hardcode your program to always start with a (3, 4, 5) triangle, or some similar starting circumstance, that is okay).

You may write your submission in any language. Readability and commenting are encouraged.

You may find a list of Pythagorean triples here.

Standard Loopholes are disallowed.

Python 3, 109

This was certainly a deceptively hard challenge. There were many times writing the code that I found myself questioning my basic geometry abilities. That being said, I'm pretty happy with the result. I put no effort in to coming up with a complex algorithm for placing the triangles, and instead my code just blunders through always placing the smallest it can find. I hope I can improve this later on, or my answer will spurn others to find a better algorithm! All in all, a very fun problem, and it produces some interesting pictures.

Here's the code:

import time
import math

W = int(input("Enter W: "))
H = int(input("Enter H: "))

middle_x = math.floor(W/2)
middle_y = math.floor(H/2)

sides = [ # each side is in the format [length, [x0, y0], [x1, y1]]
    [3,[middle_x,middle_y],[middle_x+3,middle_y]],
    [4,[middle_x,middle_y],[middle_x,middle_y+4]],
    [5,[middle_x+3,middle_y],[middle_x,middle_y+4]]
    ]

triangles = [[0,1,2]] # each triangle is in the format [a, b, c] where a, b and c are the indexes of sides

used_triangles = [[3,4,5]] # a list of used Pythagorean triples, where lengths are ordered (a < b < c)

max_bounds_length = math.sqrt(W**2 + H**2)

def check_if_pyth_triple(a,b): # accepts two lists of the form [l, [x0,y0], [x1,y1]] defining two line segments
    # returns 0 if there are no triples, 1 if there is a triple with a right angle on a,
    # and 2 if there is a triple with the right angle opposite a
    c = math.sqrt(a[0]**2 + b[0]**2)
    if c.is_integer():
        if not sorted([a[0], b[0], c]) in used_triangles:
            return 1
        return 0
    else:
        if a[0] > b[0]:
            c = math.sqrt(a[0]**2 - b[0]**2)
            if c.is_integer() and not sorted([a[0], b[0], c]) in used_triangles:
                return 2
        return 0

def check_if_out_of_bounds(p):
    out = False
    if p[0] < 0 or p[0] > W:
        out = True
    if p[1] < 0 or p[1] > H:
        out = True
    return out

def in_between(a,b,c):
    maxi = max(a,c)
    mini = min(a,c)
    return mini < b < maxi

def sides_intersect(AB,CD): # accepts two lists of the form [l, [x0,y0], [x1,y1]] defining two line segments
    # doesn't count overlapping lines
    A = AB[1]
    B = AB[2]
    C = CD[1]
    D = CD[2]

    if A[0] == B[0]: # AB is vertical
        if C[0] == D[0]: # CD is vertical
            return False
        else:
            m1 = (C[1] - D[1])/(C[0] - D[0]) # slope of CD
            y = m1*(A[0] - C[0]) + C[1] # the y value of CD at AB's x value
            return in_between(A[1], y, B[1]) and in_between(C[0], A[0], D[0])
    else:
        m0 = (A[1] - B[1])/(A[0] - B[0]) # slope of AB
        if C[0] == D[0]: # CD is vertical
            y = m0*(C[0] - A[0]) + A[1] # the y value of CD at AB's x value
            return in_between(C[1], y, D[1]) and in_between(A[0],C[0],B[0])
        else:
            m1 = (C[1] - D[1])/(C[0] - D[0]) # slope of CD
            if m0 == m1:
                return False
            else:
                x = (m0*A[0] - m1*C[0] - A[1] + C[1])/(m0 - m1)
                return in_between(A[0], x, B[0]) and in_between(C[0], x, D[0])

def check_all_sides(b,triangle):
    no_intersections = True
    for side in sides:
        if sides_intersect(side, b):
            no_intersections = False
            break

    return no_intersections

def check_point_still_has_room(A): # This function is needed for the weird case when all 2pi degrees
    # around a point are filled by triangles, but you could fit in a small triangle into another one
    # already built around the point. Doing this won't cause sides_intersect() to detect it because
    # the sides will all be parallel. Crazy stuff.
    connecting_sides = []
    for side in sides:
        if A in side:
            connecting_sides.append(side)

    match_count = 0
    slopes = []
    for side in connecting_sides:
        B = side[1]
        if A == B:
            B = side[2]
        if not A[0] == B[0]:
            slope = round((A[1]-B[1])/(A[0]-B[0]),4)
        else:
            if A[1] < B[1]:
                slope = "infinity"
            else:
                slope = "neg_infinity"
        if slope in slopes:
            match_count -= 1
        else:
            slopes.append(slope)
            match_count += 1

    return match_count != 0

def construct_b(a,b,pyth_triple_info,straight_b_direction,bent_b_direction):
    # this function finds the correct third point of the triangle given a and the length of b
    # pyth_triple_info determines if a is a leg or the hypotenuse
    # the b_directions determine on which side of a the triangle should be formed
    a_p = 2 # this is the index of the point in a that is not the shared point with b
    if a[1] != b[1]:
        a_p = 1

    vx = a[a_p][0] - b[1][0] # v is our vector, and these are the coordinates, adjusted so that
    vy = a[a_p][1] - b[1][1] # the shared point is the origin

    if pyth_triple_info == 1:
        # because the dot product of orthogonal vectors is zero, we can use that and the Pythagorean formula
        # to get this simple formula for generating the coordinates of b's second point
        if vy == 0:
            x = 0
            y = b[0]
        else:
            x = b[0]/math.sqrt(1+((-vx/vy)**2)) # b[0] is the desired length
            y = -vx*x/vy

        x = x*straight_b_direction # since the vector is orthagonal, if we want to reverse the direction,
        y = y*straight_b_direction # it just means finding the mirror point

    elif pyth_triple_info == 2: # this finds the intersection of the two circles of radii b[0] and c
        # around a's endpoints, which is the third point of the triangle if a is the hypotenuse
        c = math.sqrt(a[0]**2 - b[0]**2)
        D = a[0]
        A = (b[0]**2 - c**2 + D**2 ) / (2*D)
        h = math.sqrt(b[0]**2 - A**2)
        x2 = vx*(A/D)
        y2 = vy*(A/D)
        x = x2 + h*vy/D
        y = y2 - h*vx/D

        if bent_b_direction == -1: # this constitutes reflection of the vector (-x,-y) around the normal vector n,
            # which accounts for finding the triangle on the opposite side of a
            dx = -x
            dy = -y
            v_length = math.sqrt(vx**2 + vy**2)
            nx = vx/v_length
            ny = vy/v_length

            d_dot_n = dx*nx + dy*ny

            x = dx - 2*d_dot_n*nx
            y = dy - 2*d_dot_n*ny

    x = x + b[1][0] # adjust back to the original frame
    y = y + b[1][1]

    return [x,y]

def construct_triangle(side_index):
    a = sides[side_index] # a is the base of the triangle
    a_p = 1
    b = [1, a[a_p], []] # side b, c is hypotenuse

    for index, triangle in enumerate(triangles):
        if side_index in triangle:
            triangle_index = index
            break

    triangle = list(triangles[triangle_index])
    triangle.remove(side_index)

    add_tri = False

    straight_b = construct_b(a,b,1,1,1)

    bent_b = construct_b(a,b,2,1,1)

    A = sides[triangle[0]][1]
    if A in a:
        A = sides[triangle[0]][2]

    Ax = A[0] - b[1][0] # adjusting A so that it's a vector
    Ay = A[1] - b[1][1]

    # these are for determining if construct_b() is going to the correct side
    triangle_on_side = (a[2][0]-a[1][0])*(A[1]-a[1][1]) - (a[2][1]-a[1][1])*(A[0]-a[1][0])
    straight_b_on_side = (a[2][0]-a[1][0])*(straight_b[1]-a[1][1]) - (a[2][1]-a[1][1])*(straight_b[0]-a[1][0])
    bent_b_on_side = (a[2][0]-a[1][0])*(bent_b[1]-a[1][1]) - (a[2][1]-a[1][1])*(bent_b[0]-a[1][0])

    straight_b_direction = 1
    if (triangle_on_side > 0 and straight_b_on_side > 0) or (triangle_on_side < 0 and straight_b_on_side < 0):
        straight_b_direction = -1

    bent_b_direction = 1
    if (triangle_on_side > 0 and bent_b_on_side > 0) or (triangle_on_side < 0 and bent_b_on_side < 0):
        bent_b_direction = -1

    a_ps = []
    for x in [1,2]:
        if check_point_still_has_room(a[x]): # here we check for that weird exception
            a_ps.append(x)

    while True:
        out_of_bounds = False
        if b[0] > max_bounds_length:
            break

        pyth_triple_info = check_if_pyth_triple(a,b)

        for a_p in a_ps:
            if a_p == 1: # this accounts for the change in direction when switching a's points
                new_bent_b_direction = bent_b_direction
            else:
                new_bent_b_direction = -bent_b_direction

            b[1] = a[a_p]
            if pyth_triple_info > 0:
                b[2] = construct_b(a,b,pyth_triple_info,straight_b_direction,new_bent_b_direction)

                if check_if_out_of_bounds(b[2]): # here is the check to make sure we don't go out of bounds
                    out_of_bounds = True
                    break

                if check_all_sides(b,triangle):
                    if pyth_triple_info == 1:
                        c = [math.sqrt(a[0]**2 + b[0]**2), a[3-a_p], b[2]]
                    else:
                        c = [math.sqrt(a[0]**2 - b[0]**2), a[3-a_p], b[2]]

                    if check_all_sides(c,triangle):
                        add_tri = True
                        break

        if out_of_bounds or add_tri:
            break

        b[0] += 1 # increment the length of b every time the loop goes through

    if add_tri: # this adds a new triangle
        sides.append(b)
        sides.append(c)
        sides_len = len(sides)
        triangles.append([side_index, sides_len - 2, sides_len - 1])
        used_triangles.append(sorted([a[0], b[0], c[0]])) # so we don't use the same triangle again

def build_all_triangles(): # this iterates through every side to see if a new triangle can be constructed
    # this is probably where real optimization would take place so more optimal triangles are placed first
    t0 = time.clock()

    index = 0
    while index < len(sides):
        construct_triangle(index)
        index += 1

    t1 = time.clock()

    triangles_points = [] # this is all for printing points
    for triangle in triangles:
        point_list = []
        for x in [1,2]:
            for side_index in triangle:
                point = sides[side_index][x]
                if not point in point_list:
                    point_list.append(point)
        triangles_points.append(point_list)

    for triangle in triangles_points:
        print(triangle)

    print(len(triangles), "triangles placed in", round(t1-t0,3), "seconds.")

def matplotlib_graph(): # this displays the triangles with matplotlib
    import pylab as pl
    import matplotlib.pyplot as plt
    from matplotlib import collections as mc

    lines = []
    for side in sides:
        lines.append([side[1],side[2]])

    lc = mc.LineCollection(lines)
    fig, ax = pl.subplots()
    ax.add_collection(lc)
    ax.autoscale()
    ax.margins(0.1)
    plt.show()

build_all_triangles()

Here's a graph of the output for W = 1000 and H = 1000 with 109 triangles:

Here is W = 10000 and H = 10000 with 724 triangles:

Call the matplotlib_graph() function after build_all_triangles() to graph the triangles.

I think the code runs reasonably fast: at W = 1000 and H = 1000 it takes 0.66 seconds, and at W = 10000 and H = 10000 it takes 45 seconds using my crappy laptop.


Arbitrary-length currying Write a function, f, that takes in a positive integer and returns a function.

The new function returned should be identical to f. However, when the "termination call" happens, f should instead return the sum of all integers passed.

For example, g=f(4) (if f is the first function) should set g to another function. h=g(3) will do the same. However, when you call h with no arguments (see below for details), it should output 7, as that is the sum of the previous function arguments.   Put another way, f(3)(4)() == 7.

Do note this is not the same as f(3,4)().

"Termination call" is one of the following options (your choice):

call w/o arguments
null as argument
any non-positive value

Arbitrary amount of function calls should be supported, there is no predefined limit.

It's guaranteed that total sum will not be bigger than 1'000.

We can assume that there is at least one call is made prior to "termination call".

Your code should not use static, per-program variables, so it should be possible to run the experiment multiple times in the same runtime and observe exactly the same behavior.

Examples:

f(1)() == 1
f(4)(2)(7)() == 13
f(4)(2)(7)(5)(2)() == 20

JavaScript (ES6), 18 bytes

f=n=>m=>m?f(m+n):n

Pass a falsy value to retrieve the sum. Zeros could be allowed for a cost of 2 bytes.

Try it online

Ungolfed:

f = function(n) {
    return function(m) {
        if (m) {
            return f(m+n);
        } else {
            return n;
        }
    }
}


Helicopter challenge There is a helicopter flying 500 meters from the ground. It can fly up 100 meters, which takes 1.0 secs. Or if it doesn't fly up it will fall 200 meters, which also takes 1.0 secs - This means if the instruction is anything other than "Fly" the helicopter falls. Build a program that takes input of a list of instructions, telling the helicopter when to fly and when not to. When the helicopter falls it should output the time counter.

INPUT:

  Fly Dance Fly Golf Fly Fly

OUTPUT:

  8.5 secs

Walkthrough:

  1) Fly == Fly so +100 = 600m

  2) Dance != Fly so -200 = 400m

  3) Fly == Fly so +100 = 500m

  4) Golf != Fly so -200m = 300m

  5) Fly == Fly so +100 = 400m

  6) Fly == Fly so +100 = 500m

  7) NO INSTRUCTIONS so -200 = 300m

  8) NO INSTRUCTIONS so -200 = 100m

  9) NO INSTRUCTIONS so -100 = 0m (This takes 0.5 seconds)

Each instruction should be separated by a space, and if the instuction isn't fly, then automatically fall. When the program runs out of instructions automatically fall. Your program must output in (float)secs, and if it takes  => 60.0 seconds display in mins and seconds eg. 1 mins 32.0 secs

Seconds are float decimal values, minutes are whole interger values. Also note capitalization does not matter your program should work for capitals or no capitals.

This is code-golf so the least NO bytes wins!

Python, 100 92 89 bytes

lambda I:sum(reduce(lambda(a,s),i:(a+(a>0)*(-1,.5)[i=='Fly'],s+(a>0)),I.split(),(2.5,0)))

try it online


Preprocessing primality The challenge:

Given an integer N, 1 < N < 2³¹, write code that uses the C preprocessor
to determine whether N is prime, and produces a "Hello world" program if N is prime,
or an error otherwise. Make the code as short as possible.
It's not very hard, so don't worry that there are so many rules; most
of them are boilerplate.

The following sample code (in example.c) works for N < 100:

#include <stdio.h>
int main() {
#if (N%2!=0 && N%3!=0 && N%5!=0 && N%7!=0) || (2==N || 3==N || 5==N || 7==N)
printf("Hello world!");
#else
Walkmen;
#endif
}

23 is prime but 99 is not, so:

c:\golf\preprime>gcc -std=c99 -DN=23 example.c

c:\golf\preprime>a
Hello world!
c:\golf\preprime>gcc -std=c99 -DN=99 example.c
example.c: In function 'main':
example.c:6:1: error: 'Walkmen' undeclared (first use in this function)
 Walkmen;
 ^
example.c:6:1: note: each undeclared identifier is reported only once for each function it appears in
c:\golf\preprime>

Rules

1 < N < 2147483648
N will be defined in a macro named N. N will be written using only the characters 0123456789 and will not begin with 0.
The code will be compiled with the command gcc -std=c99 -DN=<number> <filename>.c [-o <outfile>]
If N is prime, a valid C99 program must be successfully compiled. When executed, the program's output to stdout must be precisely Hello world! followed by zero or more newlines.
If N is composite, gcc must emit a compiler error. A linker error is not acceptable.
You may not utilize any GCC extensions.
You may not assume anything about the name of any file.
Note: It is not allowed to use implicit types or implicit function declarations.
Neither gcc nor any "Hello world" program may take more than 20 seconds to execute on a typical computer.
Shortest code length in UTF-8 bytes wins.

For reference, my ungolfed implementation is 571 bytes. Happy golfing!

441 characters

OK, here is another approach — this time breaking things down into a giant binary tree of tests. I was hoping this could be done recursively, but the C preprocessor doesn't support recursive functions...so I did this as a fallback.

Algorithm: This tests N for divisibility by 2 and by all odd numbers up to the square root of 2³². (Note: That's a bit of overkill, because it need only test potential divisors up to the square root of 2³¹, but it's easier to stick to powers of 2.)

#define A(x) (N%(x)||N==x)
#define B(x) A(x)&A(x+2)&A(x+4)&A(x+6)
#define C(x) B(x)&B(x+8)&B(x+16)&B(x+24)
#define D(x) C(x)&C(x+32)&C(x+64)&C(x+96)
#define E(x) D(x)&D(x+128)&D(x+256)&D(x+384)
#define F(x) E(x)&E(x+512)&E(x+1024)&E(x+1536)
#define G(x) F(x)&F(x+2048)&F(x+4096)&F(x+6144)
#define H(x) G(x)&G(x+8192)&G(x+16384)&G(x+24576)
#include <stdio.h>
int main(){
#if A(2)&H(3)&H(32771)
printf("Hello world!");
#else
Walkmen;
#endif
}

Notes:

The value 32771 is really just 3+32768.
Yes, the parentheses around x in N%(x) are indeed needed (but not in N==x).
Compiles as per instructions and obeys rules of output.
Elapsed time for each test of N (e.g., each invocation of the compiler) is about 1/6 second on my machine.


Distribution of Variables I was annoyed the other day when I got a point off in math class because I didn't distribute the factors of my function.

That is, I put (x+2)(x-3) when I should have put x^2 - x - 6.

Your job is to write a program that takes a string with the expression and convert it to the expanded form so I don't miss future points.

Rules

Any letters within the lowercase English alphabet can be used as "x" (for example: (a+1)(c+3)).
All exponents in answer must be in the form (variable)^n where n is the power
variables can be assumed to be 1 character long. That is, ab == a * b
Your answer should not contain the "*" character
The spaces before and after a + or - must be present. Otherwise, no spaces are permitted, except for trailing spaces.
You must account for exponents outside of parentheses, so (x+1)^n.

Specifications

You may create a program or function that takes a string parameter
Your program must output the correct expression to STDOUT or a text file
You may assume that all factors will be surrounded by parentheses. For example, x(x+1) will always be (x)(x+1).
There will never be any other operation besides multiplication between parenthesis. This will never happen: (x)+(x+1).
You may assume there will never be any nested parentheses/exponents.
Order of the resulting expression should be highest exponents first, as per usual math standards. Otherwise, order does not matter.
You may assume single digit exponents
Built in expansion libraries/functions are not allowed, as the comments mention below

Examples

(x+1)(x+2) --> x^2 + 3x + 2
(a)(a-4) --> a^2 - 4a
(c+1)^3 --> c^3 + 3c^2 + 3c  + 1
(a+1)(f-2) --> af - 2a + f - 2
(x-2)(x+4)(x-5)(x+10) --> x^4 + 7x^3 - 48x^2 - 140x + 400
(x+a+c)(b+g) --> xb + xg + ab + ag + cb + cg
(r+4)^2(b) --> br^2 + 8br + 16b

This is code-golf, so shortest program wins!

Bonus

-25 bytes to anyone who makes their program compatible with complex numbers