Interpret Interval Notation Interval notation is a way to write complicated range bounds more conveniently and concisely than writing an inequality. The challenge, should you choose to accept it, is to write a program or function that interprets a subset of interval notation. In this subset, intervals are a comma-separated pair of integers delimited by either brackets, parentheses, or both.
The range starts from the first integer ends at the second integer, inclusive if delimited by a bracket or exclusive if by parentheses. Multiple ranges, delimited by U, may be chained together, in which case duplicate elements are removed.
Input is a string in interval notation and output is a list of numbers contained in the specified interval. Only meaningful intervals are valid, so ranges may overlap, but the start will always be less than the end. Zero sized intervals should have an empty output. All integers in the interval must be displayed once and only once, but may be outputted in any particular order.
This is code-golf so the lowest byte count wins.
Other Details

Invalid inputs are undefined behavior
a ∪ or ⋃ symbol may be used instead of U
The U will always be between ranges, never in front or behind
If your language uses a character other than - to represent negative numbers that may be used instead

Test Cases
[0,5] -> [0,1,2,3,4,5]
(0,5] -> [1,2,3,4,5]
[0,5) -> [0,1,2,3,4]
(0,5) -> [1,2,3,4]
[9,13] -> [9,10,11,12,13]
[-5,-1] -> [-5,-4,-3,-2,-1]
[-5,-1) -> [-5,-4,-3,-2]
(-5,-1] -> [-4,-3,-2,-1]
(-5,-1) -> [-4,-3,-2]
[-3,2] -> [-3,-2,-1,0,1,2]
[-3,2) -> [-3,-2,-1,0,1]
(-3,2] -> [-2,-1,0,1,2]
(-3,2) -> [-2,-1,0,1]
[0,0] -> [0]
(0,0] -> []
[0,0) -> []
(0,0) -> []
[1,2) -> [1]
(1,2) -> []
[-3,0)U(0,3] -> [-3,-2,-1,1,2,3]
[-3,0)U[0,3] -> [-3,-2,-1,0,1,2,3]
[-3,0]U[0,3] -> [-3,-2,-1,0,1,2,3]
[-3,0]U[2,5] -> [-3,-2,-1,0,2,3,4,5]
[1,5]U[2,4] -> [1,2,3,4,5]
[-5,-1]U[-6,-2] -> [-5,-4,-3,-2,-1,-6]
[-5,-1]U[-6,0] -> [-6,-5,-4,-3,-2,-1,0]
[-5,-1]U[-6,-2]U[-7,0] -> [-7,-6,-5,-4,-3,-2,-1,0]
[1,2)U[2,3)U[3,4)U[4,5) -> [1,2,3,4]
[2,1) -> Undefined
U(5,10) -> Undefined
[13,18)U -> Undefined

Python 3, 79 bytes

lambda s:eval('{*range%s}'%s.translate({91:40,40:'(1+',93:'+1)',85:',*range'}))

Try it online!
-6 bytes thanks to ovs
-3 bytes thanks to dingledooper


Choose the last card in a poker hand Poker hands are ranked from best to worst as follows:

Straight flush - five cards of sequential rank, all of the same suit
Four of a kind - four cards of the same rank and one card of another rank
Full house - three cards of one rank and two cards of another rank
Flush - five cards all of the same suit
Straight - five cards of sequential rank
Three of a kind - three cards of the same rank and two cards of two other ranks
Two pair - two cards of the same rank, two cards of another rank and one card of a third rank
One pair - two cards of the same rank and three cards of three other ranks
High card - five cards not all of sequential rank or of the same suit, and none of which are of the same rank

Rank = The number on the card (A, K, Q, J, 10, 9, 8, 7, 6, 5, 4, 3, 2). You may choose to use T instead of 10.
Suit = hearts (h), spades (s), clubs (c) and diamonds (d).

Note that the Ace, A, can both be the highest and the lowest number (1 or 14).

A card can be identified by two letters As (Ace of spades), Jc (Jack of clubs), 7h (7 of hearts)  and so on.

Challenge:

You get four cards from the dealer (four input strings). Find and output the best possible last card you can get.

If there are cards that are equally good then you can choose which to pick.

Input and output formats are optional, but the individual cards must identified as shown above Jc and 2h.

Test cases:

Ah Kh Jh 10h
Qh

7d 8h 10c Jd
9d (or 9h, 9c, 9s)

Js 6c 10s 8h
Jc (or Jh, Jd)

Ac 4c 5d 3d
2h (or 2d, 2c, 2s)

5s 9s Js As
Ks

2h 3h 4h 5h
6h

Js Jc Ac Ah
As (or Ad)  <- Note that AAAJJ is better than AAJJJ because A is higher than J

10d 9d 5h 9c
9h (or 9s)

Ah Ac Ad As
Ks (or Kd, Kh, Kc)

4d 5h 8c Jd
Jc (or Js, Jh)

This is code golf, so the shortest submission in bytes win.

Pyth, 73 bytes

eo_S+*-5l@\AN}SPMJ+NZSM.:+\AT5+-4l{eMJlM.gPkJ-sM*=T+`M}2Tc4"JQKA""hscd"=Zc

This is pretty terrible. Parsing cards, sorting the values, ... Everything takes so many chars. But the approach is interesting.

Try it online: Demonstration or Test Suite

Explanation:

I generate all 52 cards, remove the four cards of the input, generate a score for each card (score of the hand), and print the card with the maximal score.

The score is a little bit odd. If I compare the score of two completely different hands, it may pick the wrong winner. E.g. a straight would beat 4 aces. But it works, if the first 4 cards are the same in both hands. And my computed score is actually not a value, but a list of values:

G: First I group the 5 cards by rank and take the lengths: 5h 5d 6c 5s Jd -> [3, 1, 1]
F: Then I append 4 minus the number of different suites to this list. Flush -> 3 gets appended, not flush -> 2/1/0 gets appended.
S: Add another number. 0 if it is not a straight, 4 if it is the straight A2345, or 5 if it is a higher straight.

These lists of 4-7 numbers get sorted in decreasing order and the list with maximal value is picked.

Why does this work? Here you see the possible configurations for all types. The letter beside the numbers, tell you with which rule this number got generated.

Straight flush: [5S, 3F, 1G, 1G, 1G, 1G, 1G] or [4S, 3F, 1G, 1G, 1G, 1G, 1G]
Four of a kind: [4G, 1G, 0F, 0S]
Full house: [3G, 2G, 1F, 0S] or [3G, 2G, 0F, 0S]
Flush: [3F, 1G, 1G, 1G, 1G, 1G, 0S]
Straight: [5S, 2F, 1G, 1G, 1G, 1G, 1G], [5S, 1F, 1G, 1G, 1G, 1G, 1G], [5S, 1G, 1G, 1G, 1G, 1G, 0F], [4S, 2F, 1G, 1G, 1G, 1G, 1G], [4S, 1F, 1G, 1G, 1G, 1G, 1G], [4S, 1G, 1G, 1G, 1G, 1G, 0F]
Three of a kind: [3G, 1G, 1G, 1F, 0S], [3G, 1G, 1G, 0F, 0S]
Two pair: [2G, 2G, 2F, 1G, 0S], [2G, 2G, 1F, 1G, 0S], [2G, 2G, 1G, 0F, 0S]
One pair: [2G, 2F, 1G, 1G, 1G, 0S], [2G, 1G, 1G, 1G, 1F, 0S], [2G, 1G, 1G, 1G, 0F, 0S]
High card: [2F, 1G, 1G, 1G, 1G, 1G, 0S], [1F, 1G, 1G, 1G, 1G, 1G, 0S], [1G, 1G, 1G, 1G, 1G, 0S, 0F]

Pyth compares lists element-wise. So it's obvious that a Straight flush will always beat Four of a kind. Most of the typical poker rules are obvious with these lists. Some seem conflicting.

A Straight will win against Four of a kind or a Full house: Not a problem. If you have a chance to get Four of a kind / Full house with the river card, than you can't reach a straight at the same time (since you already have 2 or 3 different suites in your hand).
A Straight will win against a flush. If you can reach a flush and a straight with the river card, then you also can reach a straight flush. And the straight flush has a better score than both the straight and the flush.
One pair [2G, 2F, 1G, 1G, 1G, 0S] will win against some two pair hands. Also no problem. If you get a two pair with the river card, than you had at least one pair before the river. But this means, that you can improve to three of a kind, which is better. So a two pair will actually never be the answer.
High card [2F, 1G, 1G, 1G, 1G, 1G, 0S] will win against some one pair hands. If this is the best score you can reach, before the river you will have 3 cards of one suite and one card of a different suite. But then you can choose the card with one of these two suites and with a value that already appears, and you'll end up with the score [2F, 2G, ...], which is also better.

So this chooses the correct type of solution. But how do I get the best one-pair (out of 4 possibilities), how do I choose the best straight, ...? Because two different one-pair solutions can have the same score.

That's easy. Pyth guaranties stable sorting (when taking the maximum). So I simple generate the cards in the order 2h 2s 2c 2d 3h 3s ... Ad. So the card with the highest value will automatically be the maximum.

Implementation details

=Zc splits the input string and stores the list of cards in Z.
=T+`M}2Tc4"JQKA" generates the list of ranks ['2', ..., '10', 'J', 'Q', 'K', 'A'] and stores them in T. -sM*T..."hscd"Z generates each combination of rank with the suites, and removes the cards of Z.

o... orders these remaining cards by: lM.gPkJ the lenght of the groups of the ranks, +-4l{eMJlM appends 4 - length(suites), +*-5l@\AN}SPMJ+NZSM.:+\AT5 appends 0/4/5 depending on suite (generate each substring of length 5 of "A"+T, check if the hand one of them (requires sorting the hand and sorting all subsets), multiply by 5 - number of "A"s in the card), _S sorts the list decreasing.

e pick the maximum and print.


Binary tree encoding Let's suppose you have a complete binary tree (i.e. each internal node has exactly two non empty descendants). Each node contains a nonzero integer. You are given the task of encoding and decoding the tree into/from a list of integers.

The tree is stored internally something like:

struct node {
  int data;
  struct node *left, *right;
};

And you have to implement two functions:

int *encode(struct node *root);
struct node *decode(int *array);

It is up to you how you encode and decode.

Points for:

minimum encoding length
complexity (ideally linear in number of nodes)
originality

No points for source code length and you are not restricted to C.

Tree example:

     5
    / \
   3   2
      / \
     2   1
    / \
   9   9

This Haskell program encodes a tree of n nodes in n Integers. The trick is that it encodes the node's data doubled, and then uses the lower-order bit to indicate if this is a leaf node, or an interior node.

Technically, the Parser monad here is over-kill, since there is only one parser created, decoder and I could have put the parser chaining logic directly there. But this way the decoder is very clear, and the Parser despite it's small size, is a reasonable simple parsing framework.

import Control.Monad (ap)

data Tree = Leaf Integer | Node Integer Tree Tree
  deriving (Eq, Show)

encode :: Tree -> [Integer]
encode (Leaf n)     = [n*2]
encode (Node n t u) = (n*2+1) : encode t ++ encode u

decode :: [Integer] -> Maybe Tree
decode = fullyParse decoder
  where
    decoder :: Parser Integer Tree
    decoder = do
      i <- next
      let n = i `div` 2
      if even i
        then return (Leaf n)
        else return (Node n) `ap` decoder `ap` decoder

-- A simple Parsing Monad
data Parser a b = P { runParser :: [a] -> Maybe (b, [a]) }

instance Monad (Parser a) where
  return a = P ( \ts -> Just (a, ts) )
  p >>= q  = P ( \ts -> runParser p ts >>= (\(v,ts') -> runParser (q v) ts') )
  fail _   = P ( const Nothing )

next :: Parser a a
next = P n
 where n (t:ts) = Just (t,ts)
       n _      = Nothing

fullyParse :: Parser a b -> [a] -> Maybe b
fullyParse p ts = runParser p ts >>= consumedResult
  where
    consumedResult (v,[]) = Just v
    consumedResult _      = Nothing

-- Example
main :: IO ()
main = do
    putStrLn $ "example:  " ++ show ex
    putStrLn $ "encoding: " ++ show encEx
    putStrLn $ "decoding: " ++ show decEx
    putStrLn $ "worked?   " ++ show worked
  where
    ex = Node 5
          (Leaf 3)
          (Node 2
            (Node 2
              (Leaf 9)
              (Leaf 9)
            )
            (Leaf 1)
          )
    encEx = encode ex
    decEx = decode encEx
    worked = maybe False (ex ==) decEx

Running this gets you:

> runhaskell TreeEncoding.hs
example:  Node 5 (Leaf 3) (Node 2 (Node 2 (Leaf 9) (Leaf 9)) (Leaf 1))
encoding: [11,6,5,5,18,18,2]
decoding: Just (Node 5 (Leaf 3) (Node 2 (Node 2 (Leaf 9) (Leaf 9)) (Leaf 1)))
worked?   True


Role-Playing Game Dice-Rolling Background

When playing an RPG such as Dungeons & Dragons, Pathfinder, or Paranoia, players each need a set of dice. You are hosting one such game this weekend, and some of the friends you invited have never played an RPG before. They don't want to commit to buying their own set of dice until they know they'll use them (if they want to keep playing). This is fine and dandy with you, but you're not going to let them use your lucky set of dice that you pre-rolled the ones out of...

Goal

...so you are going to write a program or function that simulates the dice-rolling for them.

Dice are often described in the format: <How many dice>d<Number of sides> A common set of dice for RPG use includes: 1d4, 1d6, 1d8, 2d10 (also used as 1d% or 1d100), 1d12, and 1d20.

Your code must accept a string of any number of the above dice specifiers separated by spaces or commas as input. It must then output the result of each individual die-roll separated by spaces, with parentheses around groups; then the sum of each grouping on the next line, separated by spaces; and finally, the total sum on a third line. Single-die groups don't have parentheses. Dice must always be in the same order as provided in the input.

The percent die, whether written as 1d% or 1d100, should be calculated as the concatenation of 2d10 (just 2 rolls, each from 0-9, but a final result of zero is instead counted as 100), but each occurrence will be displayed as if a single roll. 2d10 in the input will still be treated and displayed as 2 individual rolls. It can be easy to get confused by percent dice, here's a good explanation.

Edit: To clarify, the number of rolls may exceed 9.

Examples

Input:

1d4 3d6 2d8

Possible Output:

3 (1 5 2) (8 4)
3 8 12
23

Input:

1d20 1d% 2d10 1d100 5d12

Possible Output:

16 100 (9 4) 42 (5 1 7 7 11)
16 100 13 42 31
204

Rules

Standard loopholes are disallowed.
Printable ASCII in code, only.
code-golf - shortest code wins.
-10 bytes if the rolls are actually random, rather than pseudo-random.

Pyth, 48 bytes

-jdm?td(.*dhdJ.bmOSYNmm.xsk100cd\dcz))\,jdsMJssJ

Test Suite

Tricks / golfs in this code:

Everything that's not a number will be treated as 100, not just %.
To get the parentheses, I make the list into a tuple, then subtract out the commas.
This is the first time I've used .b, the binary map, which was added 3 days ago.
The code contains 6 different map functions.


Parallel accounts (Day 2) Challenge Taken with permission from my University Code Challenge Contest

After finishing her studies a couple of months ago, Marie opened a bank account to start receiving the payment of her first job in town. Since then she has been performing a few transactions with it. Her first payment was $1000 dollars. With that money she paid for a dinner in which she invited her parents (The dinner cost $150 dollars), then, she did a purchase in a well-known supermarket ($80 dollars) and a hotel reservation for her vacations ($200). At the end of the month she received her payment again (1040 dollars, a little more than the previous month) and the day after she spent another $70 dollars at the supermarket.

Today, she realized that if after paying the first $80 dollars in the supermarket a second account had been created and the first one frozen, both accounts would have exactly the same balance:

$$ \underbrace{1000\quad -150\quad -80}_{Total=770}\quad \underbrace{-200\quad 1040\quad -70}_{Total=770} $$

The event was so rare to her that she wants to continue ascertaining if the movements of her account and those of her friends have also this feature or not.

Challenge

Given a list of transactions, output the number of instants of time in which the owner of the bank account could have created a second account so that both had the same final balance.

Example: [1000, -150, -80, -200, 1040, -70]
$$ \color{red}{1)\quad\underbrace{}_{Total=0}\quad \underbrace{1000\quad -150\quad -80\quad -200\quad 1040\quad -70}_{Total=1540}} $$
$$ \color{red}{2)\quad\underbrace{1000}_{Total=1000}\quad \underbrace{-150\quad -80\quad -200\quad 1040\quad -70}_{Total=540}} $$
$$ \color{red}{3)\quad\underbrace{1000\quad -150}_{Total=850}\quad \underbrace{-80\quad -200\quad 1040\quad -70}_{Total=690}} $$
$$ \color{green}{4)\quad\underbrace{1000\quad -150\quad -80}_{Total=770}\quad \underbrace{-200\quad 1040\quad -70}_{Total=770}} $$
$$ \color{red}{5)\quad\underbrace{1000\quad -150\quad -80\quad-200}_{Total=570}\quad \underbrace{ 1040\quad -70}_{Total=970}} $$
$$ \color{red}{6)\quad\underbrace{1000\quad -150\quad -80\quad -200\quad 1040}_{Total=1610}\quad \underbrace{-70}_{Total=-70}} $$
$$ \color{red}{7)\quad\underbrace{1000\quad -150\quad -80\quad-200\quad 1040\quad -70}_{Total=1540}\quad \underbrace{}_{Total=0}} $$

Test Case

Input: 1000 -150 -80 -200 1040 -70 Output: 1
Input: 100 -100 Output: 2
Input: 1 2 3 Output: 1
Input: 10 -20 15 Output: 0
Input: 15 -15 15 -15 Output: 3
Input: 1 Output: 0

Notes

You can assume there wont be any transaction of $0 dollars
You can take input in any reasonable way

C# (Visual C# Interactive Compiler), 63 bytes

n=>n.Append(0).Where((a,b)=>n.Take(b).Sum()*2==n.Sum()).Count()

Saved 6 bytes thanks to dana

Try it online!


Convert Planck unit to SI metric Objective

Given a dimension of an SI unit, convert the Lorentz-Heaviside version of a Planck unit \$1\$ into SI metric.

What is a Planck unit?

Planck units are a set of units of measurement. It defines five fundamental constants of the universe as dimensionless \$1\$.

What is a dimension?

There are five types of fundamental dimension: L, M, T, Q, and Θ (U+0398; Greek Capital Letter Theta).

L stands for length and corresponds to SI unit m (meter).

M stands for mass and corresponds to SI unit kg (kilogram).

T stands for time and corresponds to SI unit s (second).

Q stands for electric charge and corresponds to SI unit C (Coulomb).

Θ stands for temperature and corresponds to SI unit K (Kelvin).

A dimension is a multiplicative combination of these. For example, SI unit V (volt) is same as kg·m²·C/s⁴ and thus corresponds to dimension L²MQ/T⁴.

Planck to SI

\$1\$ as Planck unit can be converted to SI metric as follows:

$$
1 = 5.72938×10^{−35} \space [\text{m}] = 6.13971×10^{−9} \space [\text{kg}] = 1.91112×10^{−43} \space [\text{s}] = 5.29082×10^{−19} \space [\text{C}] = 3.99674×10^{31} \space [\text{K}]
$$

Input and Output

A dimension is given as the input. Its type and format doesn't matter. In particular, it can be an size-5 array of signed integers, each integer representing the exponent of a fundamental dimension.

The Planck unit \$1\$ is to be converted to the SI unit that corresponds to the inputted dimension, and then outputted. The output type and format doesn't matter.

Examples

Let's say the input format is a tuple of five integers, representing L, M, T, Q, and Θ, respectively.

For example, If the input is \$(2,1,-1,-2,0)\$, it corresponds to SI unit Ohm, and thus:

$$
1 = \frac{(5.72938×10^{−35})^2 × (6.13971×10^{−9})}{(1.91112×10^{−43})×(5.29082×10^{−19})^2} \space [\text{Ω}]
$$

So the output is approximately \$376.730\$.

For another example, if the input is \$(-2,-1,3,0,1)\$, it corresponds to SI unit K/W, and thus:

$$
1 = \frac{(1.91112×10^{−43})^3 × (3.99674×10^{31})}{(5.72938×10^{−35})^2 × (6.13971×10^{−9})} \space [\text{K/W}]
$$

So the output is approximately \$1.38424×10^{−20}\$.

Note that, if the input is \$(0,0,0,0,0)\$, the output must be \$1\$.

Python 3, 118 \$\cdots\$ 85 80 bytes

Saved a whopping 29 bytes thanks to Surculose Sputum!!!
Saved 4 bytes thanks to Arnauld!!!
Saved 5 bytes thanks to xnor!!!

lambda a,b,c,d,e:399674e26**e/174539e29**a/162874e3**b/523253e37**c/189007e13**d

Try it online!


cadaddadadaddddaddddddr - linked list accessing Create a function (or closest equivalent, or full program) that takes an list of some datatype (your choice) that may be nested and a string (in either order), and generalizes the lisp c[ad]+r functions.

Functions are provided which perform compositions of up to four car and cdr operations. Their names consist of a C, followed by two, three, or fourany positive number occurrences of A or D, and finally an R. The series of A's and D's in each function's name is chosen to identify the series of car and cdr operations that is performed by the function. The order in which the A's and D's appear is the inverse of the order in which the corresponding operations are performed.

(source: common lisp hyperspec)
The car and cdr operations will return the first element and all the other elements, respectively, for the purposes of this challenge. The string will hold the operation you should perform.
Examples:
   Array    ,  Accessor  =>  Result
===================================
     [0,1,2],      'cdr' => [1,2]
 [0,[1,2],3],     'cadr' => [1,2]
 [[[[[0]]]]],   'caaaar' => [0]
          [],      'cdr' => do not need to handle (no cdr)
          [],      'car' => do not need to handle (no car)
    anything, 'cr'/'asd' => do not need to handle (invalid command)
         [0],      'car' => 0
         [0],      'cdr' => []

Reference Implementation

{

  const inp = document.getElementById("inp");
  const out = document.getElementById("out");
  inp.onchange = () => {
    const data = JSON.parse(inp.value);
    var list = data.list;
    data.cmd.match(/^c([ad]+)r$/)[1]
      .split("").reverse().forEach(letter =>
        list = letter === "a" ? list[0] : list.slice(1));
    out.value = JSON.stringify(list);
  };
  inp.onchange();

}
<textarea id="inp" rows="2" cols="50">
{ "cmd": "cadadr",
  "list": [0,[1,[2,3],4],5] }
</textarea>
<br>
<textarea readonly id="out" rows="1" cols="50">
waiting, there seems to be a problem
</textarea>

This is code-golf, shortest solution in bytes per language wins.

JavaScript (V8), 48 bytes

a=>f=b=>b[2]?b[[x,...r]=f(b.slice(1)),1]<f?x:r:a

Try it online!
-2 bytes thanks to @Arnauld!


Which tetromino is this? Given an unsigned 16-bit integer N, your task is to determine whether its binary representation mapped inside a 4x4 matrix is matching a tetromino shape, and if so, which shape it is.

Matrix

Each bit of N is mapped inside a 4x4 matrix, from left to right and from top to bottom, starting with the most significant one.

Example:

N = 17600
binary representation: 0100010011000000
matrix: [ [ 0, 1, 0, 0 ],
          [ 0, 1, 0, 0 ],
          [ 1, 1, 0, 0 ],
          [ 0, 0, 0, 0 ] ]

Tetromino shapes

Base shapes

There are 7 tetromino shapes, identified by the letters O, I, S, Z, L, J and T:

Rotations and translations

If a shape is translated and/or rotated within the 4x4 matrix, it is still considered a valid variation of the same tetromino. For instance, 17600, 1136, 2272 and 1604 should all be identified as J tetrominoes:

Don't wrap!

However, the shapes can't wrap around or be shifted beyond any boundary of the matrix. For instance, neither 568 nor 688 should be identified as J tetrominoes (let alone any other shape):

Clarifications and rules

You may take input as an integer, or directly as 16 binary digits in any reasonable format, such as a 2D array, a flat array or a delimited string.
The input is guaranteed to be an unsigned 16-bit integer (or its equivalent representation as an array or a string).
When a valid shape is identified, you must print or return the letter identifying the shape, in either lower or upper case.
If no shape is identified, you must print or return a value that doesn't match any tetromino letter. You may also choose to return nothing at all.
To be considered valid, the matrix must contain the exact tetromino shape without any additional cells (see 1911 and 34953 in the test cases).
This is code-golf, so the shortest answer in bytes wins!

Test cases

You can follow this link to get the test cases as 2D arrays.

0      -> false
50     -> false
51     -> 'O'
1911   -> false
15     -> 'I'
34952  -> 'I'
34953  -> false
1122   -> 'S'
3168   -> 'Z'
785    -> 'L'
1136   -> 'J'
568    -> false
688    -> false
35968  -> 'T'
19520  -> 'T'

Python 3, 124 bytes

def f(n):
 while n&4369<n/n:n>>=1
 while n&15<1:n>>=4
 return'TJLZSIO'["rēȣc63ıGtĲȱᄑ@'̢̑@@@@Ȳq".index(chr(n))%7]

Try it online!

Expects an integer n representing a 4 × 4 binary matrix. Throws if no tetromino is found.

Line 2 slides the shape to the right until a 1 is in the rightmost column. (4369 is 0001 0001 0001 0001 in binary.) Line 3 lowers the shape until a 1 is in the bottom row. Together this turns e.g.:

    0 1 0 0        0 0 0 0
    1 1 1 0  into  0 0 0 0
    0 0 0 0        0 0 1 0
    0 0 0 0        0 1 1 1

Then we look for the index of n in this list:

 [114  275  547   99   54   15   51
  305   71  116  306  561 4369   64
   39  802  785   64   64   64   64
  562  113   23]
#   T    J    L    Z    S    I    O

Each column of indices equivalent modulo 7 corresponds to a tetromino shape. 64 (@) is used as a padding value as n cannot be 64 at this point in the code.

NB. An exception is thrown for input 0 by computing n/n instead of 1.


Ratio of Uppercase Letters to Lowercase In this challenge you and your friends are debating on which case is better, uppercase or lowercase? To find out, you write a program to do this for you.

Because esolangs scare your friends, and verbose code scares you, your code will need to be as short as possible.

Examples

PrOgRaMiNgPuZzLeS & CoDe GoLf
0.52 uppercase

DowNGoAT RiGHtGoAt LeFTGoat UpGoAT
0.58 uppercase

Foo BaR Baz
0.56 lowercase

Specifications

The input will consist only of ASCII characters. All non-alphabetic characters should be ignored. There will be at least 1 character of each case

The output should be the amount of the case that appears the most often over the total amount of alphabetic characters. It should be a decimal accurate to at least 2 decimal places. If uppercase appears more often, the output should end with uppercase, or lowercase.

There will never the the same amount of uppercase and lowercase characters.

JavaScript (ES6) 87 bytes
Edit 1 byte saved thx ETHProductions
Edit 1 more byte saved thx l4me
An anonymous function. Long, but I didn't find a way to golf this more
s=>(l=t=0,s.replace(/[a-z]/ig,c=>l+=++t&&c>'Z'),l/=t,l<.5?1-l+' upp':l+' low')+'ercase'

Less golfed
s=>( // arrow function returning the value of an expression
  // here I use comma for clarity,
  // in the golfed version it's all merged in a single expression
  t = 0, // counter for letters
  l = 0, // counter for lowercase letters
  s.replace(
    /[a-z]/ig, // find all alphabetic chars, upper or lowercase
    c => // execute for each found char (in c)
        l += ++t && c>'Z', // increment t, increment l if c is lowercase
  ),
  l /= t, // l is the ratio now
  ( l < .5 // if ratio < 1/2
    ? (1-l) +' upp' // uppercase count / total (+" upp")
    : l +' low'     // lowrcase count / total (+" low")
  ) + 'ercase' // common suffix
)


Can I Choose Not to Fly? Inspired by a chat conversation I lurked.

I am an adventurer on the far away land of Zendikar. I truly enjoy traveling the land. Bushwhacking, weathering the roil and encountering strange and exotic flora and fauna are the highlights of any good adventure. Unfortunately, my duties as an adventurer do not always allow me to stop and smell the lotuses. Occasionally I am crunched for time and must hop on my kitesail and fly to my destination. I just glide over the land without being able to enjoy it.

The Challenge

Write a program that will let me know if I can choose not to fly. The program will take three inputs: my current location, my destination, and the maximum permitted travel time in days. Using the information below, determine if my travel time on foot is less than my maximum allowed travel time. If it is and I can travel on foot, return a truthy value. If the land travel time is as long as or longer than the maximum time, return a falsey value.

Guul Draz is two days away from Sejiri, its only neighboring territory.

Sejiri is one day away from Murasa and two days from Guul Draz.

Murasa is one day from Bala Ged,  one day from Akoum, two days from Tazeem, and one day from Sejiri.

Bala Ged is two days from Akoum and one day from Murasa.

Akoum is one day from Ondu, one day from Murasa and two days from Bala Ged.

Ondu is one day from Akoum, its only neighboring territory.

Tazeem is two days from Murasa, its only neighboring territory.

Every location is connected, but not always directly. For example, going from Tazeem to anywhere requires you to travel to Murasa first. There are no real branches in the path either. Protip: Only go to Bala Ged if it is one of your endpoints. Here is a rough map if you're lost:

                        Bala Ged --
                           |       \
Guul Draz ---- Sejiri -- Murasa -- Akoum -- Ondu
                            |
                            |
                         Tazeem

Scoring

This is code golf, so shortest program wins. Standard loopholes apply.

Test Cases

Guul Draz
Ondu
5

False

Bala Ged
Akoum
3

True

Tazeem
Sejiri
1

False

TI-BASIC, 84 82 bytes

Prompt Str1,Str2,X
"GSMAOBT->Str3
{-3,-1,0,1,2,i,-2i
Ans(inString(Str3,sub(Str1,1,1))-Ans(inString(Str3,sub(Str2,1,1
X>real(Ans-iAns

I store the positions of each city on the complex plane, then calculate the Manhattan distance. Bala Ged is at 0+1i, Guul Draz is at -3+0i, and so on.

There would be a 75-ish byte solution if quotes could be in strings, but one of TI-BASIC's limitations prevents that.


The 3x3 Hexa Prime Square Puzzle The 3x3 Hexa Prime Square Puzzle

Introduction

We consider 3x3 squares of hexadecimal digits (from 0 to F) such as:

2 E 3    1 F 3
8 1 5    7 2 7
D D 5    B B 9

We define a 3x3 Hexa Prime Square (HPS3) as such a square for which all hexadecimal numbers read from left to right and from top to bottom are odd primes (i.e. primes greater than 2).

This is true for the left square and false for the right square:

2 E 3 --> 0x2E3 = 739       1 F 3 --> 0x1F3 = 499
8 1 5 --> 0x815 = 2069      7 2 7 --> 0x727 = 1831
D D 5 --> 0xDD5 = 3541      B B 9 --> 0xBB9 = 3001
| | |                       | | |
| | +---> 0x355 = 853       | | +---> 0x379 = 889 = 7 x 127
| +-----> 0xE1D = 3613      | +-----> 0xF2B = 3883 = 11 x 353
+-------> 0x28D = 653       +-------> 0x17B = 379

Goal

Given a list of 9 hexadecimal digits, your goal is to find an arrangement that forms a HPS3.

Example:

Input: 123558DDE
Possible output: 2E3815DD5 (a flattened representation of the above left example)

Input / Output

Input and output formats are flexible. The only requirement is that output digits are ordered from left to right and from top to bottom. Below are some possible options:

"2E3815DD5"
[ 0x2, 0xE, 0x3, 0x8, 0x1, 0x5, 0xD, 0xD, 0x5 ]
[ "2", "E", "3", "8", "1", "5", "D", "D", "5" ]
[
  [ 0x2, 0xE, 0x3 ],
  [ 0x8, 0x1, 0x5 ],
  [ 0xD, 0xD, 0x5 ]
]
[ "2E3", "815", "DD5" ]
etc.

Using the same format for both input and output is not required.

Rules

This is code-golf, so the shortest answer in bytes wins. Standard loopholes are forbidden.
Your algorithm must be deterministic
You can't just bogosort the array until it's valid, even in a deterministic way (by using a constant random seed).
You may list all possible solutions for a given input, but this is neither required nor subject to a bonus.
You're not required to support inputs that do not admit any solution. (It's perfectly fine if your code is looping forever or crashing in that case.)

Test cases

Input       Possible output
---------------------------
123558dde   2e3815dd5
1155578ab   a7b851551
03bddffff   ffd0dfb3f
35899beff   8f99e3bf5
15899bbdf   581bb9fd9
14667799f   6f1469779
13378bcdd   78d1cd33b
24577bbdd   7274bd5db
1118bbddd   11b18dbdd
223556cdd   623c25dd5
12557899a   8a5295971
113579bbd   5b3db7191

05AB1E, 23 21 bytes

Uses CP-1252 encoding.

œJvy3ôD€SøJìHDps2›*P—

Too slow for TIO.

Explanation

œJ                     # all permutations of input as strings
  v                    # for each permutation
                       # EXAMPLE: 2E3815DD5
   y3ô                 # split in pieces of 3
                       # EXAMPLE: ['2E3','815','DD5']
      D                # duplicate
                       # EXAMPLE: ['2E3','815','DD5'], ['2E3','815','DD5']
       €SøJ            # zip the copy to swap rows and columns
                       # EXAMPLE: ['2E3','815','DD5'], ['28D','E1D','355']
           ì           # attach them to the same list
                       # EXAMPLE: ['2E3','815','DD5','28D','E1D','355']
            H          # convert from base 16 to base 10
                       # EXAMPLE: [739, 2069, 3541, 653, 3613, 853]
             D         # duplicate
                       # EXAMPLE: [739, 2069, 3541, 653, 3613, 853],[739, 2069, 3541, 653, 3613, 853]
              p        # check first copy for primality
                       # EXAMPLE: [739, 2069, 3541, 653, 3613, 853],[1,1,1,1,1,1]
               s2›     # check that each in second copy is larger than 2
                       # EXAMPLE: [1,1,1,1,1,1],[1,1,1,1,1,1]
                  *    # pairwise multiplication
                       # EXAMPLE: [1,1,1,1,1,1]
                   P   # product (1 if all were primes larger than 2, else 0)
                       # EXAMPLE: 1
                    —  # if 1, print y
                       # EXAMPLE: 2E3815DD5


Reconstruct a 3d arrangement of cubes from two of its projections Setup

Take the following 4x4x4 cube along with a 2D view of 3 of its faces, with a common 1x1x1 cube highlighted:

The arrows represent the points of view that generated the V1, V2 and V3 faces drawn underneath the big cube.

Given an arrangement of some 1x1x1 cubes inside the main cube we can try and identify it with only three projections. For example, the arrangement below:

could be represented as follows:

V1
X...
....
....
XXXX

V2
X...
X...
X...
X..X

V3
X...
X...
X...
XXXX

However, if we consider only projections on V1 and V2, most of the time we can't identify uniquely the arrangement being considered.(there are arrangements that can't be uniquely identified, even with the 6 projections)

Task

Given projections on V1 and V2, output the minimum and maximum number of 1x1x1 cubes that an arrangement could have and still produce the projections V1 and V2.

I'll walk you through 2 examples:

Explained example 1

V1
XXXX
....
....
....

V2
X...
X...
X...
X...

These two projections signal some directions along which there must be cubes:

and the output would be 4, 16; This is the case because both V3 below represent valid projections on V3:

V3a
X...
.X..
..X.
...X

This is a "diagonal" pattern of cubes in the back plane, when viewed from V3; ...

V3b
XXXX
XXXX
XXXX
XXXX

and this is a full face in the back plane.

Explained example 2

V1
XXXX
XXXX
XXXX
XXXX

V2
XXXX
....
....
....

These projections represent the top face of the main cube, so in this case we managed to identify the arrangement uniquely. The output in this case would be 16, 16 (or 16, see output rules below).

Input

Your code takes the projections on V1 and V2 as input. There are a variety of reasonable ways for you to take this input. I suggest the following to represent each projection:

An array of length 4 with strings of length 4, two different characters to encode "empty" or "filled", like ["X...", ".X..", "..X.", "...X"] for the V3a above.
An array/string of length 16, representing the 16 squares of the projection, like "X....X....X....X" for V3a above.
An integer where its base 2 expansion encodes the string above; 1 must represent the X above, so V3a above would be 33825 = b1000010000100001.

For any of the alternatives above, or for any other valid alternative we later decide that is helpful for you guys, you can take any face in any orientation you see fit, as long as it is consistent across test cases.

Output

The two non-negative integers representing the minimum and maximum possible number of 1x1x1 cubes in an arrangement that projects onto V1 and V2 like the input specifies. If the minimum and maximum are the same, you can print only one of them, if that helps you in any way.

Test cases

(I didn't really know how to format these... if needed, I can reformat them! Please let me know.)

XXXX
....
....
....,
X...
X...
X...
X... -> 4, 16

XXXX
XXXX
XXXX
XXXX,
XXXX
....
....
.... -> 16, 16

XXXX
XXXX
XXXX
XXXX,
XXXX
....
..X.
.... -> 16, 20

X..X
.XX.
.XX.
X..X,
X.XX
.X..
..X.
XX.X -> 8, 16

XXXX
XXXX
XXXX
XXXX,
XXXX
XXXX
XXXX
XXXX -> 16, 64

X...
....
....
XXXX,
X...
X...
X...
X..X -> 8, 8

X..X
....
....
XXXX,
X...
X...
X...
X..X -> 8, 12

This is code-golf so shortest submission in bytes, wins! If you liked this challenge, consider upvoting it! If you dislike this challenge, please give me your feedback. Happy golfing!

APL (Dyalog Unicode), 11 bytes

+.(⌈,×)/+⌿¨

Try it online!

Takes V1 and V2 as two binary matrices inside a nested vector, and V1 is rotated so that it vertically lines up with V2. Returns doubly nested vector of (min, max).

How it works

The first column of V1 and the first column of V2 decide the first vertical layer of 4x4 cells. If n cells are shaded in V1's column and m cells in V2's, the minimum number of shaded cells in the corresponding 4x4 layer is max(m,n), and the maximum is m * n.

min          |  max
  | 1 0 1 0  |    | 1 0 1 0
-----------  |  -----------
1 | 1 0 0 0  |  1 | 1 0 1 0
1 | 1 0 0 0  |  1 | 1 0 1 0
0 | 0 0 0 0  |  0 | 0 0 0 0
1 | 0 0 1 0  |  1 | 1 0 1 0

Therefore, it suffices to count ones in each column, and evaluate sums of the pairwise max (for minimum) and pairwise product (for maximum) of the column sums.

+.(⌈,×)/+⌿¨
        +⌿¨  ⍝ In each matrix, evaluate column sums
       /     ⍝ Over the two vectors,
+. ⌈         ⍝ Evaluate the sum of pairwise max
    ,        ⍝ and
+.   ×       ⍝ the sum of pairwise product


Parity of Nth Term in Fibonacci Integer Sequences If you look at the Fibonacci Numbers, you will notice a pattern in their parity: 0, 1 , 1 , 2 , 3 , 5 , 8 , 13 , 21 , 34 , 55 , 89 , 144. Every third number is even, and all the others are odd. This makes sense because an even plus an odd is odd, but an odd plus an odd is even and the sum for a term will always include at least one even number unless the last two terms were odd, which happens every three terms.
In this challenge you will have to look at a generalization of this problem.
Specs

You will be given as input two positive integers describing the Fibonacci integer sequence you will have to look at.
For example, 0, 1 describes the original Fibonacci numbers, and 2, 1 would be the Lucas numbers. The sequence is calculated with the recurrence relation: x(n+2)=x(n+1)+x(n).
You will also take a positive integer n.
Your code has to output the parity of the nth term of the described Fibonacci integer sequence (0 indexed).
The output format can be any two sane, consistent outputs (e.g. 0 for even and 1 for odd).

Test Cases
(Fibonacci numbers) [0, 1], 4  ->  odd
(Lucas numbers) [2, 1], 9  ->  even
[14, 17], 24  ->  even
[3, 9], 15  ->  odd
[2, 4], 10  ->  even

Python, 29 bytes

lambda a,b,n:[a,b,a+b][n%3]%2

The generalized Fibonacci sequence modulo 2 has cycle length of 3. So, we reduce n mod 3 and take that element of the first three.

31 bytes:
lambda a,b,n:0<a%2*2+b%2!=n%3+1

True for odd, False for even


Draw Translucent Boxes note: the string art might look horrible here because of SE font weirdness :P :(

Given a list of four-tuples representing the corners of rectangles, draw translucent rectangles over each other in that order.

For this challenge, you are required to have the smallest coordinate in the top-left corner and the x-axis increasing to the right and the y-axis increasing downwards.

A four-tuple (x0, y0, x1, y1) or (x0, x1, y0, y1) represents the (x, y) coordinate pairs of the top-left and bottom-right corners of a rectangle (you may choose either of the two formats for rectangles but it must be consistent)

What do I mean by "translucent rectangle"? Well, for this challenge, you will be using the space character and most of the box-drawing characters; specifically, all of the ones used to draw rectangles, including "bold" characters. When a translucent rectangle is drawn, first all thin lines in the space being occupied disappear and all bold lines become thin, and then the rectangle itself is drawn over in bold lines.

For example, if you draw a rectangle in the top-left and then in the bottom-right, it might look something like this:

┏━━━━┓
┃    ┃
┃    ┃
┃ ┏━━╇━━┓
┃ ┃  │  ┃
┗━╉──┘  ┃
  ┃     ┃
  ┃     ┃
  ┗━━━━━┛

To be clear, lines are lightened (bold -> thin -> none) for all lines strictly within the rectangle (for example, downwards facing lines are affected for the top edge but not the bottom edge).

Test Cases

Some number of lines of input will be given, followed by unicode-art, for each test case.

0 0 5 5
5 5 10 10
3 3 7 7
2 2 8 8

┏━━━━┓
┃    ┃
┃ ┏━━╇━━┓
┃ ┃┌─┴─┐┃
┃ ┃│   │┃
┗━╉┤   ├╊━┓
  ┃│   │┃ ┃
  ┃└─┬─┘┃ ┃
  ┗━━╈━━┛ ┃
     ┃    ┃
     ┗━━━━┛

14 5 15 9
13 2 15 16
6 4 15 11

             ┏━┓
             ┃ ┃
      ┏━━━━━━╇━┫
      ┃      │ ┃
      ┃      │ ┃
      ┃      │ ┃
      ┃      │ ┃
      ┃      │ ┃
      ┃      │ ┃
      ┗━━━━━━╈━┫
             ┃ ┃
             ┃ ┃
             ┃ ┃
             ┃ ┃
             ┗━┛

6 8 10 11
15 12 16 16
14 10 16 16
9 1 15 15

         ┏━━━━━┓
         ┃     ┃
         ┃     ┃
         ┃     ┃
         ┃     ┃
         ┃     ┃
         ┃     ┃
      ┏━━╉┐    ┃
      ┃  ┃│    ┃
      ┃  ┃│   ┌╊┓
      ┗━━╉┘   │┃┃
         ┃    │┠┨
         ┃    │┃┃
         ┃    │┃┃
         ┗━━━━╈┩┃
              ┗┷┛

Generate more test cases!

Rules

Input can be in any reasonable format for a list of four-tuples. Input can be one-indexed or zero-indexed along either axis (i.e. the top-left corner can be any of (0, 0), (0, 1), (1, 0), (1, 1).
Output must be as unicode-art as described. Output may not have leading newlines and can have at most one trailing newline (after the last line). Trailing whitespace will be ignored for the purposes of this challenge.

Code-points

The bold and light horizontal and vertical pipes are in the range [U+2500, U+2503]. The various corner pipes are in the range [U+250C, U+251C). The three-armed pipes are in the range [U+251C, U+253C). The four-armed pipes are in the range [U+253C, U+254C). The remaining pipes that can be found in my program are never actually used.

Python 3, 289 286 bytes

l,u=eval(input())
*_,w,h=map(max,zip(*l))
r=[*map(list,[' '*-~w]*-~h)]
R=range
for x,y,X,Y in l:
 for i in R(x,X+1):
  for j in R(y,Y+1):Q=i<X,y<j,x<i,j<Y;r[j][i]=u[sum(3**o*max(Q[o]*[j in(y,Y),i in(x,X)][o%2]*2,u.index(r[j][i])//3**o%3-Q[o])for o in R(4))]
for l in r:print(''.join(l))

Try it online!

Takes input as a list of 4-tuples: (x0, y0, x1, y1), along with the pipedrawing characters as follows: " ╶╺╵└┕╹┖┗╴─╼┘┴┶┚┸┺╸╾━┙┵┷┛┹┻╷┌┍│├┝╿┞┡┐┬┮┤┼┾┦╀╄┑┭┯┥┽┿┩╃╇╻┎┏╽┟┢┃┠┣┒┰┲┧╁╆┨╂╊┓┱┳┪╅╈┫╉╋"

Supports boxes of zero width or height (uses all box drawing chars).

Based on my answer to this question, but modified to alter existing boxes when drawing.

'Ungolfed':

u=" ╶╺╵└┕╹┖┗╴─╼┘┴┶┚┸┺╸╾━┙┵┷┛┹┻╷┌┍│├┝╿┞┡┐┬┮┤┼┾┦╀╄┑┭┯┥┽┿┩╃╇╻┎┏╽┟┢┃┠┣┒┰┲┧╁╆┨╂╊┓┱┳┪╅╈┫╉╋"

#Create array of spaces:
l=eval(input())
w,h=list(map(max,zip(*l)))[2:]
r=[[' ']*w for _ in' '*h]

for x,y,X,Y in l:
 n,m=X-1,Y-1
 for i in range(x,X):
  for j in range(y,Y):
   A,B=j in(y,m),i in(x,n)
   P=(i<n*A,y<j*B,x<i*A,j<m*B)   # Pipe sides of the new box
   Q=(i<n,y<j,x<i,j<m)           # Pipe sides that are inside the new box, and should be thinned.
   # Get new pipe (sides of new box, on top of thinned pipes of existing boxes. (u.index... is existing pipe))
   l=sum(3**o*max(P[o]*2,(u.index(r[j][i])//3**o%3)-Q[o])for o in range(4))
   #Add to 'canvas'
   r[j][i]=u[l]

print('\n'.join(''.join(l)for l in r))


The leading zeroes challenge The challenge

Given two integers as input (x and y), output x as a string with as many leading zeroes necessary for it to be y characters long without the sign.

Rules

If x has more than y digits, output x as string without modification.
Output as integer is not accepted, even if there are no leading zeroes.
When x is negative, keep the - as is and operate on the absolute value.
Negative y should be treated as 0, meaning you output x as is (but as string)

Examples:

IN: (1,1)   OUT: "1"
IN: (1,2)   OUT: "01"
IN: (10,1)  OUT: "10"
IN: (-7,3)  OUT: "-007"
IN: (-1,1)  OUT: "-1"
IN: (10,-1) OUT: "10"
IN: (0,0)   OUT: "0"
IN: (0,1)   OUT: "0"
IN: (0,4)   OUT: "0000"

Shortest code in bytes wins, standard loopholes apply.

Pyth, 12 bytes
%"%0*d",+E>0

Try it here!


Average Idle-Dice Rolling So I ran into this progressive/idle game cleverly called Idle Dice. Has a variety of random effects applied to a pretty typical progression formula game. Warning, time sink! Play at your own risk.

However after you have 5 dice (summed the usual way) along with some bonuses for various matches (pair, two pair, three of a kind, etc), but after that you eventually get multiplier dice. These five dice are all multiplied against the total rolled by the first five dice and multiplicatively combine with each other.

Even later on you get access to a roulette wheel which can (if it lands on the right wedges) "skip 10 minutes." Sometimes longer, but all intervals are some multiple of 10 minutes.

Your task:

Given the multiplier dice I have, how much will I make when I land on the "skip 10 minutes" wedge of the roulette wheel (figuring I can calculate the 20 minute and 1 hour wedges from there)? We'll ignore any upgraded multipliers and focus solely on the flat base values of each die (incremental games, being what they are, get to obscenely large values in a hurry).

Input

Five values in any reasonable format. Each value represents the number of faces of each of the five multiplier dice.

Missing dice can either be explicitly specified (as 0) or left absent, your choice as long as it is made clear how your program accepts it.
You can assume input values of 0, 2, 4, 6, 8, 10, 12, 20, and 100 will be used.
For example an input of [6,6,4,2] would indicate that there are 2 six-sided multiplier dice, 1 four sided, and 1 two sided, while 6 6 4 2 0 would also be acceptable.

How the dice roll

All ten dice are rolled once a second
The five base dice are summed
The sum is multiplied by each of the five multiplier's dice's face value
That total is multiplied by the score bonus (if any)

The dice

The five basic (six sided) dice will be assumed all present.

Score bonus values:

We'll assume the following score multipliers (which apply to the face results of the base 5 dice, not the multiplier dice):

Pair: 2
Triplet: 7
Two-Pair: 5
Four of a Kind: 60
Straight: 20
Full House (pair + triplet): 30
Five of a Kind: 1500

This page has the odds listed out for the likelyhood of any given result, except a straight for some reason, which is 240/7776 (what's called a Large Straight, rather than a Short Straight).

Note: My original test cases were computed using an incorrect value of 2600/7776 odds for a Pair (correct value should be 3600). Given the existing answers, I am not fixing this.

Output:

Compute the expected average total over a 10 minute period (600 rolls) based on the inputs provided, assuming all dice are uniformly distributed. Output need only be accurate to the nearest whole value, but more precision is allowed.

Test cases

Two extra decimal-fractions of precision included for convenience.

[2] -> 111643.52
[4] -> 186072.53
[6] -> 260501.54
[8] -> 334930.56
[10] -> 409359.57
[12] -> 483788.58
[20] -> 781504.63
[100] -> 3758665.12
[2,2,2] -> 251197.92
[4,2,2] -> 418663.19
[6,6,6] -> 3191143.90
[2,2,2,2,2] -> 565195.31
[6,6,6,6,6] -> 39091512.83
[10,8,6,4,2] -> 24177799.48
[100,20,2,2,2] -> 133197695.3
[100,20,12,2,2] -> 577190013.02
[100,20,12,10,8] -> 6349090143.23
[100,100,100,100,100] -> 24445512498226.80

R, 50 32 bytes

function(M)prod(M/2+.5)*691250/9

Try it online!
-17 Bytes thanks to Nick Kennedy, and thanks to Jonathan Allan for suggesting a precision fix, with no byte loss!
Ignores any missing bonus dice. Just a brute force approach.
Works pretty well, but integers get promoted to doubles once we get past the 2-billion mark (2^31-1), leading to a loss of precision.
Because the "regular" and "bonus" dice are independent, \$E[RB]=E[R]E[B]\$, easing the calculations to simply calculating \$E[B]\$ (which is again the prod of the expected values of each die) and scaling by \$E[R]\$, easily calculated from the given test cases.


Compressing the Atomic Ionization Energies This is a different type of compression challenge.  In a normal kolmogorov-complexity challenge, you are required to recreate a list exactly.  Here, you are allowed to round the values in any way you wish.  What's the catch?  Your score is penalized based on how wrong your output is.

At the bottom of this question is a list of the first ionization energies for the first 108 elements.  Your program, upon execution, should output a reasonably accurate copy of this list.  There will be no input or arguments. For scoring purposes your output should be deterministic (same output every time).

Output format

Your program/function must output a list of 108 numbers, sorted in order of increasing atomic number. This list can be in any appropriate format. The source data below is provided in the correct order, from hydrogen to hassium.

Scoring

Your score will be your program's length in bytes plus a rounding penalty.  A rounding penalty is calculated for each element and summed to give the total penalty.

As an example, let's take the number 11.81381. Let's say that your program outputs an incorrect value of 11.81299999.

First, both numbers are multiplied by the same power of 10 such that there is no longer a decimal point in the true value: 1181381, 1181299.999. Trailing zeros in the true value are considered significant.
Then, the absolute difference is taken to determine the absolute error: 81.001.
Finally, we calculate this element's penalty as max(0, log10(err * 4 - 1)) -> 2.50921.  This formula was chosen such that an error < 0.5 gives no penalty (since the answer is correct within rounding), while also giving an asymptotic 50% chance that rounding the number to any particular decimal place would provide a net benefit in score (assuming no other compression).

Here is a Try-It-Online implementation of a penalty-calculating program.  The input to this program is provided as a list of numbers, one per line.  The output of this program is the total penalty and a per-element breakdown of scoring.

Data

The list of numbers below is the target data, in the correct order from atomic number 1 to 108.

Source

13.598434005136
24.587387936
5.391714761
9.322699
8.2980190
11.260296
14.53413
13.618054
17.42282
21.564540
5.1390767
7.646235
5.985768
8.151683
10.486686
10.36001
12.96763
15.7596112
4.34066354
6.11315520
6.56149
6.82812
6.746187
6.76651
7.434018
7.9024678
7.88101
7.639877
7.726380
9.3941990
5.9993018
7.899435
9.7886
9.752392
11.81381
13.9996049
4.177128
5.69486720
6.21726
6.63390
6.75885
7.09243
7.11938
7.36050
7.45890
8.33686
7.576234
8.993822
5.7863552
7.343917
8.608389
9.00966
10.45126
12.1298431
3.893905548
5.211664
5.5769
5.5386
5.473
5.5250
5.582
5.64371
5.670385
6.14980
5.8638
5.93905
6.0215
6.1077
6.18431
6.254159
5.425871
6.825069
7.549571
7.86403
7.83352
8.43823
8.96702
8.95883
9.225553
10.437504
6.1082871
7.4166796
7.285516
8.414
9.31751
10.7485
4.0727409
5.278424
5.380226
6.3067
5.89
6.19405
6.2655
6.0258
5.9738
5.9914
6.1978
6.2817
6.3676
6.50
6.58
6.65
4.90
6.01
6.8
7.8
7.7
7.6

Baselines & Tips

The source data above is 906 bytes, with certain compression tools able to get it to sub-500 bytes. Interesting solutions are those that attempt to perform intelligent rounding, use algebraic formulas, or other techniques to output approximate values in fewer bytes than compression alone. It is difficult, however, to judge these tradeoffs across languages: for some languages compression alone might be optimal, while many other languages might lack compression tools altogether, so I expect a wide variation in score across languages. This is fine, as I'm going by the "competition within languages, not between them" philosophy.

I anticipate that it might be useful to attempt to take advantage of trends in the periodic table.  Below is a graph I found of ionization energies, so that you can see some of these trends.


Create a C program that takes the longest period of time to compile in gcc Create a short C program that takes an absurdly long time to compile with gcc. Entries will be scored by timing the compilation then subtracting the reference program's compile time.

Rules

Any C language feature or gcc extension
gcc 4.2.1

#define a "xxxxxxxxxxx"
#define b a a a a a a a
#define c b b b b b b b
#define d c c c c c c c
#define e d d d d d d d
#define f e e e e e e e
#define g f f f f f f f
#define h g g g g g g g
#define i h h h h h h h
#define j i i i i i i i
z=j;


Find words containing every vowel Your program must find all the words in this wordlist that contain all the vowels (a e i o u y). There are easy ways to do this, but I am looking for the shortest answer. I will take any language, but I'd like to see Bash.

Here is an example (could be much improved):

cat wordlist.txt | grep "a" | grep "e" | grep "i" | grep "o" | grep "u" | grep "y"

Your score is the length of the code.

-5 points for counting all occurrences of the word.

Lowest score wins.

GolfScript, 19 characters
n%{'aeiouy'&,6=},n*

Usage:
golfscript vowels.gs < wordlist.txt

Output:
abstemiously
authoritatively
behaviourally
[...]
uninformatively
unintentionally
unquestionably
unrecognisably

If you also want to output the count at the end you can use
n%{'aeiouy'&,6=},.n*n@,

which is four characters longer.


Evaluate a Dice 10,000 roll Introduction
Dice 10,000 is a dice game which can be played with 6 dice and something to write. Players roll the dice multiple times a turn and gain a score at the end of it. The player who reaches 10,000 point first wins the game. Calculating the score of one roll is your job in this challenge.
Look here for the full rules.
Please note that the rules (especically the scoring) change from region to region since the game is widely known. We use the rules descibed below.
The Challenge
Given a list of six numbers from one to six representing a dice roll, output their score. The score is calculated in the follwing way:

Ones counts 100 points
Fives counts 50 points
Triplets count their number times 100 points. Three twos for example give 200 points. An exception are three ones which count 1000 points.
Six of the same number count like two triplets as described above. So six threes give 600 points. The same goes for the edge case with the ones: Six ones are 2,000 points.
One die can't be used more than once. If a die is part of a triplet, it does not count for other scorings. The fives in a triplet do not count 50 points in addition to the 500 points they give.
Triples are always counted first to maximize the score. So three fives are never counted as 150 points. Four fives are counted as one triplet and one ordinary five which then gives 550 points.

Notes

The input will always contain six numbers from one to six. You will not recieve invalid input.
The numbers can be in any order. You may not assume any specific ordering.

Rules

Input format is up to  you as long as it's not preprocessed.
Function or full program allowed.
Default rules for input/output.
Standard loopholes apply.
This is code-golf, so lowest byte-count wins. Tiebreaker is earlier submission.

Test cases

[1, 2, 3, 4, 5, 6] -> 150
[1, 1, 1, 2, 3, 5] -> 1050
[1, 1, 1, 1, 1, 1] -> 2000
[2, 2, 2, 2, 2, 2] -> 400
[6, 6, 1, 5, 5, 6] -> 800
[2, 3, 4, 6, 2, 4] -> 0
[1, 5, 1, 5, 1, 5] -> 1500
[5, 5, 5, 5, 2, 3] -> 550
[1, 1, 1, 1, 1, 5] -> 1250
[3, 3, 4, 4, 3, 4] -> 700

05AB1E, 34 31 30 bytes
7G¹N¢O3‰N*2LRN1Q+°*X5‚Nå_i¨}OO

Explanation
7G                                  # for N in 1..6
  ¹N¢O                              # count number of occurrences of N in input
      3‰                            # divmod 3
        N*                          # multiply by N
          2LRN1Q+°*                 # multiply by 10, 100 or 1000
                   X5‚Nå_i¨}        # if N is not 1 or 5, scrap the singles
                            OO      # sum all triple and single scores so far
                                    # implicitly display total sum

Try it online


Random passwords vs Common passwords On Github, there is a list of the 10,000 most common passwords.  I've also generated my own list of random passwords.

Your job is to identify the difference between the two lists (with 100% accuracy).

Therefore, your program needs to accept a string, and return:

A truthy value if the password is on the common passwords list
A falsy value if the password is on the random passwords list
Anything you'd like if the password isn't on either

For those that are interested, my program generates passwords between 5-10 characters in length, and each character is either a lowercase letter or a digit.

Note: You should not use these passwords in anything secure. My generation algorithm is not secure at all, and the results are posted online for all to see


Morse code generator in sound Inspired by the Morse code question, and the Twinkle Twinkle little star question, write a program to accept a letter and generate the morse code audio for that letter.


Cat, Quine, Hello World Write a cat program, a quine, and a Hello World in the same language such that when two specific programs of the three are concatenated in a certain order, you get the third program. It does not matter which program is the first, second, and third are as long as all three types are represented once each.
e.g. if \$A\$ is a cat and \$B\$ is a quine then \$AB\$ is Hello World. Alternatively, if \$A\$ is Hello World and \$B\$ is a cat then \$AB\$ is a quine. You only need to make one permutation of the possible 6 work.
For completeness of explanation:

A cat program outputs the input exactly
A quine is a program that outputs its own source code
A hello world program outputs the string "Hello World!"

Rules, Scoring, Formatting

Shortest code wins. Scoring goes by the length of the concatenated program, i.e. the longest of the three.
Standard rules and loopholes apply.
The hello world program and quine might possibly receive input. You must output the appropriate text regardless of what is given as input.
Programs may output a trailing newline.
You can treat all three programs as if they are surrounded by your language's function closure (please specify the name of your implicit argument in this case) or main function boilerplate if that is required for your solution to work. Use the same convention for all three programs. The quine should not contain the boilerplate in this case.

Format the header of your answer like this:

<first type> + <second type> = <third type>, <language>, <score>

or

<language>, <first type> + <second type> = <third type>, <score>

Python 3, Hello World + Quine = Cat, 129 bytes

Hello World:
import os,atexit as a
p=print
a.register(p,"Hello World!")
def print(_):
 p(input())
 os._exit(0)

Quine:
s='s=%r;print(s%%s)';print(s%s)

Cat:
import os,atexit as a
p=print
a.register(p,"Hello World!")
def print(_):
 p(input())
 os._exit(0)
s='s=%r;print(s%%s)';print(s%s)

atexit lets you define cleanup steps that will run when your program exits "normally". In this case, I register the print function (renamed p) with the argument "Hello World!", so it will print that string when the program ends.
I then redefine print to become a cat function. Normally, this would cause the program to print its input and "Hello World!", but os._exit() is an "abnormal" exit that bypasses the cleanup steps.
Now that print has been redefined, the Quine simply calls this cat function and the program abruptly exits. If the Quine doesn't exist, then the program exits normally, printing "Hello World!" in the process.
The final program doesn't work on TIO, but it works for me running Python 3.7.3 on MacOS.


Calculate the square root only using ++ Your task is to calculate the square root of a positive integer without using any mathematical operators to change the number, such as:

Setting a variable (ex. squareRoot = 5)
Addition (A+B)
Subtraction (A-B)
Multiplication (A*B)
Division (A/B)
Square, cube, fourth, etc. roots
Exponents

Comparison operators (such as <, >, ==, etc) are not considered "mathematical operators" for the purposes of this question and are allowed as long as they do not change the value of a variable.

The only operator that you are able to use is ++.  The following exceptions are in place:

If you wish, you may initialize a variable by setting it to 0.
If your language does not include the ++ syntax, you may use an equivalent syntax, such as foo+=1 or foo=foo+1
The square root should be calculated to at least 6 digits beyond the decimal (the hundred-thousands place) and outputted as a whole number of the decimals (ex. if I input 2 it could come out as 14142135624 or 1414213 depending on the rounding).  Rounding up or down is not important.

User-defined functions are not allowed.  In addition, simulating functions with goto is not allowed as well.

I'm interested to see what everyone submits!  Happy coding!

CLARIFICATION

Clarify that number is a positive integer.  You are welcome to make code that would do any number but it is not necessary.

CLARIFICATION #2

Clarify that comparison operators are allowed.

CLARIFICATION #3

Addition, subtraction, multiplication, division, and functions to change numbers are not allowed at all, regardless of whether they are saved to a variable or not.  I'm sorry that this invalidates a couple existing answers, but I meant to define this group of operators with "change the number" in order to prevent troll answers (ex. I just used the sqrt() function, you only prohibited addition, multiplication, division, and subtraction).  Sorry for the confusion.

CLARIFICATION #4

Clarify that we need at least 5 digits.  10 digits caused code to run for a long time.

Python 66

print'%.0f'%reduce(lambda a,b:abs(a)+1e10j,range(-2,input())).real

Output

>>> print'%.0f'%reduce(lambda a,b:abs(a)+1e10j,range(-2,input())).real
121
110000000000
>>> print'%.0f'%reduce(lambda a,b:abs(a)+1e10j,range(-2,input())).real
1000
316227766017

   This solution uses Spiral of Theodorus on a complex plane to achieve the result.


Visualise Bit Weaving The esoteric programming language evil has an interesting operation on byte values which it calls "weaving". It is essentially a permutation of the eight bits of the byte (it doesn't matter which end we start counting from, as the pattern is symmetric):

Bit 0 is moved to bit 2
Bit 1 is moved to bit 0
Bit 2 is moved to bit 4
Bit 3 is moved to bit 1
Bit 4 is moved to bit 6
Bit 5 is moved to bit 3
Bit 6 is moved to bit 7
Bit 7 is moved to bit 5

For convenience, here are two other representations of the permutation. As a cycle:

(02467531)

And as a list of pairs of the mapping:

[[0,2], [1,0], [2,4], [3,1], [4,6], [5,3], [6,7], [7,5]]

Your task is to visualise this permutation, using the box-drawing characters ─, │, ┌, ┐, └, ┘, ┼ (Unicode code points: U+2500, U+2502, U+250C, U+2510, U+2514, U+2518, U+253C). This visualisation should satisfy the following constraints:

The first and last line are exactly:

0 1 2 3 4 5 6 7

Between those, you can use as many lines as you want of up to 15 characters each to fit your box drawing characters (you will need at least 4 lines). The lines should start vertically beneath one of the digits on the first row and end vertically above the corresponding digit on the last row. The eight lines must be connected, and may only cross via ┼ (which is always a crossing, never two turning lines which are touching). The exact paths of the lines are up to you (and finding a particularly golfable layout is the core of this challenge). One valid output would be:

0 1 2 3 4 5 6 7
│ │ └─┼┐│ │ └┐│
└─┼─┐ ││└─┼─┐││
┌─┘ │ ││  │ │││
│ ┌─┼─┘│  │ │││
│ │ │ ┌┼──┘ │││
│ │ │ │└┐ ┌─┼┼┘
│ │ │ │ │ │ │└┐
0 1 2 3 4 5 6 7

However, any other layout that correctly connects the right digits is fine too. Please show your chosen output in your answer.

You may write a program or function and will not take any input. Output the diagram either to STDOUT (or closest alternative) or as a function return value in the form of a string or a list of strings (each representing one line).

Standard code-golf rules apply, so the shortest code (in bytes) wins.

PowerShell v2+, 172 153 148 145 142 131 123 bytes (81 chars)

($a=""+0..7)
$b='┌┘'
"│$b$('┌┼─┘'*3)
└┼┐$('│└─┐'*3)
$b$('└┼─┐'*3)│
│ $($b*6)│"
$a

I golfed the weaving further, eliminating the need for several variables by using inline code blocks. This is probably within a few bytes of optimal.

We start by setting $a equal to the range 0..7 that's been joined together with spaces. This is because the default $ofs (Output Field Separator) for an array is a space, so when the array is stringified with ""+ (with an operator like this, PowerShell will try to implicitly cast the right-hand object as the left-hand object), the result is the range space-separated.

That's encapsulated in parens, which adds the result onto the pipeline. We then setup a one helper variable $b, followed by four lines of output with the appropriate variable in place (split with literal newlines), and using inline code-blocks for repeat sections, followed by $a again. The four lines and $a are also placed on the pipeline, and output is implicit at the end.

PS C:\Tools\Scripts\golfing> .\visualize-bit-weaving.ps1
0 1 2 3 4 5 6 7
│┌┘┌┼─┘┌┼─┘┌┼─┘
└┼┐│└─┐│└─┐│└─┐
┌┘└┼─┐└┼─┐└┼─┐│
│ ┌┘┌┘┌┘┌┘┌┘┌┘│
0 1 2 3 4 5 6 7


Hofstadter Q-sequence Definition

a(1) = 1
a(2) = 1
a(n) = a(n-a(n-1)) + a(n-a(n-2)) for n > 2 where n is an integer

Task

Given positive integer n, generate a(n).

Testcases

n  a(n)
1  1
2  1
3  2
4  3
5  3
6  4
7  5
8  5
9  6
10 6
11 6
12 8
13 8
14 8
15 10
16 9
17 10
18 11
19 11
20 12

Reference

Obligatory OEIS A005185

Haskell, 35 33 bytes

a n|n<3=1|b<-a.(-)n=b(b 1)+b(b 2)

Defines a function a.


Write a radiation-hardened irradiator The task is to write a radiation-hardened irradiator. What do I mean by that, exactly?

An irradiator is a program that, when given a string as input, will output all possible versions of the string with one character removed. For example, given the input Hello, world!, the program should output:

ello, world!
Hllo, world!
Helo, world!
Helo, world!
Hell, world!
Hello world!
Hello,world!
Hello, orld!
Hello, wrld!
Hello, wold!
Hello, word!
Hello, worl!
Hello, world

An irradiator, however, must be protected from its radiation, so the irradiator you write must also survive when put through itself. That is, when any single byte of your program is removed, the program must still function properly.

Test cases

abc -> bc; ac; ab
foo bar -> oo bar:fo bar:fo bar:foobar:foo ar:foo br:foo ba
source -> ource;surce;sorce;souce;soure;sourc;

Specifications

You may take input by any acceptable method by our Standard I/O rules
The output may be either a list of strings or a printed list delimited by a character or group of characters. A trailing delimiter is acceptable
The output may be in any order as long as it contains all of the possible versions
Duplicate entries (such as the two Helo, world!s in the first example) may be filtered out, but this is not necessary
As this is code-golf, the smallest program, in bytes, wins

05AB1E, 29 26 bytes

æIg<ùˆ\æIg<ùˆ\æIg<ùˆ¯¯{Å`s

Try it online!, or try all irradiated versions.

The shortest irradiator I could find is 5 bytes:

æ        # powerset of the input
 Ig      # length of the input
   <     # - 1
    ù    # elements of a with length b

The idea is to repeat that 3 times, then do majority voting:

æIg<ù         # irradiate
     ˆ        # add the result to the global array
      \       # pop (in case the above instruction gets irradiated)
æIg<ùˆ\       # idem
æIg<ùˆ        # no pop, it's okay to dirty the stack at this point
¯             # push global array
 ¯            # and again, so at least one goes through
  {           # sort
   Å          # conveniently ignored by the parser
    `         # dump
     s        # swap
              # and implicitly output

Å is a prefix for 2-byte commands, but there's no Å` command, which is why the Å gets ignored. We'll need it later, though.

Sorting makes sure the majority vote is in the middle of the array. Dumping then swapping gets that value to the top of the stack.

Any irradiation in the initial part only results in an error in the global array, which gets solved by the majority vote. Irradiations in the final {Å`s bit are much trickier to reason about:

Å is ignored anyway, so it's okay to irradiate it
If the backtick is irradiated, Å`s becomes Ås, which is the "get middle of the array" extended command.
If { or s are irradiated, that means nothing else is, so the global array is the same value three times. In that case we don't need sorting/swapping, any value will work.


Is my triangle right? Given a, b, c the length of the three sides of a triangle, say if the triangle is right-angled (i.e. has one angle equal to 90 degrees) or not.
Input
Three positive integer values in any order
Output
Either a specific true output (true, 1, yes, ...) or a specific false output (false, 0, no, ...)
Example
5, 3, 4        --> yes
3, 5, 4        --> yes
12, 37, 35     --> yes
21, 38, 50     --> no
210, 308, 250  --> no

Rules

The input and output can be given in any convenient format.
In your submission, please state the true and the false values.
No need to handle negative values or invalid edge triple
Either a full program or a function are acceptable. If a function, you can return the output rather than printing it.
If possible, please include a link to an online testing environment so other people can try out your code!
Standard loopholes are forbidden.
This is code-golf so all usual golfing rules apply, and the shortest code (in bytes) wins.

Jelly, 5 bytes

²µSHe

Try it online!

Technical note: Bytes are counted in Jelly codepage.

Explanation:

²µSHe  Main link.
²      Square each number.
 µ     With the new list,
  S    calculate its sum,
   H   and halve it.
    e  Check if the result exists in the new list (squared input)

The problem is equivalent to being given three numbers a, b, c, and asking if there is a permutation such that a² + b² = c². This is equivalent to whether (a² + b² + c²) ÷ 2 is one of a², b² or c², so the program just checks that.


Show me the nearest demon A demonic number is a positive integer whose decimal representation consists of only 6. The list of demonic numbers starts with 6, 66, 666, 6666.

Given a positive integer, output the nearest demonic number. If there are two, output the bigger one.

Testcases:

n   output
1   6
2   6
3   6
6   6
35  6
36  66
37  66
100 66
365 66
366 666
666 666
999 666

This is code-golf. Shortest answer in bytes wins.

Python 2, 28 bytes

lambda n:'6'*len(`-~n*3/11`)


Determine the Sharpness of a Word Overview

The sharpness of a word is the sum of the sharpness of each of its letters, using the following rules:

Sharp letters

A, and V each have a sharpness of 1
N and Z each have a sharpness of 2
M and W each have a sharpness of 3

Dull letters

C and U each have a sharpness of -1
S has a sharpness of -2
O has a sharpness of -3

All other letters have a sharpness of 0.

Example

The word SAUCE has a sharpness of -3 since the A contributes 1, the U and C each contribute -1 and the S contributes -2.

The word MAZE has a sharpness of 6 since the M contributes 3, the Z contributes 2, and the A contributes 1.

Task

Given as input a string containing only uppercase letters*, determine the sharpness of that string.

*If you wish, you may instead take the input as a string containing only lowercase letters. Other common input formats are also acceptable (eg. a list of characters, a list of codepoints, etc.)

Scoring

This is code-golf!

Test Cases

CODE => -4
GOLF => -3
SAUCE => -3
CATS => -2
MOON => -1
NONSENSE => -1
ZUCKERBERG => 0
STRING => 0
CHALLENGE => 2
NAIL => 3
CARNIVAL => 4
COMPLIMENT => 4
WAVE => 5
UNKNOWN => 5
MAZE => 6

Extra test cases (Provided by @Surculose Sputum)

MIZZENMASTMAN => 17
PNEUMONOULTRAMICROSCOPICSILICOVOLCANOCONIOSIS => -26
MANAGEMENT => 12
CONSCIOUSNESS => -13

Python 2, 53 bytes

lambda s:sum(3-"MWCUNZS_AVO".find(c)/2*4%7for c in s)

Try it online!


Draw Recamán's sequence with ASCII Recamán's sequence (A005132) is a mathematical sequence, defined as such:

$$A(n) = \begin{cases}0 & \textrm{if } n = 0 \\
A(n-1) - n & \textrm{if } A(n-1) - n \textrm{ is positive and not already in the sequence} \\
% Seems more readable than
%A(n-1) - n & \textrm{if } A(n-1) > n \wedge \not\exists m < n: A(m) = A(n-1)-n \\
A(n-1) + n & \textrm{otherwise}
\end{cases}$$

An alternative, simpler verbal explanation is as follows:

  Subtract unless you can't (the number is negative, or has been used before), in which case add.

The first few terms are \$0, 1, 3, 6, 2, 7, 13, 20, 12, 21, 11\$

Now, there is already this challenge which asks you to generate the nth term of the sequence. This one is slightly different.

Challenge

Given a number n, draw the first n terms of the sequence. What do I mean by 'draw'? Let me demonstrate:

Draw a number line max([A(y) for y<=n]) units long. We'll assume n is 5, for now, so the number line is 6 units long (since the largest of \$A(1) = 0\$, \$A(2) = 1\$, \$A(3) = 3\$, \$A(4) = 6\$ and \$A(5) = 2\$ is \$6\$). Make the line from underscores, starting at 0:

______

Start with the transition between the first and second terms: that is, 0 and 1. Use | and - to draw a square (equal length and height), going upwards. In this case, we'll have to miss out the - because the distance is only 1.

||
______

Now, we'll draw on the next step (\$A(2) = 1\$ to \$A(3) = 3\$) on the bottom of the line (we alternate between up and down each time):

||
______
 | |
 |-|

As you can see, this line also has a height of 2, since the height must be equal to the distance between the two terms.

If we continue, we will eventually get to:

   |--|
   |  |
|| |  |
______
 |||  |
 |||  |
  |   |
  |---|

Rules

If there is a - and | colliding, the later one takes priority.
There may be preceeding/trailing spaces before/after the image, but trailing/preceeding _s or -s are not allowed (exception is 0- or 1- indexing)
You can choose to set the 0 point just before the first _ on the number line, or just after it.
No alternative characters for -, | or _ may be used.
This is code-golf, so shortest answer in bytes wins.

Test case

Here is another test case, with n=10

            |-------|
            ||-----||
            ||     ||
  |----|    ||     ||
  |    |    ||     ||
  ||--||    ||     ||
  ||  ||    ||     ||
||||  ||    ||     ||
_____________________
 |||  ||   |||     ||
 |||  ||   |||     ||
  |   ||   |||     ||
  |---||   |||     ||
       |   |||     ||
       |---|||     ||
           ||------||
           |--------|

Jelly, 70 65 bytes

µ_ż+ɗLṪ>Ƈ-ḟ⁸Ḣṭµ¡µL;ⱮṀ’ṭr,;ɗƝJW,RN¹ƭƲ€$+Lp""ƲZẎ€Ʋ‘ŒṬ×"J$»/ị“-|_ ”Y

Try it online!

A full program taking a single integer \$n\$ via STDIN and outputting the ASCII art based on zero-indexing.


Convert to Roman Numeral! Your task is to convert a given positive integer from Arabic numeral to Roman numeral.

Things get difficult when you count to 4000.

The romans did this by adding a line above a symbol to multiply that symbol by 1 000. However, overlines aren't exactly displayable in ASCII. Also, there are double overlines to multiply a symbol by 1 000 000, and then triple overline to multiply a symbol by 1 000 000 000, etc...

Therefore, I decided to use parentheses to replace overlines.

The symbols can be individually placed in parentheses. For example, both (VI) and (V)(I) are valid representations of 6 000. (V)M is also a valid representation of 6000.

(I) is a valid way to represent 1 000.

Testcases

Input: 1
Output: I
Input: 2
Output: II
Input: 3
Output: III
Input: 4
Output: IV
Input: 15
Output: XV
Input: 40
Output: XL
Input: 60
Output: LX
Input: 67
Output: LXVII
Input: 400
Output: CD
Input: 666
Output: DCLXVI
Input: 3000
Output: MMM
Input: 3999
Output: MMMCMXCIX
Input: 4000
Output: M(V)
Input: 4999
Output: M(V)CMXCIX
Input: 6000
Output: (VI)
Input: 6000000
Output: ((VI))
Input: 6006000
Output: ((VI)VI)
Input: 6666666666
Output: (((VI)DCLXVI)DCLXVI)DCLXVI

Scoring

This is code-golf. Shortest code in bytes win.

Mathematica, 67 bytes

Fold["("<>#<>")"<>#2&,RomanNumeral[#~IntegerDigits~1000]/."N"->""]&

Avoids all trouble with M by converting the input to base 1000 and converting each digit separately with RomanNumeral. Then we fold them up by inserting (...) from the left.

Unfortunately, Mathematica represents zeros as N so we need to get rid of those.


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

I'm aware Scheme and Racket (formerly PLT Scheme) are technically different languages but are quite similar in many ways and much code (I suspect) will run mostly as intended in either. If your tip only applies to one of the aforementioned languages, note as such.

In Racket, λ and lambda are synonymous keywords for constructing anonymous functions, but λ is 2 bytes where lambda is 6.

In Scheme, there's no such keyword λ and you're stuck with lambda.


Greatest Common Divisor Your task is to compute the greatest common divisor (GCD) of two given integers in as few bytes of code as possible.

You may write a program or function, taking input and returning output via any of our accepted standard methods (including STDIN/STDOUT, function parameters/return values, command-line arguments, etc.).

Input will be two non-negative integers. You should be able to handle either the full range supported by your language's default integer type, or the range [0,255], whichever is greater. You are guaranteed that at least one of the inputs will be non-zero.

You are not allowed to use built-ins that compute either the GCD or the LCM (least common multiple).

Standard code-golf rules apply.

Test Cases

0 2     => 2
6 0     => 6
30 42   => 6
15 14   => 1
7 7     => 7
69 25   => 1
21 12   => 3
169 123 => 1
20 142  => 2
101 202 => 101

Retina, 16
^(.+)\1* \1+$
$1

This doesn't use Euclid's algorithm at all - instead it finds the GCD using regex matching groups.
Try it online. - This example calculates GCD(8,12).
Input as 2 space-separated integers.  Note that the I/O is in unary.  If that is not acceptable, then we can do this:
Retina, 30
\d+
$*
^(.+)\1* \1+$
$1
1+
$.&

Try it online.
As @MartinBüttner points out, this falls apart for large numbers (as is generally the case for anything unary).  At very a minimum, an input of INT_MAX will require allocation of a 2GB string.


Shortest POSIX command line that eagerly removes dual newline sequences Example:

echo -ne 'a\n\nb\nc\n\n\n\nd\n\n\n' | your-command

should output the same as

echo -ne 'ab\ncd\n'

Watch out, some POSIX tools have implementations that diverge from the standard. Please consult https://pubs.opengroup.org/onlinepubs/9699919799/idx/utilities.html before submitting your solutions.

Bash, 32 bytes

awk 'BEGIN{RS="\n\n";ORS="";} 1'

Try it online!


substring conversion (in Haskell). Can you beat this? Ok, I found myself with a nice little problem:

you will get from stdin a string. In this string you will find some hex colors (like #ff00dd). You must return the string with the colors inverted (#ff00dd inverted is #00ff11).

A sample input/output could be:

ascscasad #ff00ff csdcas dcs c#001122 #qq5500
ascscasad #00ff00 csdcas dcs c#ffeedd #qq5500

As I am proficient in Haskell, I tackled the problem with it. Came up with this code, and I think it's the best I can do. Do you see any way to improve it / a completely different way to make it shorter?

import Text.Regex.Posix ( (=~) )

main = getLine >>= putStrLn . f

f [] = []
f x = let (b, q, p) = x =~ "#[0-f]{6}"
          c = '#' : ['0'..'f'] ++ "#"
          a = zip c (reverse c)
          r = map ( (maybe '@' id) . (flip lookup $ a) ) q
      in b ++ r ++ f p

I am also interested to compare other languages to Haskell, so post in other languages are welcome, too!

Perl, 44 chars

Two different tweaks can get it to this length, one suggested by Primo:

s/#\K[\da-f]{6}/sprintf"%06x",~hex ff.$&/eg

Another one by playing around with the /ee modifier:

s/#\K[\da-f]{6}/"sprintf'%06x',~0xff$&"/eeg

Requires -p command line switch (1 char included in count).

Works for lower-case hex numbers (as in example).  An i switch added to the regex would make it work for upper-case as well (though not preserving the case of the original number).


Underhanded Password Hashing In the spirit of the Underhanded C Contest, I'm starting an Underhanded Code Contest.  The objective of this contest is to straightforwardly implement some code, while subtly hiding a nefarious bug inside it.

The contest

You are a secret Russian mole working in the IT department of an American spy agency.  Your American boss has just asked you to implement a password hashing algorithm to use for encrypting secret messages.

Your boss wants you to implement the following function:

f: String -> byte[16]

which converts a password to a 16-byte quantity suitable for use as an AES key.  Your boss wants a secure function, which in this context means that different password strings should generate different results with overwhelming probability.  For instance, returning the md5 hash of the input would be a simple implementation of f.

Of course, your real boss in the Russian spy agency would want you to subvert this process.  Your task is to implement f such that the Russians can decrypt all the secret messages encrypted using keys returned by f.

To do so, you must implement f so that it returns only a small subset of the 2^128 possible outputs.  In particular, your f must return at most 2^16 different results so that the Russians can do an easy brute-force search for the correct key for each encrypted message they wish to decrypt.

Keep in mind, however, that espionage carries the death penalty.  In order not to get caught, your function f must generate at least 2^8 different results, so that a cursory inspection of a few outputs of f is unlikely to reveal a duplicate.  And most importantly, the code you introduce to limit the range of f must look unintentional, not deliberate.  If you ever get hauled into a courtroom, there must be some reasonable doubt as to whether you introduced the bug deliberately or by accident.

Judging

I and two others I recruit will judge the entries (email me if you'd like to judge).  I'm offering a 200 reputation bounty for the winning entry.  Submissions must be uploaded by May 1.

Judging will take into account the following criteria:

Does f adhere to the spec, i.e. does it generate between 2^8 and 2^16 possible outputs.  Don't feel that these are hard limits, but we'll deduct points if you're too far out of range.
Is the bug plausibly the result of an unintentional mistake?
Do the outputs of f look random?
The shorter your implementation of f, the better.
The clearer your implementation of f, the better.

Notes

You may use any language to implement your code.  You're trying to hide a bug in plain sight, so obfuscated code is not suggested.

You might want to take a look at some of the previous Underhanded C contest winners to get a feel for what makes a good submission.

Input strings will be printable ascii (32 through 126, inclusive).  You may assume a reasonable max length if you want.

C

2^16 possible outputs (or 2^8 times the number of used characters).
Uses Linux's MD5 implementation, which is, AFAIK, fine. But this gives the same hash, for example, for "40" and "42".
EDIT: Renamed bcopy to memcpy (swapped parameters of course).
EDIT: Converted from program to function, to meet requirements better.

#include <string.h>
#include <openssl/md5.h>

void f(const unsigned char *input, unsigned char output[16]) {

    /* Put the input in a 32-byte buffer, padded with zeros. */
    unsigned char workbuf[32] = {0};
    strncpy(workbuf, input, sizeof(workbuf));

    unsigned char res[MD5_DIGEST_LENGTH];
    MD5(workbuf, sizeof(workbuf), res);

    /* NOTE: MD5 has known weaknesses, so using it isn't 100% secure.
     * To compensate, prefix the input buffer with its own MD5, and hash again. */
    memcpy(workbuf+1, workbuf, sizeof(workbuf)-1);
    workbuf[0] = res[0];
    MD5(workbuf, sizeof(workbuf), res);

    /* Copy the result to the output buffer */
    memcpy(output, res, 16);
}

/* Some operating systems don't have memcpy(), so include a simple implementation */
void *
memcpy(void *_dest, const void *_src, size_t n)
{
    const unsigned char *src = _src;
    unsigned char *dest = _dest;
    while (n--) *dest++ = *src++;
    return _dest;
}


Code golf a random orthogonal matrix An orthogonal matrix is a square matrix with real entries whose columns and rows are orthogonal unit vectors (i.e., orthonormal vectors).

This means that M^T M = I, where I is the identity matrix and ^T signifies matrix transposition.

Note that this is orthogonal not "special orthogonal" so the determinant of M can be 1 or -1.

The aim of this challenge is not  machine precision so if M^T M = I to within 4 decimal places that will be fine.

The task is to write code that takes a positive integer n > 1 and outputs a random orthogonal n by n matrix.  The matrix should be randomly and uniformly chosen from all  n by n orthogonal matrices.   In this context, "uniform" is defined in terms of the Haar measure, which essentially requires that the distribution does not change if multiplied by any freely chosen orthogonal matrix.  This means the values of the matrix will be floating point values in the range -1 to 1.

The input and output can be any form you find convenient.

Please show an explicit example of your code running.

You may not use any existing library function which creates orthogonal matrices. This rule is a little subtle so I  will explain more. This rule bans the use of any existing function which takes in some (or no) input and outputs a matrix of size at least n by n which is guaranteed to be orthogonal.  As an extreme example, if you want the n by n identity matrix, you will have to create it yourself.

You can use any standard random number generator library for choosing random numbers of your choosing.

Your code should complete within at most a few seconds for n < 50.

Haskell, 169 150 148 141 132 131 bytes

import Numeric.LinearAlgebra
z=(unitary.flatten<$>).randn 1
r 1=asRow<$>z 1
r n=do;m<-r$n-1;(<>diagBlock[m,1]).haussholder 2<$>z n

Recursively extend an orthogonal matrix of size n-1 by adding 1 to lower right corner and apply a random Householder reflection. randn gives a matrix with random values from a gaussian distribution and z d gives a uniformly distributed unit vector in d dimensions.

haussholder tau v returns the matrix I - tau*v*vᵀ which isn't orthogonal when v isn't a unit vector.

Usage:

*Main> m <- r 5
*Main> disp 5 m
5x5
-0.24045  -0.17761   0.01603  -0.83299  -0.46531
-0.94274   0.12031   0.00566   0.29741  -0.09098
-0.02069   0.30417  -0.93612  -0.13759   0.10865
 0.02155  -0.83065  -0.35109   0.32365  -0.28556
-0.22919  -0.41411   0.01141  -0.30659   0.82575
*Main> (<1e-14) . maxElement . abs $ tr m <> m - ident 5
True


Number of solutions to a binary weight equation We define \$a(n)\$ as the 1-indexed position of \$n\$ in the sequence of positive integers with the same binary weight, i.e. the same number of 1's in their binary representation. This is A263017.
Given a positive integer \$n\$, your task is to determine how many positive integers \$k\$ satisfy:
$$k-a(k)=n$$
For instance, \$n=6\$ can be expressed as:

\$n=7-a(7)=7-1\$ (\$7\$ being the 1st integer with 3 bits set)
\$n=12-a(12)=12-6\$ (\$12\$ being the 6th integer with 2 bits set)

There's no other \$k\$ such that \$k-a(k)=6\$. So the expected answer is \$2\$.
This is code-golf.
Test cases
Input Output
1     1
6     2
7     0
25    4
43    0
62    1
103   5
1000  0
1012  6
2000  1
3705  7
4377  8

Or as lists:
Input : [1, 6, 7, 25, 43, 62, 103, 1000, 1012, 2000, 3705, 4377]
Output: [1, 2, 0, 4, 0, 1, 5, 0, 6, 1, 7, 8]

MATL, 15 bytes

t4*:tB!s&=Rs-=s

Try it online! Or verify all test cases.

This makes use of the following result:

Claim

\$a(n) \le 3n/4\$ for \$n \geq 3\$.

Here is a graphical illustration. The bound is quite loose, but it is sufficient to establish that only a finite number of values of \$k\$ need to be tested for a given \$n\$ (more on that in “How the code works”).

Proof

The sequence \$a(n)\$ (A263017) is the amount of numbers in the set \$\{1,2,\ldots,n\}\$ that have the same binary weight as \$n\$. The binary expansion of \$n\$ has \$b \leq \log_2 n + 1\$ digits, with a leading 1. Let \$w\$ be the binary weight of \$n\$. Clearly \$w \in \{0,\ldots,b\}\$.

The number of unique permutations of the binary expansion of \$n\$, not necessarily with a leading 1, is \${b\choose w}\$. \$a(n)\$ will be at most equal to this value. It can be less, because some of the permutations may produce a number exceeding \$n\$. Thus,

$$
a(n) \leq {b\choose w}.
$$

For \$b\$ even, the bound

$$
{2m \choose m} \leq \frac{4^m}{\sqrt{3m+1}} \text{ for all } m \geq 1
$$

and the fact that \${b\choose w} \leq {b\choose b/2}\$ imply that

$$
{b \choose w} \leq \frac{2^b}{\sqrt{\frac{3b+2}{2}}}.
$$

For \$b\$ not necessarily even, the bound holds with \$b\$ replaced by \$b+1\$:

$$
{b \choose w} \leq \frac{2^{b+1}}{\sqrt{\frac{3b+5}{2}}}.
$$

Since \$b \leq \log_2 n + 1\$,

$$
a(n) \leq {b\choose w} \leq \frac{2^{b+1}}{\sqrt{\frac{3b+5}{2}}} \leq \frac{4n}{\sqrt{ 3/2 \cdot \log_2 n + 4}}.
$$

This is less than \$3n/4\$ for \$n \geq 80478\$, because

$$
\sqrt{3/2 \cdot \log_2 80478 + 4}\ = 5.3333348 > 16/3.
$$

For \$n = 3, \ldots, 80477 \$, direct computation of \$a(n)\$ shows that \$a(n) \leq 3n/4\$. Therefore \$a(n) \leq 3n/4\$ for \$n \geq 3\$.

How the code works

The above result implies that

$$
k-a(k) \geq k / 4.
$$

for all \$k \geq 3\$. Thus, given \$n\$, to compute the number of positive integers \$k\$ that satisfy

$$
k-a(k)\ = n
$$

it suffices to test the latter equality for \$k = 1, \ldots, 4n\$.

Consider input 1 as an example.

t4*  % Implicit input: n. Duplicate. Multiply by 4
     % STACK: 1, 4
:    % Range. Gives [1 2 ... 4*n]. This is the vector of k values
     % STACK: 1, [1 2 3 4]
tB   % Duplicate. Binary expansion. Gives a binary matrix, where each row
     % corresponds to a value of k
     % STACK: 1, [1 2 3 4], [0 0 1;
                             0 1 0;
                             0 1 1;
                             1 0 0]
!s   % Tranpose. Sum of each column. This gives the binary weights
     % STACK: 1, [1 2 3 4], [1 1 2 1]
&=   % Matrix of pair-wise equality comparisons
     % STACK: 1, [1 2 3 4], [1 1 0 1;
                             1 1 0 1;
                             0 0 1 0;
                             1 1 0 1]
R    % Upper triangular part. This sets elements below the diagonal to 0
     % STACK: 1, [1 2 3 4], [1 1 0 1;
                             0 1 0 1;
                             0 0 1 0;
                             0 0 0 1]
s    % Sum of each column. For each column k, this gives the amount of
     % number up to k with the same weight as k; that is, a(k). Note that
     % the condition "up to k" corresponds to having taken the upper
     % triangular part of the matrix
     % STACK: 1, [1 2 3 4], [1 2 1 3]
-    % Subtract, element-wise. This gives k-a(k)
     % STACK: 1, [0 0 2 1]
=    % Equality comparison, element-wise. This compares n with each
     % value k-a(k)
     % STACK: [0 0 0 1]
s    % Sum. Implicit display
     % STACK: 1


I'm walking around manhattan, how far am I from my hotel? The unnecessary and convoluted story

I am walking around manhattan, block by block and my feet have gotten tired and want to go back home.

The traffic is pretty bad, but fortunately I'm very rich and I have a helicopter on standby at the hotel. But I need them to know how much fuel to pack for the flight and for that they need to know my direct distance from the hotel. I did remember which blocks I walked and can tell them what route I took. This distance needs to be precise though, if they are too short we won't make it back, too long and I've bought fuel I can't use.

Can you write me a program to convert that into the distance they will have to travel on their flight to fetch me?

Specification:

Write me a function that:

Accepts a list or string of blocks walked relative to an arbitrary grid:

U p, D own, L eft and R ight.
Can be either upper or lower case - eg. if its shorter to use u instead of U go ahead.
An invalid direction has undefined behaviour - eg. a direction of X can cause a failure.

Returns a float/decimal/double that is twice the straight line distance from the point of origin.

For illustration and clarification:

My trip could have just as easily been recorded as "luluu..." or ['l','u','l'...] but it must be recorded as Up, Down, Left, Right.

J, 17 characters
2*|+/0j1^'urdl'i.

Uses the fact, that the powers of j represent the proper directions.

'urdl'i. take string and calculate indices (0 for 'u', 1 for 'r', ...)
0j1^ transforms into the direction in the complex plane using the corresponding power of j.
+/ sums up the single steps
2*| two times the modulus

Example:
> 2*|+/0j1^'urdl'i.'uuuudrrrl'
7.2111