Underhanded code contest: Not-so-quick sort The Task

Write a program, in the language of your choice, that reads lines of input from standard input until EOF, and then writes them to standard output in ASCIIbetical order, similar to the sort command-line program.  A short, non-underhanded example in Python is:

import sys

for line in sorted(sys.stdin):
    print(line.rstrip('\n'))

The underhanded part

Similar to The OS War, your goal is to prove that your favored platform is “better”, by having your program deliberately run much more slowly on a competing platform.  For the sake of this contest, a “platform” consists of any combination of:

Processor

Architecture (x86, Alpha, ARM, MIPS, PowerPC, etc.)
Bitness (64-bit vs. 32-bit vs. 16-bit)
Big- versus little-endian

Operating System

Windows vs. Linux vs. Mac OS, etc.
Different versions of the same operating system

Language implementation

Different compiler/interpreter vendors (e.g., MSVC++ vs. GCC)
Different versions of the same compiler/interpreter

Although you could meet the requirements by writing code like:

#ifndef _WIN32
    Sleep(1000);
#endif

Such an answer should not be upvoted.  The goal is to be subtle.  Ideally, your code should look like it's not platform-dependent at all.  If you do have any #ifdef statements (or conditions based on os.name or System.Environment.OSVersion or whatever), they should have a plausible justification (based on a lie, of course).

Include in your answer

The code
Your “favorite” and “unfavorite” platforms.
An input with which to test your program.
The running time on each platform, for the same input.
A description of why the program runs so slowly on the unfavorite platform.

C

CleverSort

CleverSort is a state-of-the-art (i. e. over-engineered and sub-optimal) two-step string sorting algorithm.

In step 1, it starts by pre-sorting the input lines using radix sort and the first two bytes of each line. Radix sort is non-comparative and works very well for strings.

In step 2, it uses insertion sort on the pre-sorted list of strings. Since the list is almost sorted after step 1, insertion sort is quite efficient for this task.

Code

#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// Convert first two bytes of Nth line into integer

#define FIRSTSHORT(N) *((uint16_t *) input[N])

int main()
{
    char **input = 0, **output, *ptemp;
    int first_index[65536], i, j, lines = 0, occurrences[65536];
    size_t temp;

    // Read lines from STDIN

    while(1)
    {
        if(lines % 1000 == 0)
            input = realloc(input, 1000 * (lines / 1000 + 1) * sizeof(char*));

        if(getline(&input[lines], &temp, stdin) != -1)
            lines++;
        else
            break;
    }

    output = malloc(lines * sizeof(char*));

    // Radix sort

    memset(occurrences, 0, 65536 * sizeof(int));

    for(i = 0; i < lines; i++) occurrences[FIRSTSHORT(i)]++;

    first_index[0] = 0;

    for(i = 0; i < 65536 - 1; i++)
        first_index[i + 1] = first_index[i] + occurrences[i];

    memset(occurrences, 0, 65536 * sizeof(int));

    for(i = 0; i < lines; i++)
    {
        temp = FIRSTSHORT(i), output[first_index[temp] + occurrences[temp]++] = input[i];
    }

    // Insertion sort

    for(i = 1; i < lines; i++)
    {
        j = i;

        while(j > 0 && strcmp(output[j - 1], output[j]) > 0)
            ptemp = output[j - 1], output[j - 1] = output[j], output[j] = ptemp, j--;
    }

    // Write sorted lines to STDOUT

    for(i = 0; i < lines; i++)
        printf("%s", output[i]);
}

Platforms

We all know that big-endian machines are much more efficient than their little-endian counterparts. For benchmarking, we'll compile CleverSort with optimizations turned on and create randomly a huge list (just over 100,000 strings) of 4-byte lines:

$ gcc -o cleversort -Ofast cleversort.c
$ head -c 300000 /dev/zero | openssl enc -aes-256-cbc -k '' | base64 -w 4 > input
$ wc -l input
100011 input

Big-endian benchmark

$ time ./cleversort < input > /dev/null

real    0m0.185s
user    0m0.181s
sys     0m0.003s

Not too shabby.

Little-endian bechmark

$ time ./cleversort < input > /dev/null

real    0m27.598s
user    0m27.559s
sys     0m0.003s

Boo, little Endian! Boo!

Description

Insertion sort is really rather efficient for almost-sorted lists, but it is horribly inefficient for randomly sorted ones.

CleverSort's underhanded part is the FIRSTSHORT macro:

#define FIRSTSHORT(N) *((uint16_t *) input[N])

On big-endian machines, ordering a string of two 8-bit integers lexicographically or converting them to 16-bit integers and ordering them afterwards yields the same results.

Naturally, this is possible on little-endian machines as well, but the macro should have been

#define FIRSTSHORT(N) (input[N][0] | (input[N][1] >> 8))

which works as expected on all platforms.

The "big-endian benchmark" above is actually the result of using the proper macro.

With the wrong macro and a little-endian machine, the list is pre-sorted by the second character of every line, resulting in a random ordering from the lexicographical point of view. Insertion sort behaves very poorly in this case.


Print the Oscars Best Picture Winner This challenge is in tribute to the winner of Best Picture at the Oscars 2017, La La Land Moonlight!

Your challenge is to print the text La La Land pause one second, then change the text to show

La La Land MoonlightThe original text (La La Land) must have a strikethrough. This can be achieved either by clearing the screen, drawing on top of the original text, or by any other clever solutions.

This is a code-golf so lowest bytes wins. Standard code-golf rules apply.

Vim, 37 bytes
3iLa <esc>snd<esc>gs:s/./&<C-v>u336/g
A Moonlight

A fairly straightforward solution.
Here is an animation of it running:


Computing the entropy Input
A matrix M represented as two space separated lines of integers. Each line will have the same number of integers and each integer will be either -1 or 1.  The number of integers per line will be at most 20.  M will therefore be 2 by n where n is the number of integers on each of the two lines.
Your code should be a complete program. and accept the input either on standard in or from a file (that is your choice). You can accept input from standard in, from a file or simply as a parameter. However, if you do the latter please give an explicit example of how your code should work and remember that it must be a complete program and how the matrix M will be represented in the input. In other words, you are likely to have to do some parsing.
Output
The binary Shannon entropy of the distribution of M*x where the elements of x are uniformly and independently chosen from {-1,1}.   x is an n-dimensional column vector.
The entropy of a discrete probability distribution is
- sum p_i log_2(p_i)

In this case, p_i is the probability of the ith unique possible M*x.
Example and helpful hints
As a worked example, let the matrix M be
-1 1
-1 -1

Now look at all 2^2 different possible vectors x. For each one we compute M*x and put all the results in an array (a 4-element array of 2-component vectors). Although for each of the 4 vectors the probability of it occurring is 1/2^2 = 1/4, we are only interested in the number of times each unique resultant vector M*x occurs, and so we sum up the individual probabilities of the configurations leading to the same unique vectors. In other words, the possible unique M*x vectors describe the outcomes of the distribution we're investigating, and we have to determine the probability of each of these outcomes (which will, by construction, always be an integer multiple of 1/2^2, or 1/2^n in general) to compute the entropy.
In the general n case, depending on M the possible outcomes of M*x can range from "all different" (in this case we have n values of i in p_i, and each p_i is equal to 1/2^n), to "all the same" (in this case there is a single possible outcome, and p_1 = 1).
Specifically, for the above 2x2 matrix M we can find by multiplying it with the four possible configurations ([+-1; +-1]), that each resulting vector is different. So in this case there are four outcomes, and consequently p_1 = p_2 = p_3 = p_4 = 1/2^2 = 1/4.  Recalling that log_2(1/4) = -2 we have:
- sum p_i log_2(p_i) = -(4*(-2)/4) = 2

So the final output for this matrix is 2.
Test cases
Input:
-1 -1
-1 -1

Output:
1.5

Input:
-1 -1 -1 -1
-1 -1 -1 -1

Output:
2.03063906223

Input:
-1  -1  -1  1
1  -1  -1  -1

Output:
3

Mathematica, 48 68 bytes

Edit: Preprocess is added for accepting string as the parameter.

With the help of Tuples and Entropy, the implementation is both concise and readable.

Entropy[2,{-1,1}~Tuples~Length@#.#]&@Thread@ImportString[#,"Table"]&

where Tuples[{-1,1},n] gives all possible n-tuples from {-1,1}, and Entropy[2,list] gives the base-2 information entropy.

One of the cool things is that Mathematica will actually return an accurate expression:

%["-1 -1 \n -1 -1"]
(* 3/2 *)

Approximate result can be achieved with an extra . added (Entropy[2., ...).


Remove duplicates from list and order it by count? (python 3) How do I remove all duplicates from list and order it based on count?
s = ["foo", "this", "lem", "foo", "lem"]
s = ["foo", "ebh", "wosv", "wosv", "ebh", "4whcu"]
#should return
>>> ["foo", "lem", "this"]
>>> ["ebh", "wosv", "foo", "4whcu"]

Rules:

Must be shorter than the below code in terms of byte size.
Order must be based on the count of  in descending order.
If there are two strings with the same count, the first appearance comes first
All duplicates must be removed, only one of each string should be in the final list

I currently have
list({}.fromkeys(sorted(s,key=lambda y:-s.count(y))))

I've noticed answers like set but that arbitrarily changes the order, which I do not want.
Edit: Sorry for the poor quality before. I had whipped this right before I slept and I was quite tired. This is not for StackOverflow because I'm trying to golf/shorten the size of this code as much as possible. I've tried looking for answers but I haven't been able to find anything.

44 bytes

sorted({}.fromkeys(s),key=s.count,reverse=1)

Try it online!
An improvement to the below, replacing the key with a built-in rather than a lambda, and using reverse to swap the comparisons. We'd like to do [::-1] on the final result instead, but that doesn't do the right stable tiebreaks.

47 bytes

sorted({}.fromkeys(s),key=lambda y:-s.count(y))

Try it online!
A simple transposition of your code, moving your {}.fromkeys de-duplication trick before the sorting. Since sorting converts to a list, extracting the keys from a dictionary, this saves the list() call of the original.
For ease of reference, the original code is:
53 bytes

list({}.fromkeys(sorted(s,key=lambda y:-s.count(y))))

Try it online!


Count spelling errors in text; minimize the number of spelling errors in your code Write a program or function that takes two inputs:

A text message
The dictionary of English language, as it appears in this Github file (containing about 60000 words)

and outputs the number of spelling errors in the message (see below for definition and test cases).

You can receive the dictionary as a parameter to your function, as a pre-defined file that your program expects to find, as hard-coded data in your code, or in any other sensible manner.

Your code should itself look like a text message, with a minimal number of spelling errors. So, you will calculate the score of your code by feeding it to itself as input.

The winner is code that has the lowest score (minimal possible score is 0). If there are several answers with the same score, the winner is decided by code size (in characters). If two answers are still tied, the winner is the earlier one.

If required, you can assume the input message to be ASCII (bytes 32...126) with newlines encoded in a conventional manner (1 byte "10" or 2 bytes "13 10"), and non-empty. However, if your code has non-ASCII characters, it should also support non-ASCII input (so it can calculate its own score).

Characters are subdivided into the following classes:

Letters a...z and A...Z
Whitespace (defined here as either the space character or the newline character)
Punctuation . , ; : ! ?

Sentence-ending . ! ?

Garbage (all the rest)

A word is defined as a sequence of letters, which is maximal (i.e. neither preceded nor followed by a letter).

A sentence is defined as a maximal sequence of characters that are not sentence-ending.

A character is a spelling error if it violates any of the spelling rules:

A letter must belong to a dictionary word (or, in other words: each word of length N that doesn't appear in the dictionary counts as N spelling errors)
The first character in a sentence, ignoring any initial whitespace characters, must be an uppercase letter
All letters must be lowercase, except those specified by the previous rule
A punctuation character is only allowed after a letter or garbage
A newline character is only allowed after a sentence-ending character
Whitespace characters are not allowed in the beginning of the message and after whitespace characters
There should be no garbage (or, in other words: each garbage character counts is a spelling error)

In addition, the last sentence must be either empty or consist of exactly one newline character (i.e. the message should end with a sentence-ending character and an optional newline - let's call it rule 8).

Test cases (below each character is a rule that it violates; after => is the required answer):

Here is my 1st test case!!
           711           4                => 4

main(){puts("Hello World!");}
2   777    883     3     77 78            => 12

  This message starts with two spaces
66                                   8    => 3

What ? No apostrophe's??
     4              71 4                  => 4

  Extra   whitespace   is   BAD!
66      661111111111 66   66333           => 21

Several
lines?
Must be used only to separate sentences.
                                          => 1 (first linebreak is en error: rule 5)

"Come here," he said.
73         7                              => 3 (sentence starts with '"', not 'C')

Perl 6, 134 spelling errors

my token punctuation {<[.,;:!?]>}
my \text = slurp; my \mistakes=[]; for split /\.|\!|\?/, text { for .trim.match: :g, /<:letter>+/ -> \word { (append mistakes, .comb when none words slurp pi given lc word) or (push mistakes, $_ if ((.from or word.from) xor m/<[a..z]>/) for word.match: :g, /./) }}
append mistakes, comb / <after \s | <punctuation>> <punctuation> | <!before <punctuation> | <:letter> | \s> . | <!after \.|\!|\?> \n | [<before ^> | <after \s>] \s /, text; say mistakes.Numeric

With extra whitespace for readability:

my token punctuation {<[.,;:!?]>}
my \text = slurp;
my \mistakes=[];
for split /\.|\!|\?/, text {
    for .trim.match: :g, /<:letter>+/ -> \word {
        (append mistakes, .comb when none words slurp pi given lc word)
        or
        (push mistakes, $_ if ((.from or word.from) xor m/<[a..z]>/) for word.match: :g, /./)
    }
}
append mistakes, comb /
  <after \s | <punctuation>> <punctuation>
  | <!before <punctuation> | <:letter> | \s> .
  | <!after \.|\!|\?> \n
  | [<before ^> | <after \s>] \s
/, text;
say mistakes.Numeric

Notes:

Expects the dictionary in a file called 3.14159265358979 in the current working directory.
The only inspired part is the line
append mistakes, .comb when none words slurp pi given lc word,
the rest is pretty bad. But maybe it can at least serve as a baseline for better solutions... :)


Explicit-ify APL expressions involving trains Related: Clearly parenthesize APL trains

Background

In the most basic form, APL has two kinds of tokens: arrays and functions. For this challenge, we will use a lowercase letter a-z for an array, and an uppercase letter A-Z for a function. Furthermore, we will assume each character is a token of its own; Fx is equivalent to F x.

APL has two ways to call a function: monadic (taking one argument) and dyadic (taking two arguments). Monadic application is written in prefix F x, and dyadic one is written in infix x F y. There's nothing like "operator precedence"; an APL expression is always evaluated from right to left, which can be overridden with parentheses ().

x F G y -> x F (G y)
F x G y -> F (x G y)
x F y G z -> x F (y G z)
(F x) G H y -> (F x) G (H y)

A train is a way to compose functions to derive a more complex function. In essence, a train is formed when the rightmost token is a function. Here are the rules for 2- and 3-token trains:

(F G H) x -> (F x) G (H x)
(u G H) x -> u G (H x)
(G H) x -> G (H x)

x (F G H) y -> (x F y) G (x H y)
x (u G H) y -> u G (x H y)
x (G H) y -> G (x H y)

For 4-token and longer trains, the rightmost 3 tokens are recursively grouped to form a derived function until 2 or 3 tokens remain. As a whole, it can be thought of as follows:

Odd-length trains
(V D V D ... V D V) x -> (V x) D (V x) D ... (V x) D (V x)
x (V D V D ... V D V) y -> (x V y) D (x V y) D ... (x V y) D (x V y)

Even-length trains
(M V D V D ... V D V) x -> M (V x) D (V x) D ... (V x) D (V x)
x (M V D V D ... V D V) y -> M (x V y) D (x V y) D ... (x V y) D (x V y)

If an array u appears at the V position (other than the last), replace the cooresponding (V x) or (x V y) simply with u. An array appearing at M or D position is a syntax error.

Note that trains may also have sub-expressions that evaluate to an array or a function:

x ((D a) F G (u H J) K) y
   Expand 5(odd)-token train, leftmost V position being an array (D a)
-> (D a) F (x G y) (u H J) (x K y)
   Expand 3(odd)-token train (u H J)
-> (D a) F (u H (x G y) J (x K y))

Challenge

Given a line of APL expression that evaluates to an array (which may or may not include one or more trains), convert it into an equivalent expression without a train.

You can assume that the input is valid under the rules stated above, and it doesn't contain any spaces. You don't need to worry too much about parentheses or spaces in the output; lacking or redundant parentheses/spaces are fine as long as they represent the equivalent expression.

Standard code-golf rules apply. The shortest code in bytes wins.

Test cases

x(XY)y -> X(xYy)
uKKKv -> uKKKv
U(xVW)yZa -> UxVWyZa
MnP(QRsTU)VWx -> MnP(QVWx)RsTUVWx
x(XXxYYYdDD)y -> (xXy)XxY(xYy)YdDxDy
a((DEF)GHJ)Kb -> (D(aGKb)HaJKb)EF(aGKb)HaJKb
c((k(PQRSTU)m)(VW)(XY)(ZA)BCD)n -> V(P(kQm)R(kSm)T(kUm))WZ(XcYn)A(cBn)C(cDn)

APL (Dyalog Classic), 63 59 58 54 52 51 bytes

∊⍎'.[A-Z].'⎕r'{0::&⍵⋄''() '',⍪⍺&⍵}'⊢'\w'⎕r'''&'''⊢⍞

Try it online!

put all letters in quotes, replace uppercase letters with dfns that return either "(left) self right" or "self right" depending on the presence of a left arg, and execute.


Are these states connected? With the US election going on right now, I noticed that there is one (completely meaningless, but still) thing which Trump can still achieve and which is out of reach for Biden: Having the won states being connected.
Task: Given a list of strings of two-letter abbreviations (see below) for US states, determine whether they are connected. That is, is the graph whose edges are the states in this list and where two edges are connected whenever the corresponding states are neighbors to each other connected? That is, for each two states, does there exist a path (in this graph) from one to another?
On Githhub, ubikuity has compiled a list of neighboring US states, which I copy here for convenience:
AK,WA
AL,FL
AL,GA
AL,MS
AL,TN
AR,LA
AR,MO
AR,MS
AR,OK
AR,TN
AR,TX
AZ,CA
AZ,CO
AZ,NM
AZ,NV
AZ,UT
CA,HI
CA,NV
CA,OR
CO,KS
CO,NE
CO,NM
CO,OK
CO,UT
CO,WY
CT,MA
CT,NY
CT,RI
DC,MD
DC,VA
DE,MD
DE,NJ
DE,PA
FL,GA
GA,NC
GA,SC
GA,TN
IA,IL
IA,MN
IA,MO
IA,NE
IA,SD
IA,WI
ID,MT
ID,NV
ID,OR
ID,UT
ID,WA
ID,WY
IL,IN
IL,KY
IL,MO
IL,WI
IN,KY
IN,MI
IN,OH
KS,MO
KS,NE
KS,OK
KY,MO
KY,OH
KY,TN
KY,VA
KY,WV
LA,MS
LA,TX
MA,NH
MA,NY
MA,RI
MA,VT
MD,PA
MD,VA
MD,WV
ME,NH
MI,OH
MI,WI
MN,ND
MN,SD
MN,WI
MO,NE
MO,OK
MO,TN
MS,TN
MT,ND
MT,SD
MT,WY
NC,SC
NC,TN
NC,VA
ND,SD
NE,SD
NE,WY
NH,VT
NJ,NY
NJ,PA
NM,OK
NM,TX
NM,UT
NV,OR
NV,UT
NY,PA
NY,VT
OH,PA
OH,WV
OK,TX
OR,WA
PA,WV
SD,WY
TN,VA
UT,WY
VA,WV

To be clear, “to be a neighbor of” is symmetric and hence the entry AK,WA means that AK neighbors WA and that WA neighbors AK. There might be some disagreement whether some of these states are indeed neighbors of each other but for the purpose of this question, let us go with the list above. (Although that would mean that Trump needs to lose Alaska in order to have his won states connected.)
Input: A list of two-letter strings or something equivalent such as a single string consisting of a series of two-letter pairs such as "AK WA OR" or "AKWAOR". It may be assumed that each string is one of the two-letter abbreviations in the list above and that no string appears more than once in the list.
Output: Return/Ouput a truthy value if the states are connected and a falsey value if they are not.
(Very!) simple test cases:

[] is connected.

["AK"] is connected.

["AK", "WA", "OR"] is connected.

["UT", "CO", "WY", "KS", "NM"] is connected. (That is, they form a connected graph although they do not form a “line” of neighboring states.)

["AK", "OR"] is not connected.

["ID", "OR", "WA", "AL", "GA", "TN"] is not connected.

Standard I/O rules apply and standard loopholes are forbidden.
This is code-golf, so shortest code in bytes wins.

Wolfram Language (Mathematica), 169 167 bytes
ConnectedGraphQ@Subgraph[Cases[#[v="StateAbbreviation"]&/@#@"BorderingStates"#@v&/@Interpreter["USState"]@#|"CA""HI"|"AK""WA"/."MI""MN"|"NY""RI"->0,a_ b_:>a<->b,3],#]&

Try it online!
TIO doesn't have data sets downloaded, so most of the footer is to ensure the code works as if they had been.
The BorderingStates properties differ from the given list of adjacencies in four ways: HI and AK do not border any other states, MI borders MN, and NY borders RI.
Interpreter["USStates"]@#           (* get Entitys corresponding to abbreviations *)
#@"BorderingStates"                 (* for each state, get a list of bordering states, *)
#[v="StateAbbreviation"]&/@ % #@v&  (* pair it (unordered) with each of those and convert back to abbreviations. *)
% /@ %%% |"CA""HI"|"AK""WA"         (* append CA-HI and AK-WA, *)
% /."MI""MN"|"NY""RI"->0            (* discard MI-MN and NY-RI, *)
Cases[ % ,a_ b_:>a<->b,3]           (* then get all pairs and convert them to edges. *)
ConnectedGraphQ@Subgraph[ % ,#]&    (* is the subgraph consisting of input states connected? *)

There's also GraphData["ContiguousUSAGraph"], which is missing AK-WA, AZ-CO, CA-HI, and NM-UT edges. Unfortunately, the vertices are numbered in what seems to be an arbitrary order.


compute number of 1 bits in a binary representation of a number The goal is to write a program that returns number of 1 bits in a given number.

Examples

5      ->  2
1254   ->  6
56465  ->  8

Winner

The winning submission is the code which runs in the minimum time. You can assume that normal int value in your language can handle any number (no matter how large) and computes all the valid operators defined for integer in O(1).

If two pieces of code run in the same time the winner is the one implemented in fewer bytes.

Please provide some explanation how your code is computing the result.

C/C++
int popcnt(int n)
{
    return __builtin_popcount(n);
}

For some CPUs __builtin_popcount compiles to a single instruction (e.g. POPCNT on x86).
Note: requires gcc or gcc-compatible compiler (e.g. ICC).


Make a Bubble-wrap simulator Bubble-wraps are maximum-level entertainment. Everyone can agree to that.
Now, you will make even computers enjoy bubble-wraps.
Specs
You will be given two integers, w, and h.(each are responsively width and height)
Your program should output all w*h phases waiting 1 second between each one and terminate.
Every bubble-wrap starts with all cells full.
For example, a 4*6 bubble-wrap starts like:
O_O_
_O_O
O_O_
_O_O
O_O_
_O_O

And each phase, a random non-popped cell is popped.For example,
O_O_
_O_O
O_X_
_O_O
O_O_
_O_O

The program should terminate when all the cells are popped. aka.
X_X_
_X_X
X_X_
_X_X
X_X_
_X_X

Examples
(4,6)
(5,5)
(6,2)
(10,10)
(7,9)


Weird string calculation String is given in form of a variable. Let's call that variable s. It is known that the string looks like a calculation expression using +, -, *, /. There's no parentheses.

Calculate the expression inside the string and store the result in variable r (you can assume it's already declared). All the divisions can be performed without remainders (4-6*3/8 is invalid because 8 is not divisible by 3). Length of string is not limited. String can't contain 0.

Challenge is not supposed to give advantage for some languages, so I decided to change some math rules:

Operators precedence is a little bit different than it is in math and programming language expressions: multiplication/division is still higher than addition/substraction. However, if there're some multiplications/divisions in a row, it is performed right-to-left. Addition/substraction is preformed left-to-right.

Sample s and r:

2+5-6/9*8+7 -> 2

1/3*6-6 -> 12

The shortest code (in bytes) wins.

Mathematica (41)
s = "2+5-6/9*8+7";
ToExpression@StringReplace[s,"/"->"^-1 "]

2

Correct me if I'm wrong


How many unique one sided polyominos Context

From Wikipedia:
A polyomino is a plane geometric figure formed by joining one or more equal squares edge to edge.

one-sided polyominoes are distinct when none is a translation or rotation of another (pieces that cannot be flipped over). Translating or rotating a one-sided polyomino does not change its shape.

In other words, a one sided polyomino reflected across its x or y axis is not the same as the original polyomino, but a one sided polyomino that is rotated is still considered the same polyomino

Task

Given a number n, find how many different unique one sided
polyominos can be created using n number of blocks

Input

Take integer n as input for the number of blocks that exist in the polyomino

Output

An integer of the amount of unique one sided polyominos that can be generated

Examples

in -> out

4 -> 7

5 -> 18

6 -> 60

7 -> 196

More test cases can be found on the Wikipedia page and OEIS

Jelly,  39  37 bytes
Soon to be crushed by MATL and, quite possibly, APL
p`œc⁸ḣ1ạ§ỊẸʋƇ@;QɗƬƊṪṢƊƑƇŒṬZṚŒṪƲƬṂ$€QL

Try it online! (It's pretty slow - a(6) took ~30 minutes locally!)
To see them instead try this (L -> ŒṬ€G€j⁾¶¶).
How?
Builds all index lists, where each represents the locations of 1s on a grid of 1s and 0s, up to those for a square of side n, filters for those that have their 1s fully connected, then selects the "minimal" of each after any amount of rotation + vertical translation, and finally de-duplicates and yields the length.
   p`œc⁸ḣ1ạ§ỊẸʋƇ@;QɗƬƊṪṢƊƑƇŒṬZṚŒṪƲƬṂ$€QL - Link: integer, n
   A....B..................C............ - break down below

A: p`œc⁸ - Get all ways to have n 1s on an n*n grid as multidimensional indices
    `    - use n as both arguments of:
   p     -   Cartesian product -> all pairs of [1..n] - these are in sorted order
       ⁸ - chain's left argument, n
  œc     - combinations (no replacement) - ...and so each of these are in sorted order

B: ḣ1ạ§ỊẸʋƇ@;QɗƬƊṪṢƊƑƇ - Keep only the fully-connected ones (call input "All")
                     Ƈ - filter keep those for which:
                    Ƒ  -   is invariant under:
                   Ɗ   -     last three links as a monad:
                Ɗ      -       last three links as a monad:
    1                  -         one
   ḣ                   -         head to index - i.e. [firstPair] (initial "Current")
               Ƭ       -         collect up while distinct, applying:
              ɗ        -           last three links as a dyad - i.e. f(Current, All):
           @           -             with swapped arguments - i.e. f(All, Current):
          Ƈ            -               filter keep those (of All) for which:
         ʋ             -                 last four links as a dyad - i.e. f(All, Current):
     ạ                 -                   absolute difference (vectorises)
      §                -                   sum each
       Ị               -                   insignificant? (effectively "in (0,1)?")
        Ẹ              -                   any? - i.e. any are neighbours/same?
            ;          -             concatenate (the result with Current)
             Q         -             deduplicate (-> Current for the next Ƭ-loop)
                 Ṫ     -       tail
                  Ṣ    -       sort

C: ŒṬZṚŒṪƲƬṂ$€QL - Count the distinct results
             €   - for each:
            $    - last two links as a monad:
          Ƭ      -   collect up while distinct, applying:
         Ʋ       -     last four links as a monad:
   ŒṬ            -       2d array from multidimensional indices
     Z           -       transpose
      Ṛ          -       reverse (transpose + reverse = rotate 1/4 anti-clockwise)
       ŒṪ        -       truthy multidimensional indices
           Ṃ     -   minimum
              Q  - de-duplicate
               L - length


Sort by Largest Digit(s) Challenge:

Given a list of integer, sort descending by their single largest digit(s). The order for numbers with the same largest digit are then sorted by second largest digit, etc.
We ignore duplicated digits in numbers. And if all digits in a number are the same, the order of those numbers in the list can be in any way you'd like.

Example:

Input:            [123, 478, -904, 62778, 0, -73, 8491, 3120, 6458, -7738, 373]
Possible outputs: [8491, -904, 62778, 478, -7738, 6458, 373, -73, 3120, 123, 0]
                  [8491, -904, 62778, 478, -7738, 6458, -73, 373, 3120, 123, 0]

Why? Here are the relevant digits the numbers were sorted on:

Output:
[8491,  -904,  62778,   478,     -7738,   6458,  373,   -73,   3120,      123,     0  ]

Relevant digits they were sorted on:
[[9,8], [9,4], [8,7,6], [8,7,4], [8,7,3], [8,6], [7,3], [7,3], [3,2,1,0], [3,2,1], [0]]

Challenge rules:

We ignore duplicated digits, so 478 and -7738 will be ordered as 478, -7738, because the largest digits are [8,7,4] and [8,7,3], and not [8,7,4] and [8,7,7,3].
If multiple numbers have the same digits, the order of those can be either way. So 373 and -73 can be sorted as both 373, -73 or -73, 373 (digits are [7,3] for both of these numbers).
If a number contains no more digits to check, it will be placed at the back of the relevant numbers. So 123 and 3120 will be sorted as 3120, 123, because the largest digits [3,2,1] are the same, but 0 comes before none.
You can assume all numbers in the input are in the range [-999999,999999].
Just one of the possible outputs is enough as result, but you are allowed to output all possible outputs where sublists can be in any permutation if you want (although I doubt it would save bytes in any language).

General rules:

This is code-golf, so shortest answer in bytes wins.
Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.
Standard rules apply for your answer with default I/O rules, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call.
Default Loopholes are forbidden.
If possible, please add a link with a test for your code (i.e. TIO).
Also, adding an explanation for your answer is highly recommended.

Test cases:

Input:            [123, 478, -904, 62778, 0, -73, 8491, 3120, 6458, -7738, 373]
Possible outputs: [8491, -904, 62778, 478, -7738, 6458, 373, -73, 3120, 123, 0]
                  [8491, -904, 62778, 478, -7738, 6458, -73, 373, 3120, 123, 0]

Input:            [11, -312, 902, 23, 321, 2132, 34202, -34, -382]
Possible outputs: [902, -382, 34202, -34, -312, 321, 2132, 23, 11]
                  [902, -382, 34202, -34, 2132, -312, 321, 23, 11]
                  etc. The sublist [-312, 321, 2132] can be in any permutation

Input:            [9, 44, 2212, 4, 6, 6, 1, 2, 192, 21, 29384, 0]
Possible outputs: [29384, 192, 9, 6, 6, 4, 44, 2212, 21, 2, 1, 0]
                  [29384, 192, 9, 6, 6, 44, 4, 2212, 21, 2, 1, 0]
                  etc. The sublists [4, 44] and [2212, 21] can be in any permutation

Input:            [44, -88, 9, 233, -3, 14, 101, 77, 555, 67]
Output:           [9, -88, 67, 77, 555, 14, 44, 233, -3, 101]

05AB1E, 5 bytes

ΣêR}R

Try it online!
or as a Test suite

Explanation

Σ  }    # sort input by
 ê      # its sorted unique characters
  R     # reversed (to sort descending)
    R   # reverse the result (to sort descending)


Find the odd one out in a sequence The Challenge:

Consider the function F(N) = 2^N + 1 where N is a positive integer less than 31. The sequence defined by this function is:

3, 5, 9, 17, 33, 65, 129, 257, 513, 1025, 2049, 4097, 8193, 16385, 32769, 65537, 131073, 262145, 524289, 1048577, 2097153, 4194305, 8388609, 16777217, 33554433, 67108865, 134217729, 268435457, 536870913, 1073741825

An input will be generated as follows:

Take 5 contiguous integers from the above sequence.
Replace one of them with a different, positive integer (which may or may not be part of the above sequence).
Optionally reorder the the 5 resulting numbers.

Given such a list of 5 integers, find the one that was swapped in and is therefore not part of the original 5 contiguous integers.

Example:

Original sublist: 5, 9, 17, 33, 65.
Replace one: 5, 7, 17, 33, 65.
Reorder: 33, 17, 5, 7, 65.

The expected output would be 7.

The 5 values in the input will always be distinct and there will always be a unique solution. (For instance, you won't have to deal with inputs like 3, 9, 17, 33, 129 where either 3 or 129 might have been swapped in.)

Test Cases:

5,9,17,33,829
o/p: 829

9,5,17,829,33
o/p: 829

33, 17, 5, 7, 65
o/p: 7

5,9,177,33,65
o/p: 177

65,129,259,513,1025
o/p: 259

129,259,513,1025,65
o/p: 259

63,129,257,513,1025
o/p: 63

65,129,257,513,4097
o/p: 4097

5, 9, 2, 17, 33
o/p: 2

536870913, 67108865, 1073741825, 1, 268435457
o/p: 1

Jelly, 15 bytes

⁹R2*‘ṡ5ḟ@€µEÐfQ

TryItOnline
All test cases also at TryItOnline

Returns a list containing one list containing the odd one out.

How?

⁹R2*‘ṡ5ḟ@€µEÐfQ - Main link, a (list)
⁹               - literal 256 (saving a byte over literal 30)
 R              - range, [1,2,3,...]
  2*            - 2 ** x, [2,4,8,...]
    ‘           - increment, [3,5,9,...]
     ṡ5         - all contiguous slices of length 5
       ḟ@€      - filter with reversed arguments for each
          µ     - monadic chain separation
            Ðf  - filter on condition:
           E    - all equal (those previously filtered lists with only one value)
              Q - unique (there can be two, but both will have the same odd-one-out)


Cutting Sequence for N dimensions Inputs:

The program or function should take 2 vector-like (e.g. a list of numbers) O and V  of the same number of dimensions, and a number T (all floating-point numbers or similar)

Constraints:

T >= 0
All elements of Vector O will be in the range [0,1)

Output:

The program or function should output the N dimensional cutting sequence given an infinite ray whose origin is the first vector, and whose velocity is the second vector.  The sequence should include every cut the ray makes on the time interval (0, T], appearing in order of when they occur.  Details on the format and specification of the sequence are explained below

Cutting sequence

In a N dimensional Cartesian coordinate system, there exist axis-aligned unit coordinate facets, e.g. the integer points on a 1 dimensional number line, the unit grid lines on a 2D grid, planes like x = 1, z =- 10 or y = 0 in 3D space.  As this problem is generalized to N dimensions, from here forward we will no longer use lettered axes, but instead number the axes starting with 0.  Every facet can be defined by some equation like Axis j = k, where j and k are integers, and j is the characteristic axis of the facet.

As the ray extends through N dimensional space, it intersects these facets. This is called a cut.  Each of these cuts is described by 2 things.

The characteristic axis of the facet.
The direction of the cut, i.e. whether the ray extending positively or negatively with respect to the characteristic axis.

Hence each cut shall be outputted in the sequence as a string of a plus or minus sign corresponding to the direction of the cut, then the number (base 10) of the characteristic axis of the cut facet.

The sequence will be outputted as a continuous string of these cuts, e.g. +0+1+0+0+1-2+0

Examples

This image from the Wikipedia page for Cutting Sequence shows a 2D example. This is equivalent to O=[0,0] V=[1,0.618] T = 6.5, where the output is +0+1+0+0+1+0+1+0+0+1

For 1 dimension, all non-empty cutting sequences will look like +0+0+0... or -0-0-0...

More examples / test cases to be added

Special cases

If two or more cuts occur at exactly the same time (to the precision
of your numeric type), they must appear in the sequence in order of their axis from least to greatest
Your program should be accurate for extreme input values

e.g. for V=[1, -0.0009765625], the sequence will have a repeating pattern of +0 1024 times and then a -1.  This pattern should hold exactly for arbitrarily large values of T

Your program must always output a sequence, e.g.

If Vector V has a length 0, the program should not loop indefinitely, but output an empty sequence.
If the inputs are of 0 dimensions, the program should output an empty sequence

Python, 226 bytes

Assumes the lists O and V are defined, as well as the time T, either an int or a float.

Try it online

s=lambda x:int(x/abs(x));r=range;f=lambda O,V,T:"".join(map(lambda t:t[1],sorted(sum([[((i-o)/v,"%+d"%(s(v)*c))for i in r((v>0)-(v<0)*(o==0),int((o+T*v)//1)+(v>0),s(v))]for c,o,v in zip(r(len(O)),O,V)],[]),key=lambda t:t[0])))

The idea of the code is simple, first we loop over all coordinates, and for each coordinate we:

find where the first cut is, depending on the sign of v and the origin being 0 or not, the first cut might be at -1, 0 or 1;
find how far the ray goes in the time given with o + v*T (which then needs proper rounding to be an argument for the range function);
find the time t for which each successive cut occurs, by solving o + v*t = i iff t = (i - o)/v, for the successive integer values of i (this amounts to finding the time for which the ray crosses the hyperplane x_c = i);
sort everything by the time and drop the time, as it was just an auxiliary thing.

The code un-golfed:

# sign function, returns 1 for positive numbers and -1 for negative numbers
sgn = lambda x: int(x/abs(x))
l = []
# c is the coordinate we are in,
# o is the origin in this coordinate and v the velocity
for (c, o, v) in zip(range(len(O)), O, V):
    # find all the cuts for this coordinate
    sub_l = []
    # this is how far the ray goes, rounded to integers, in T seconds
    stop_at = int((o + T*v)//1) # if this is negative, //1 pushes the result away from 0
    if v > 0:
        stop_at += 1
    # this is where the first cut occurs (depends on o == 0 and the sign of v)
    if v > 0:
        start_at = 1
    elif o > 0:
        start_at = 0
    else:
        start_at = -1
    for i in range(start_at, stop_at, sgn(v)):
        # this is the time at which the ray cuts the x_c = i hyperplane
        t = (i - o)/v
        # append the time of the cut and the signed axis
        sub_l.append((t, "%+d"%(sgn(v)*c)))
    l.append(sub_l)
print(l)
# flatten list
l = sum(l, [])
# order list by the time at which the cut occurs
l.sort(key = lambda tup: tup[0])
# remove the times, keep the coordinates
l = map(lambda tup: tup[1], l)
# join and print
print("".join(l))

Then we just need to note a couple of things, like I can save some bytes if I redefine r = range or if I assign start_at = (v>0)-(v<0)*(o==0) and stop_at = int((o+T*v)//1)+(v>0).

I don't feel this is properly golfed, I just wrote a program that works and then crammed everything together. Please feel free to give me some feedback.

I used a flatten from https://stackoverflow.com/a/952946/2828287 and getting the sign of a number from https://stackoverflow.com/a/2763445/2828287


Limerick Hello World A rhyming program you write
Attempting to win the fight
For winning the contest and vote
It must compute "Hello World"
Then print it very polite

The most popular poem will win.

The requirements are:

The poem should be of 5 lines with rhymes AABBA
It can print whatever you want, but the output should contain "hello world" (uppercase/lowercase does not matter, quotes not included in the output)
Symbols are read aloud. For example, the fourth line above is read: It must compute quote hello world quote
Post below your code, on another code preview, the "read-aloud" version of your code for disambiguation on special symbols.

Excluded are poems:

including dead code, or characters which could be safely removed without changing the rhymes or the functionality
Using comments as a way to rhyme (except if there is a good reason for that)
using the same symbol as end of phrase for rhyme.

In case of a tie, programs outputting a poem will win. If there is still a tie, shorter programs will win.

New lines do not count. spaces, tabs and newlines are not read aloud.
For example, "Hello, world!" would be read aloud "double-quote hello comma world exclamation point double-quote".

Whitespace

A rhyming program I	wrote

this poem of whitespace and bloat

because newlines don't count

despite the amount

so deserves your sincerest upvote

Wikipedia: Whitespace (programming language)
Online Interpreter to Test Answer

Output:

Hello World


The Euclidean Algorithm (for finding the greatest common divisor) The Challenge

Write a program or function that takes two input integers, i and j, and outputs their greatest common divisor; calculated by using the Euclidean algorithm (see below).

Input

Input may be taken as a space-delimited string representation of i and j or as two separate integers. You can assume that integers will be less than or equal to 10,000. You can also assume that the input integers will not be prime to one another.

Euclidean Breakdown

The larger number between i and j is divided by the smaller as many times as possible. Then, the remainder is added. This process is repeated with the remainder and the previous number, until the remainder becomes 0.

For example, if the input was 1599 650:

1599 = (650 * 2) + 299
 650 = (299 * 2) +  52
 299 =  (52 * 5) +  39
  52 =  (39 * 1) +  13
  39 =  (13 * 3) +   0

The final number, 13, is the greatest common divisor of the two input integers. It can be visualized like this:

Output

Your output must be the breakdown in the form above, followed by a newline and the GCD. It can be output through any medium.

Examples

Inputs

18 27
50 20
447 501
9894 2628

Outputs

27 = (18 * 1) + 9
18 =  (9 * 2) + 0
9

50 = (20 * 2) + 10
20 = (10 * 2) +  0
10

501 = (447 * 1) + 54
447 =  (54 * 8) + 15
 54 =  (15 * 3) +  9
 15 =   (9 * 1) +  6
  9 =   (6 * 1) +  3
  6 =   (3 * 2) +  0
3

9894 = (2628 *  3) + 2010
2628 = (2010 *  1) +  618
2010 =  (618 *  3) +  156
 618 =  (156 *  3) +  150
 156 =  (150 *  1) +    6
 150 =    (6 * 25) +    0
6

Note: Outputs do not have to be spaced as they are above. The spacing is only for clarity. Parentheses are required.

Bonus

If your output is spaced as above, you may add a -10% bonus to your score.

CJam, 46 43 39 bytes

q~]$3*~\{N5$"=("3$:G'*3$Gmd")+"\}h]7>NG

Try it online in the CJam interpreter.

How it works

q~]    e# Read all input, evaluate it and wrap the results in an array.
$3*    e# Sort the array and repeat it thrice.
~\     e# Dump the array and swap its last two elements.
{      e# Do:
  N    e#   Push a linefeed.
  5$   e#   Copy the sixth topmost element from the stack.
  "=(" e#   Push that string.
  3$:G e#   Copy the fourth topmost element from the stack. Save it in G.
  '*   e#   Push that character.
  3$   e#   Copy the fourth topmost element from the stack.
  Gmd  e#   Push quotient and remainder of its division by G.
  ")+" e#   Push that string.
  \    e#   Swap the string with the remainder.
}h     e#   If the remainder is positive, repeat the loop.
]7>    e# Wrap the stack in an array and discard its first seven elements.
NG     e# Push a linefeed and G.


Backspace-and-retype a list of words Here’s how to backspace-and-retype from one string to another:

Start from the first string.
Remove characters at the end until the result is a prefix of the second string. (This may take 0 steps.)
Add characters at the end until the result equals the second string. (This may take 0 steps, too.)

For example, the path from fooabc to fooxyz looks like:

fooabc
fooab
fooa
foo
foox
fooxy
fooxyz

Task

Given a list of words, write a program that backspace-and-retypes its way from the empty string, to all of the words in the list in succession, back to the empty string. Output all intermediate strings.

For example, given the input list ["abc", "abd", "aefg", "h"], the output should be:

a
ab
abc
ab
abd
ab
a
ae
aef
aefg
aef
ae
a

h

Rules

You may return or print a list of strings, or a single string with some delimiter of choice. You may optionally include the initial and final empty strings. The input is guaranteed to contain at least one word, and each word is guaranteed to contain only lowercase ASCII letters (a–z). Edit: consecutive strings in the input are guaranteed not to equal each other.

This is code-golf; shortest code in bytes wins.

A reference implementation in Python 3: Try it online!

Perl, 43 bytes
42 bytes of code + -n flags.
chop$@,say$@while!s/^$@//;s/./say$@.=$&/ge

To run it:
perl -nE 'chop$@,say$@while!s/^$@//;s/./say$@.=$&/ge' <<< "abc
abd
aefg
h"


Is it a prime? w/o math Write a program or function in any language that tells if the input is a prime number.

The input is a string representing a natural number in base-10.
The output is one of the two strings "Prime" or "Not!!" which correctly identifies the input.
Arithmetic operators, bit-wise operators, numeric variables and constants, "math-stuff" in general, etc... are not allowed anywhere in your program.  You should use string operations to do all necessary "calculations".
You can compare string lengths (which are numbers) - but -10 to your score if you don't.
Your program should work on any length input (given enough memory and time).
Lowest byte count (UTF-8) wins.

Ruby: 52 - 10 = 42

Using a variation of that famous prime-matching regex.

puts ?_*gets.to_i=~/^(_|(__+?)\2+)$/?"Not!!":"Prime"

Just to be clear: ?_*gets.to_i is a string operation that appends "_" to itself n times, where n is the input number. As I see it no string lengths are compared, so that should satisfiy the 10 character bonus criterium.


Adding up the digits and the digits reversed Given a number > 0, output the sum with all digits (1 .. n) concatenated and reversed and add them up. For example, with n = 6:

The numbers 1 to 6 concatenated:

123456

Reversed:

654321

Adding them up together will result in: 777777. Another example is n = 11:

1 2 3 4 5 6 7 8 9 10 11 > 1234567891011

and

11 10 9 8 7 6 5 4 3 2 1 > 1110987654321

Adding them up together will result in 2345555545332. This is also known as A078262.

Shortest code wins!

05AB1E, 7 bytes
LDRJsJ+

Try it online.
Explanation
LDRJsJ+

L        range from 1 .. input
 D       duplicate
  R      reverse
   JsJ   convert both arrays to strings
      +  add (coerces both strings to ints)


Probabilities - how high can you go? I previously asked a question for how to compute a probability quickly and accurately.  However, evidently it was too easy as a closed form solution was given!  Here is a more difficult version.

This task is about writing code to compute a probability exactly and quickly. The output should be a precise probability written as a fraction in its most reduced form. That is it should never output 4/8 but rather 1/2.

For some positive integer n, consider a uniformly random string of 1s and -1s of length n and call it A. Now concatenate to A a copy of itself. That is A[1] = A[n+1] if indexing from 1, A[2] = A[n+2] and so on.  A now has length 2n. Now also consider a second random string of length n whose first n values are -1, 0, or 1 with probability 1/4,1/2, 1/4 each and call it B.

Now consider the inner product of B with A[1+j,...,n+j] for different j =0,1,2,....

For example, consider n=3. Possible values for A and B could be A = [-1,1,1,-1,...] and B=[0,1,-1]. In this case the first two inner products are 0 and 2.

Task

For each j, starting with j=1, your code should output the probability that all the first j+1 inner products are zero for every n=j,...,50.

Copying the table produced by Martin Büttner for j=1 we have the following sample results.

n   P(n)
1   1/2
2   3/8
3   7/32
4   89/512
5   269/2048
6   903/8192
7   3035/32768
8   169801/2097152

Score

Your score is the largest j your code completes  in 1 minute on my computer.  To clarify a little, each j gets one minute. Note that the dynamic programming code in the previous linked question will do this easily for j=1.

Tie breaker

If two entries get the same j score then the winning entry will be the one that gets to the highest n in one minute on my machine for that j. If the two best entries are equal on this criterion too then the winner will be the answer submitted first.

Languages and libraries

You can use any freely available language and libraries you like. I must be able to run your code so please include a full explanation for how to run/compile your code in linux if at all possible.

My Machine The timings will be run on my machine. This is a standard ubuntu install on an AMD FX-8350 Eight-Core Processor.  This also means I need to be able to run your code.

Winning entries

j=2 in Python by Mitch Schwartz.
j=2 in Python by feersum. Currently the fastest entry.

Python, j=2

The dynamic programming approach for j = 1 in my answer to the previous question does not need many modifications to work for higher j, but gets slow quickly. Table for reference:

n   p(n)

2   3/8
3   11/64
4   71/512
5   323/4096
6   501/8192
7   2927/65536
8   76519/2097152
9   490655/16777216
10  207313/8388608

And the code:

from time import*
from fractions import*
from collections import*

def main():
    N_MAX=50

    T=time()

    n=2
    Y=defaultdict(lambda:0)
    numer=0

    for a1 in [1]:
        for b1 in (1,0):
            for a2 in (1,-1):
                for b2 in (1,0,0,-1):
                    if not a1*b1+a2*b2 and not a2*b1+a1*b2:
                        numer+=1
                    Y[(a1,a2,b1,b2,a1*b1+a2*b2,a2*b1,0)]+=1

    thresh=N_MAX-1

    while time() <= T+60:
        print('%d %s'%(n,Fraction(numer,8**n/4)))

        if thresh<2:
            print('reached N_MAX with %.2f seconds remaining'%(T+60-time()))
            return

        n+=1
        X=Y
        Y=defaultdict(lambda:0)
        numer=0

        for a1,a2,b1,b2,s,t,u in X:
            if not ( abs(s)<thresh and abs(t)<thresh+1 and abs(u)<thresh+2 ):
                continue

            c=X[(a1,a2,b1,b2,s,t,u)]

            # 1,1

            if not s+1 and not t+b2+a1 and not u+b1+a1*b2+a2: numer+=c
            Y[(a1,a2,b2,1,s+1,t+b2,u+b1)]+=c

            # -1,1

            if not s-1 and not t-b2+a1 and not u-b1+a1*b2+a2: numer+=c
            Y[(a1,a2,b2,1,s-1,t-b2,u-b1)]+=c

            # 1,-1

            if not s-1 and not t+b2-a1 and not u+b1+a1*b2-a2: numer+=c
            Y[(a1,a2,b2,-1,s-1,t+b2,u+b1)]+=c

            # -1,-1

            if not s+1 and not t-b2-a1 and not u-b1+a1*b2-a2: numer+=c
            Y[(a1,a2,b2,-1,s+1,t-b2,u-b1)]+=c

            # 1,0

            c+=c

            if not s and not t+b2 and not u+b1+a1*b2: numer+=c
            Y[(a1,a2,b2,0,s,t+b2,u+b1)]+=c

            # -1,0

            if not s and not t-b2 and not u-b1+a1*b2: numer+=c
            Y[(a1,a2,b2,0,s,t-b2,u-b1)]+=c

        thresh-=1

main()

Here we are keeping track of the first two elements of A, the last two elements of B (where b2 is the last element), and the inner products of (A[:n], B), (A[1:n], B[:-1]), and (A[2:n], B[:-2]).


Morse code translator Write the shortest program to transform the standard input into Morse code. Characters not in the table should be printed as they are.

C# (213 characters)

I'm sure this wont stand long, but at least I got the technique here first!

class P{static void Main(string[] a){foreach(var t in a[0]){var c="";for(int i=" ETIANMSURWDKGOHVF L PJBXCYZQ  54 3   2       16       7   8 90".IndexOf(t);i>0;i/=2)c="-."[i--%2]+c;System.Console.Write(c+"  ");}}}

And in readable format:

class P
{
    static void Main(string[] a)
    {
        foreach(var t in a[0])
        {
            var c="";
            for(int i=" ETIANMSURWDKGOHVF L PJBXCYZQ  54 3   2       16       7   8 90".IndexOf(t);i>0;i/=2)c="-."[i--%2]+c;
            System.Console.Write(c+" ");
        }
    }
}

For a brief explanation, the string of characters is a heap in which the left child is a dot and the right child is a dash.  To build the letter, you traverse back up and reverse the order.


Shortest expression for {0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4} Given list of integers {0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4}.
For those who interested these numbers are used in weekday calculation.

Weekday = (m[n] + d + y + y>>2 + y/400 - y/100) % 7;, where m[n] - expression I'm searching, d - day of month, y - year - (month <= 2).

Construct expression consisting of arithmetic, logic and bitwise operators, which will output for positive integer n integer m so that m % 7 equals n-th number in the list.

Branches, ternary operators, table lookups and pointers are not allowed.

Score:
1 - for | & ^ ~ >> << operators
1.1 - for + - < > <= >= == != ! && || operators
1.2 - for * operator
1.4 - for / % operators

Answer with lowest score wins.

Personally I have found:

   (41*n)>>4+((n+61)>>4)<<2 with score 6.4.
 I thought this will be hard to find so provided own expression to start with.


What is the Probability that a Knight Stays on Chessboard? Given the size of the chess board and initial position of the knight, calculate the probability that after k moves the knight will be inside the chess board.

Note:

The knight makes its all 8 possible moves with equal probability.
Once the knight is outside the chess board it cannot come back inside.

Input

Inputs are comma separated in the form:

l,k,x,y

where l is the length and width of the chess board, k is the number of moves the knight will make, x is the x-position of the initial position of the knight, and y is the y-position of the initial position of the knight. Note that 0,0 is the bottom-left corner of the board and l-1,l-1 is the top-right corner of the board.

Algorithm:

Start with the initial coordinates of the knight. Make all possible moves for this position and multiply these moves with their probability, for each move recursively call the function continue this process till the terminating condition is met. Terminating condition is if the knight is outside the chess board, in this case return 0, or the desired number of moves is exhausted, in this case return 1.

As we can see that the current state of the recursion is dependent only on the current coordinates and number of steps done so far. Therefore we can memorize this information in a tabular form.

Credit

This challenge is originally from a blog post of crazyforcode.com published under the CC BY-NC-ND 2.5 IN licence. It was slightly modified to make it a bit more challenging.

Pyth, 38 bytes

M?smcgtGd8fq5sm^-Fk2C,TH^UhQ2G1g@Q1>Q2

Try it online: Demonstration

Explanation:

                                        implicit: Q = evaluated input
M                                       define a function g(G,H): //G=depth, H=current cell
                         UhQ              the list [0,1,...,Q[0]-1]
                        ^   2             Cartesian product, gives all cells
          f                               filter for numbers numbers T, which satisfy:
                    C,TH                    zip(T,H)
              m                             map the two pairs k to:
                -Fk                           their difference
               ^   2                          squared
             s                              sum (distance squared)
           q5                               == 5
   m                                      map each valid cell d to:
     gtHd                                   g(G-1,d)
    c    8                                  divided by 8
  s                                       return sum
 ?                           G          if G > 0 else
                              1           return 1

                               g@Q1>Q2  call g(Q[1],Q[2:]) and print


Break my source file! Challenge
Create a program that, when run, changes the contents of the source file. This means that you can delete/add/change characters in the source file, but you can't delete the (source) file itself (deletion is when the source file does not exist after the program is run).
In the case of pre-compiled languages such as C++, your program can change the source file only, such that when compiled, either fails or does not produce the same result.
Your program must not return any errors, such as access violations (e.g. opening a file that is already open).

This is an advantage to pre-compiled languages, as the source file does not have to be in use to run it.

Input
You may take an optional path to the source file, but nothing more.
Output
You may output anything.
Scoring
This is code-golf, shortest answer wins!

Zsh, 3 bytes

>$0

Truncates the script to length 0.

Unlike its Bash counterpart, this handles filenames that contain whitespace.

Try it online!


Split string using rules Introduction

Some time ago, I need to write function which split string in some specific way. At the first look, task looks trivial, but it was not so easy - especially when I want to decrease code size.

Challenge

As example we have following input string (it can be arbitrary)

  Lorem ipsum dolor sit amet consectetur adipiscing elit sed doeiusmod tempor incididunt ut Duis aute irure dolor in reprehenderit in esse cillum dolor eu fugia ...

We need to splitting it into elements (
groups of adjacent words) using following  rules (A-E)

 "Lorem ipsum dolor",  // A: take Three words if each has <6 letters
 "sit amet",           // B: take Two words if they have <6 letters and third word >=6 letters
 "consectetur",        // C: take One word >=6 letters if next word >=6 letters
 "adipiscing elit",    // D: take Two words when first >=6, second <6 letters
 "sed doeiusmod",      // E: Two words when first<6, second >=6 letters
 "tempor"              // rule C
 "incididunt ut"       // rule D
 "Duis aute irure"     // rule A
 "dolor in"            // rule B
 "reprehenderit in"    // rule D
 "esse cillum"         // rule E
 "dolor eu fugia"      // rule D
 ...

So as you can see input string (only alphanumeric characters) is divided to elements (substrings) - each element can have min one and max three words. You have 5 rules (A-E) to divide your string - if you take words one by one from beginning - only one of this rule applied. When you find rule, then you will know how many words move from input to output (1,2 or 3 words) - after that start again: find next rule for the remaining input words.

Boundary conditions: if last words/word not match any rules then just add them as last element (but two long words cannot be newer in one element)

In the output we should get divided string - each element separated by new line or | (you don't need to use double quotes to wrap each element)

Example Input and Output

Here is example input (only alphanumeric ASCII characters):

Lorem ipsum dolor sit amet consectetur adipiscing elit sed doeiusmod tempor incididunt ut Duis aute irure dolor in reprehenderit in esse cillum dolor eu fugia

and its output:

Lorem ipsum dolor|sit amet|consectetur|adipiscing elit|sed doeiusmod|tempor|incididunt ut|Duis aute irure|dolor in|reprehenderit in|esse cillum|dolor eu fugia

Python 2, 92 90 88 87 86 85 bytes

r=''
n=0
for w in input().split():L=w[:5]<w;x=n+L<3;r+='| '[x]+w;n=n*x-~L
print r[1:]

Try it online!

-1 byte, thanks to Kevin Cruijssen


Letters in phone numbers Problem:

You are making a new phone where people can type in specialized phone numbers, for example, 1-800-program, and they would be converted automatically to a usable phone number, like 1-800-7764726 (for the previous example).

Your program will recieve a string if any length with numbers, letters and dashes, and convert all the letters to their corresponding numbers.

Here is a keypad, for reference:

Rules:

Your program will receive a string
It will process it and return/print another string
Any language is accepted
Since it is code-golf, the shortest code wins

Bash, 30

Edit: Thank you Doorknob for eliminating 3 chars

tr a-z 22233344455566677778889

Example:


Reverse every word in a line in vim Your task is to build a vim script or provide a sequence of keystrokes that will operate on a single line of text with up to 140 printable ASCII characters (anywhere in a file, with the cursor starting anywhere in the line) and reverse every space-separated string in the sentence while keeping the strings in the same order.

For example, the input:

roF emos nosaer m'I gnisu a retcarahc-041 timil no siht noitseuq neve hguoht ti t'nseod evlovni .rettiwT RACECAR

should return:

For some reason I'm using a 140-character limit on this question even though it doesn't involve Twitter. RACECAR

The script with the fewest characters, or the sequence of the fewest keystrokes, to achieve this result is the winner.

28 25 24 keystrokes

:se ri<CR>^qqct <C-r>"<Esc>f l@qq@q

Recursive macro, I assume that Ctrl-r counts as one keystroke.

The hardest part was to make sure the macro stays on the same line and does not destroy the rest of the file.


'Number' Crunching Benchmark I just want to do some benchmarking of different programming languages. So here is a tip: You can use as many characters as you want. In the end there is only the time your program needed.

So, here is the Task:

Task

After searching for a good task that would require a lot of computation, I came up with the problem Is a word in a given Type-1 grammar?

For people not knowing what this is: Formal Grammar  Chomsky-Hierarchy

Maybe there is a better algorithm but I came only up with brute forcing.

So, write a code that brute forces the Grammars as fast as possible.

Rules

Parallel execution is allowed
Delete your cache after every tested word
Add your complete compiler command for optimized result
You can use any algorithm and language you want, as long as the job gets done.
Add to your answer what files are read/how to set the files that should be read.

I Guarantee

Input is always well formatted
Variables are always capital letters, Terminals always small ones
Words only consist of Terminals
No empty Word

Input

For equal footing we need to define what the input looks like. The input is a file. I write multiple grammars and words in one file. The structure can be described with following Pseudocode:

foreach(Grammar G) do
    write('{');
    foreach (Variable V in G) do
        write(T + ',');
    od
    deleteLast();
    write('}');
    linebreak();
    write('{');
    foreach (Terminal T in G) do
        write(V + ',');
    od
    deleteLast();
    write('}');
    linebreak();
    write('{');
    foreach(Production P in G) do
        write(P + ',');
    od
    write('}');
    linebreak;
    write(StartSymbol(G));
    linebreak;
    foreach(Word W for G) do
        write(W + ',');
    od
    deleteLast();
    linebreak;
od
deleteLastLinebreak();

An Example

Output

The output has to be put in a file as well. The formatting of the output does not matter. It should be recognizable which result belongs to which word.

An Example

Example

Here is an example written in C# by myself.

Main Class

Data Classes

Test System

The system the code will run on is following:

Arch Linux
RunTime you need (if available; Please add in answer)
Intel i7-4700MQ 3.4GHz
16GB RAM

How do I test

After the code is compiled I'll run a bash script that runs your program a certain amount of times and calculates the average and median run time.

Good Luck and may the best code win.

My Benchmark: Not completed after 8-9 hours of runtime.

My Benchmark (after changing some words):

mean: 39.5157
median: 39.448687194

PS: Here is the originally planned input, which took ages with my program. Grammars are slightly changed in the new input and words are way shorter.

As the code is rather long, it can be found here (Java 8): http://pastebin.com/Q5Buuqfx

How I did it:

Instead of brute-force creating the possible word combinations and then try to find a match I instead did the reverse and tried to collapse the target word to find the starting point. As a result the path the algorithm has to traverse is much less branched, and the words from the example can all be verified in about 35 ms (on my machine).

As a side-effect of the reverse-search I do not need the first two lines of each task (variables, terminals).

In addition I utilize the Java 8 streaming technology, which allows to easily activate parallel processing with just a single change in one line of code.

Usage: java Grammar <inputFile>

Edit: Did some code cleanup and further speed tests and it ironically turned out, that the algorithm is so fast, that setting up the parallel stream takes longer than the actual task. I now use a single-CPU stream() instead and the complete example input set is processed in ~35 ms on my machine instead of ~80 ms if I use parallelStream().

Edit2: Further testing reveals some strange effects with parallelStream and certain types of Collections. A TreeSet seems to work best in both single and parallel processing. I did some tests on your extended input set and it seems to work fine, except for the task with the looping rules (CD->DC,DC->CD). Detecting and removing those would cause the search to verify instantly.


Stewie's sequence: + * - / + * - / Let's use the four basic operations, addition +, multiplication *, subtraction - and division / (float, not integer).

Stewie's sequence is defined as follows:

x = [x(1), x(2)]    // Two initial numbers (one indexed)
x(3) = x(1) + x(2)
x(4) = x(2) * x(3)
x(5) = x(3) - x(4)
x(6) = x(4) / x(5)
x(7) = x(5) + x(6)
... and so on.

Challenge:

Take two non-negative integers (x(1), x(2)), and one positive integer N as input.

x(1) and x(2) will be the two first numbers of your sequence, and N will be the length of the sequence you must output. (You can choose to have the list 0-based, in which case N will be one less than the length).

You can not assume that x(2) >= x(1).
N will always be >2 if 1-based, (>1 if 0-based).
You do not have to handle division by zero errors.

Note the 2nd test case. You will not get 0, 1, and N=6 as input, since that will result in division by zero, but you must support 0, 1 and N=5.

Assume only valid input will be given.
The input and output can be on any convenient format, but you must support at least 3 digits after the decimal points if the output is non-integer.

Test cases:

1 3
8
1, 3, 4, 12, -8, -1.5, -9.5, 14.25

0 1
5
0, 1, 1, 1, 0     // N=6 would give division by zero error. You don't need to handle that case.

1 0
9
1, 0, 1, 0, 1, 0, 1, 0, 1

6 3
25
6, 3, 9, 27, -18, -1.5, -19.5, 29.25, -48.75, -0.6, -49.35, 29.61, -78.96, -0.375, -79.335, 29.7506, -109.086, -0.272727, -109.358, 29.825, -139.183, -0.214286, -139.398, 29.8709, -169.269

Haskell, 69 68 64 bytes

x#n=take n$x++zipWith3 id(cycle[(+),(*),(-),(/)])(x#n)(tail$x#n)

x1 and x2 are taken as a list. Usage example: [1,3] # 8 -> [1.0,3.0,4.0,12.0,-8.0,-1.5,-9.5,14.25].

Laziness makes it possible to define an infinite recursive list where we take the first n elements.

Haskell, 66 bytes

(h%g)y x=x:g(h x y)y
a=(+)%b
b=(*)%c
c=(-)%d
d=(/)%a
(.a).(.).take

Different approach, slightly longer. Argument order is N, x2, x1. Usage example: ( (.a).(.).take ) 8 3 1 -> [1.0,3.0,4.0,12.0,-8.0,-1.5,-9.5,14.25].

Defines 4 functions a, b, c and d which take two arguments y, x  and make a list by putting x in front of a call to the next function with y as the second argument and x op y as the first. For example a is: a y x = x : (b (x+y) y), b does multiplication: b y x = x : (c (x*y) y), etc.

Edit: @Michael Klein saved a byte in the 1st variant (#). Luckily I also found one byte for the second variant, so both have the same length again.

Edit II: @Zgarb found 2 bytes in the second version to save, and I 4 in the first, so they are no longer of the same length.


Toasty, Burnt, Brûlée! It turns out that my toaster is a tad broken. It lost WiFi (You know, it's one of those newfangled smart toasters), and its been going bonkers! Since it no longer works, I've been having to hack into my breakfast's source code and run Plate.bread.toastAs(3); every morning. Will you help?

My toaster takes one input: the amount of time you want to toast your bread. This is written as min:sec, such as 5:45 or 0:40 (Up to 59:59). It then returns a specific value for different levels of toastiness:

0:00-0:30 = Bread
0:31-1:00 = Warm Bread
1:01-2:00 = Toasty
2:01-3:30 = Burnt
3:31 and up = Brûlée (or Brulee)

But here's the catch: my toaster has a broken keyboard! Your code can't contain any semicolons or...colons. This might be harder than the toaster repairman said it would be...

Here are some test cases, so you can...test your cases?

0:00 = Bread
5:50 = Brulee or Brûlée
2:00 = Toasty
ChicknMcNuggets = Anything
-1:00 = Anything
0:60 = Anything
1 = Anything
60:00 = Anything
1:00:00 = Anything

Standard Loopholes are prohibited
All Acceptable Forms of Input/Output are accepted
My Toaster's new code cannot contain a semicolon (;) or colon (:)
This is code-golf, so the shortest answer (in each language) wins!

Python 2, 124  118 116

t=eval(input().replace("\x3A","."))
print["Bread","Warm Bread","Toasty","Burnt","Brulee"][sum([t>3.3,t>2,t>1,t>.3])]

Try it online!

-6 with thanks to @tsh and also thanks for tho TIO test cases.

-2 with a couple of cool tips from @BlackOwlKai

Throws a ValueError for invalid inputs that cannot be converted to a float. For numbers less than 0 it returns "Bread" because it is still bread. Guess if we are really strict on ensuring that the input is a valid time it could be done but for me the interesting bit was how to avoid the : in Python.


Golfing out the haters The setup:
A social network reports the number of votes a post has in two ways: the number of net upvotes (total upvotes - total downvotes), and the % of votes that were upvotes, rounded to the nearest integer (.5 rounds up).  The number of net upvotes is an integer (not necessarily positive), and the second is guaranteed to be an integer between 0 and +100 inclusive.  The number of upvotes and the number of downvotes are both either zero or positive 32-bit integers (you can specify signed or unsigned).  Assume that if there are zero total votes, the percentage upvoted is reported as zero.
The challenge:
Given these two integers (net upvotes and % upvoted), what is the shortest program you can write which determines the lowest number of total upvotes the post received, with all the constraints above satisfied?
Input constraints are guaranteed. If the input does not satisfy the constraints above, the program behavior is up to you. Bonus kudos if it doesn't enter an infinite loop or otherwise crash. Consider returning a negative number if you want more guidance.
General rules:

This is code-golf, so the shortest valid solution (measured in bytes) wins.
Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.  Bonus kudos for a client-side Web language like Javascript.
If you have interesting solutions in multiple languages, post them separately.
Standard rules apply for your answer, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, or full programs. Your call.
Default loopholes are forbidden.
If possible, please add a link with a test for your code.
Also, please add an explanation of how the code works.
Keep in mind that if you are doing an integer division operation that truncates (e.g. 20/3=6) rather than rounds, that might not be fully correct.
Additional test cases that explore the edge cases in the above constraints are welcome.
While the expected return type is numeric, boolean "false" can be used in place of 0.

Example test cases:
The first column is just a reference number included to facilitate discussion.
ref net  %up    answer
1   0    0   => 0
2   -5   0   => 0
3   -4   17  => 1
4   -3   29  => 2
5   -2   38  => 3
6   -1   44  => 4
7   0    50  => 1
8   5    100 => 5
9   4    83  => 5
10  3    71  => 5
11  2    63  => 5
12  1    56  => 5
13  1234 100 => 1234
14  800  90  => 894  (tip: don't refer to this as the "last test case;" others may be added.)

JavaScript (ES6), 47 bytes

Takes input in currying syntax (n)(p), where n is the number of net upvotes and p is the percentage of upvotes. May return false for 0.

n=>p=>(g=u=>u/(u-n/2)*50+.5^p?g(u+1):u)(n>0&&n)

Try it online!

Commented

n => p => (          // given n and p
  g = u =>           // g = recursive function taking u = number of upvotes
    u / (u - n / 2)  //   compute u / (total_votes / 2)
    * 50 + .5        //   turn it into a percentage, add 1/2
    ^ p ?            //   XOR it with p, which gives 0 if the integer parts are matching
                     //   if the result is not equal to 0:
      g(u + 1)       //     try again with u + 1
    :                //   else:
      u              //     stop recursion and return u
)(n > 0 && n)        // initial call to g() with u = max(0, n)

Edge cases

Let Fn(u) = u / (u - n / 2) * 50 + 0.5

If u = 0 and n = 0, then Fn(u) = NaN and Fn(u) XOR p = p. So, we return u = 0 if n = p = 0 (first iteration of the first test case) or continue with the recursion if p != 0 (first iteration of the 7th test case).
If u > 0 and u = n / 2, then Fn(u) = +Infinity and -- again -- Fn(u) XOR p = p. Unless p = 0, we just go on with the next iteration. (This happens in the 9th and 11th test cases.)


Implement an 8 bit adder The Challenge

Implement a function which accepts two integers whose values range from 0 - 255 and returns the sum of those integers mod 256. You may only use bitwise negation (~), bitwise or (|), bit shifting operators (>>,<<), and assignment (=).

Things you cannot use include (but are not limited to)

Addition, subtraction, multiplication, and division
Loops
Conditional statements
Function calls

Fewest uses of binary or, binary negation, and bit shift operations wins. In the event of a tie, the most popular solution wins. As always, standard loopholes apply.

Here is an example of a simple 2-bit adder. It uses 77 binary negations, 28 binary ors, and 2 bit-shifts for a total score of 107 (this can be seen by running the C preprocessor with gcc -E). It could be made much more efficient by removing the #defines and simplifying the resulting expressions, but I've left them in for clarity.

#include <stdio.h>

#define and(a, b) (~((~a)|(~b)))
#define xor(a, b) (and(~a,b) | and(a,~b))

int adder(int a, int b)
{
    int x, carry;
    x = xor(and(a, 1), and(b, 1));
    carry = and(and(a, 1), and(b, 1));
    carry = xor(xor(and(a, 2), and(b, 2)), (carry << 1));
    x = x | carry;
    return x;
}

int main(int argc, char **argv)
{
    int i, j;
    for (i = 0; i < 4; i++) {
        for (j = 0; j < 4; j++) {
            if (adder(i, j) != (i + j) % 4) {
                printf("Failed on %d + %d = %d\n", i, j, adder(i, j));
            }
        }
    }
}

Update: Added example and changed scoring critera


Format the given number of bytes to a human readable format Challenge and origin

On Stack Overflow a popular question is: How to convert byte size into human readable format in java? The most up voted answer has a quite nice method for doing this, but this is codegolf and we can do better, can't we?

  Your challenge is to write a method or program that coverts the given
  number of bytes to the correct human readable format and prints the
  result to the standard out of your language.*

*See the rules for more clarification!

Input

The input will always be a positive number of bytes with a maximum of (2^31)-1.

Output

You may choose if you prefer the International System of Units or the binary notation as output (the SI notation probably saves you some bytes).

SI:      B, kB,  MB,  GB
Binary:  B, KiB, MiB, GiB

Note: Higher units than GB or GiB are not posible due to the restricted input range.

Example output

International System of Units:

Input       Output
0           0.0     B
999         999.0   B
1000        1.0     kB
1023        1.0     kB
1024        1.0     kB
1601        1.6     kB
160581      160.6   kB
4066888     4.1     MB
634000000   634.0   MB
2147483647  2.1     GB

Binary:

Input       Output
0           0.0     B
999         999.0   B
1000        1000.0  B
1023        1023.0  B
1024        1.0     KiB
1601        1.6     KiB
160581      156.8   KiB
4066888     3.9     MiB
634000000   604.6   MiB
2147483647  2.0     GiB

Rules

Build-in functions for byte formatting are not allowed!
The output should always be in the same notation standard, you may not mix SI or binary;
The output should always be in the largest unit possible where the
resulting number is still higher or equal to one;
The output should always have one decimal number, but you may choose
to print an integer number when the resulting output is in bytes (B);
You may choose if you would like to add a space, tab or nothing between the number and the unit;
Input is received via STDIN or function parameters;
Output is printed to the console or returned as string (or similar character container);
This is code golf, so the shortest answer wins. Have fun!

Edit: Even more clarification

Some numbers have interesting rounding behaviors like the number 999950. Most code implementations would return 1000.0 kB instead of 1.0 MB. Why? Because 999950/1000 evaluates to 999.950 which is effectively rounded to 1000.0 when using String.format in Java (in most other languages too). Hench some extra checks are needed to handle cases like this.

For this challenge both styles, 1000.0 kB and 1.0 MB are accepted, although the last style is preferred.

Pseudo code / java test code:

public static String bytesToSI(long bytes){
      if (bytes < 1000){
          return bytes + ".0 B";
      }
      //Without this rounding check:
      //999950    would be 1000.0 kB instead of 1.0 MB
      //999950000 would be 1000.0 MB instead of 1.0 GB
      int p = (int) Math.ceil(Math.log(bytes) / Math.log(1000));
      if(bytes/Math.pow(1000, p) < 0.99995){
          p--;
      }
      //Format
      return String.format("%.1f %sB", bytes/Math.pow(1000, p), "kMGTPE".charAt(p-1));
}

TI-BASIC, 44

Would be the right tool for the job if TI-BASIC had halfway decent string manipulation (I had to resort to overwriting the exponent of the number, displayed in engineering notation, with the unit). As it is it rounds and outputs correctly, but it's not even close to winning entries. Maybe a different calculator language could win this one?

Fix 1
Eng
ClrHome
Disp Ans
Output(1,15,sub(" kMG",1+iPart(log(Ans+.5)/3),1)+"B

Input in the form [number]:[program name] on the homescreen.

Given test cases:

Input       Output (leading spaces intentional; screen clear before each output)
0                      0.0 B
999                  999.0 B
1000                   1.0kB
1023                   1.0kB
1024                   1.0kB
1601                   1.6kB
160581               160.6kB
4066888                4.1MB
634000000            634.0MB
2147483647             2.1GB


Invert a Minesweeper Board Minesweeper is a popular computer game that you have probably wasted time playing where you try to reveal the cells that are mines in a rectangular grid based on hints of how many neighboring mines each non-mine cell has. And in case you haven't played it, do so here.
A nifty mathematical fact about a Minesweeper grid (a.k.a. board) is that:

A board and its complement have the same mine total number. (Proof)

That is to say that if you have a completely revealed Minesweeper grid, the sum all the numbers on that grid, i.e. the mine total, will equal the mine total of the complement of the grid, which is the grid where every mine has been replaced with a non-mine and every non-mine replaced with a mine.
For example, for the Minesweeper grid
**1..
34321
*2**1

the mine total is 1 + 3 + 4 + 3 + 2 + 1 + 2 + 1 = 17.
The grid's complement is
24***
*****
3*44*

which has mine total 2 + 4 + 3 + 4 + 4 = 17 again.
Write a program that takes in an arbitrary Minesweeper grid in text form where * represents a mine and 1 through 8 represent the number of mines adjacent to a non-mine cell. You can use . or 0 or   (space) to represent cells with no mine neighbors, your choice. You can assume that the input grid will be correctly marked, i.e. each non-mine cell will accurately denote the total number of mines immediately adjacent to it orthogonally or diagonally.
Your program needs to print the complement of the grid in the same format (using the same ., 0, or   as you expected in the input).
The shortest code in bytes wins.

Instead of a program you may write a function that takes the input grid as a string and prints or returns the complement grid.
A trailing newline in the input or output is fine, but there should be no other characters besides those that form the grid.
You can assume a 1×1 grid will be the smallest input.

Test Cases
All inputs and outputs could be swapped as the complement of the complement is the original grid. The grids can be rotated as well for further test cases.
Input:
111
1*1
111

Output:
***
*8*
***

Input:
.

Output:
*

Input:
*11*1.1**1...1***1.....1*****1..........

Output:
1**2***11*****1.1*******1...1***********

Input: (Cut The Knot example)
**212*32
333*33**
1*22*333
222222*1
*33*2232
2**22*2*

Output:
24***4**
***7**64
*8**7***
******8*
4**7****
*33**5*3

CJam, 58 57 bytes

0WX]2m*qN/{'*f+z}2*f{\~@m<fm<W<}:..+{W<{_'*#'*@'*-,?}/N}/

Input should not end with a linefeed. Output contains 0 for cells without nearby mines.

Try it online in the CJam interpreter.

Idea

We start by padding the input matrix with one row and one column of asterisks.

For input

*4*
**2

this results in

*4**
**2*
****

Now we generate all possible modifications that result of rotating the rows and columns 0, -1 or 1 units up/left:

*4** **** **2* **4* **** ***2 4*** **** *2**
**2* *4** **** ***2 **4* **** *2** 4*** ****
**** **2* *4** **** ***2 **4* **** *2** 4***

We discard the "padding locations" from each rotation, i.e.,

*4* *** **2 **4 *** *** 4** *** *2*
**2 *4* *** *** **4 *** *2* 4** ***

and form a single matrix by concatenating the corresponding characters of each rotation:

******4** 4*******2 **24*****
*******4* *4****2** 2***4****

The first character of each position is its original character.

If it is a non-asterisk, it has to be replaced with an asterisk.
If it is an asterisk, the number of non-asterisks in that string is the number of neighboring mines.

How it works

0WX]2m*   e# Push the array of all vectors of {0,-1,1}^2.
qN/       e# Read all input from STDIN and split at linefeeds.
{'*f+z}2* e# Append a '*' to each row and transpose rows with columns. Repeat.
f{        e# For each vector [A B], push the modified input Q; then:
  \~      e#   Swap Q with [A B] and dump A and B on the stack.
  @m<     e#   Rotate the rows of Q B units up.
  fm<     e#   Rotate each row of the result A units left.
  W<      e#   Discard the last row.
}         e# This pushes all nine rotations with Manhattan distance 1.
:..+      e# Concatenate the corresponding characters for each position.
{         e# For each row:
  W<      e#   Discard the character corresponding to the last column.
  {       e#   For each remaining string:
    _'*#  e#     Find the first index of '*' in a copy.
    '*    e#     Push '*'.
    @'*-, e#     Count the non-asterisks in the string.
    ?     e#     Select '*' if the index is non-zero, the count otherwise.
  }/      e#
  N       e#   Push a linefeed.
}/        e#


Matching homologous groups Homologous series, any of numerous groups of chemical compounds in each of which the difference between successive members is a simple structural unit.
As an example, Alkane is a homologous group where the chemical compounds are in \$C_nH_{2n+2}\$ format. \$CH_4\$ (Methane) is part of the Alkane group because \$CH_4 \to C_{1}H_{2\cdot 1+2}\$ and there because there is \$n=1\$ carbon atom, so there should be \$2n+2\$ hydrogen atoms. And there is \$2×1+2 = 4\$ hydrogen atoms. So Methane or \$CH_4\$ qualifies for the Alkane group.
In this challenge we will be matching against 6 homologous groups:

Alkane          : \$C_nH_{2n+2}\$
Alkene          : \$C_nH_{2n}\$
Alkyne          : \$C_nH_{2n-2}\$
Alcohol         : \$C_nH_{2n+1}OH\$
Aldehyde        : \$C_nH_{2n+1}CHO\$
Carboxylic Acid : \$C_nH_{2n+1}COOH\$

Input format will be like CH_4 \$ \to CH_4\$, CH_3CHO \$ \to CH_3CHO \$, meaning that you need to write the subscript using an underscore (_). Output should be the group the compound belongs to.
Test Cases
CH_4 -> Alkane
C_2H_4 -> Alkene
C_2H_2 -> Alkyne
CH_3OH -> Alcohol
CH_3CHO -> Aldehyde
CH_3COOH -> Carboxylic Acid

Standard loopholes apply, shortest code wins. Input is guaranteed to be in these 6 categories and valid. Output needs to be exactly capitalized as in question. \$n\$ can be less than 2 (if it is omitted assume it is 1). There will be no leading zeros in \$n\$.

Python 3, 134 bytes
-3 bytes thanks to @tsh
Note that it fails for CH_2. It is unclear whether such a test case is valid, but I will keep this solution for now.

lambda e:['Aldehyde','Alcohol','Carboxylic Acid',0][e[::-1].rfind('O')]or'Alk%sne'%'eay'[eval(e.translate({67:45,72:43,95:43})+'//2')]

Try it online!
Python 3, 137 bytes
Works for all cases including CH_2.

lambda e:['Aldehyde','Alcohol','Carboxylic Acid',0][e[::-1].rfind('O')]or'Alk%sne'%'yae'[eval(e.translate({67:43,72:43,95:'~-'})+'//-2')]

Try it online!


Split arrays and programs in half Introduction

You have been tasked to write a program that splits a rectangular integer array evenly in half (for whatever reason).
This task is computationally intensive, but luckily you have a dual-core machine to perform the calculations.
To maximize the benefits of parallelism, you decide to split the program evenly in half and let each core run one of the parts independently of the other.

Input and output

Your input is a rectangular 2D array of nonnegative integers of size at least 1×1, taken in any reasonable format.
A splitting of such an array is obtained by splitting each horizontal row into a prefix and a suffix (either of which may be empty).
For a splitting to be valid, two adjacent rows must be split at the same index or adjacent indices.
For example, consider the array

2 4 5 5 6 3
9 7 1 7 7 0
0 0 3 6 7 8
1 2 4 7 6 1
6 6 8 2 0 0

This is a valid splitting:

 2;4 5 5 6 3
;9 7 1 7 7 0
;0 0 3 6 7 8
 1;2 4 7 6 1
 6 6;8 2 0 0

This is also a valid splitting:

2 4 5 5 6 3;
9 7 1 7 7;0
0 0 3 6 7;8
1 2 4 7;6 1
6 6 8;2 0 0

This is not a valid splitting:

2 4;5 5 6 3
9 7 1;7 7 0
0;0 3 6 7 8
1 2;4 7 6 1
6 6;8 2 0 0

Your output shall be the minimum value of

abs(sum_of_prefixes - sum_of_suffixes)

over all valid splittings of the input.

Rules and scoring

You shall write two programs (either full programs or functions) in the same language, which must not have any shared code between them.
Let's call them P1 and P2.
Program P1 takes the input array, and outputs something.
Program P2 takes this something as input, and outputs the answer of the above task for the input array.

Your score is the maximum of the byte counts of P1 and P2, lower score being better.

Some clarifications:

You can write two full prorgams, one function and one full program, or two functions.
In the case of two full programs, the entire output of P1 is fed to P2 as input, as in the Unix pipeline P1 | P2. The programs must function correctly if compiled/interpreted from two separate source files.
If either program is a function, it is converted to a full program by adding the necessary boilerplate code, and the above rule is applied to it. In particular, two functions cannot use shared auxiliary functions, shared import statements, or shared global variables.

Test cases

[[1]] -> 1
[[4,5],[8,3]] -> 4
[[8],[11],[8],[10],[4]] -> 1
[[5,7,0,9,11,2,1]] -> 7
[[146,194,71,49],[233,163,172,21],[121,173,14,302],[259,169,26,5],[164,30,108,37],[88,55,15,2]] -> 3
[[138,2,37,2],[168,382,33,77],[31,199,7,15],[192,113,129,15],[172,88,78,169],[28,6,97,197]] -> 7
[[34,173,9,39,91],[169,23,56,74,5],[40,153,80,60,28],[8,34,102,60,32],[103,88,277,4,2]] -> 0
[[65,124,184,141],[71,235,82,51],[78,1,151,201],[12,24,32,278],[38,13,10,128],[9,174,237,113]] -> 2
[[164,187,17,0,277],[108,96,121,263,211],[166,6,57,49,73],[90,186,26,82,138],[173,60,171,265,96]] -> 8

Haskell, 102 bytes

Function 1 (102 bytes):

l=length
[]#i=[[]]
(r:s)#i=id=<<[(splitAt j r:)<$>s#j|j<-[i-1..i+1],j>=0,j<l r]
f r=(r#)=<<[0..l$r!!0]

Function 2 (90 bytes):

g::[[([Int],[Int])]]->Int
g a=minimum$map(\(x,y)->abs$sum(sum<$>x)-sum(sum<$>y))$unzip<$>a

Missing boilerplate for F1 to make it a full program, including the hardcoded integer array to check:

main = print $ f [[164,187,17,0,277],[108,96,121,263,211],[166,6,57,49,73],[90,186,26,82,138],[173,60,171,265,96]]

and for F2:

main = print . g . read =<< getContents

Now you can call runhaskell f1.hs | runhaskell f2.hs which outputs 8.

How it works: f takes a list of list of integers.

f r = (r#)=<<[0..l$r!!0]          -- for each index [0 .. length r] call # with
                                  -- the first parameter being r and
                                  -- collect the results in a single list

[]#i=[[]]                         -- base case. If the list of lists is empty, stop
(r:s)#i                           -- else let r be the first list, s all others
           j<-[i-1..i+1],         -- foreach possible index j for the next line
                 j>=0,j<l r       --    (skipping out of range indices)
     (splitAt j r:)<$>            -- split the current line at j into a pair of
                                  -- lists and prepend it to every element of
                      s#j         -- a recursive call with s and j
id=<<                             -- flatten into a single list

Now we have a list of all possible splits, for example the first one and a random one from the middle

[([],[164,187,17,0,277]),                  [([164,187],[17,0,277]),
 ([],[108,96,121,263,211]),                 ([108,96],[121,263,211]),
 ([],[166,6,57,49,73]),                     ([166],[6,57,49,73]),
 ([],[90,186,26,82,138]),                   ([90,186],[26,82,138]),
 ([],[173,60,171,265,96])]                  ([173,60,171],[265,96])]

Function g takes such a list and

                    unzip<$>a       -- turn every pair of lists into a list of pairs
  map(\(x,y)->                      -- foreach such pair
      abs$sum(sum<$>x)-sum(sum<$>y) -- calculate the score
minimum                             -- and find the minimum

Note: the second function can be golfed a little bit more, but it doesn't change the score.


Length-encode a string Suppose we use the following rules to pull a single string from another string, one containing only ASCII printable characters and called an *-string. If the string runs out before the process halts, that is an error, and the result of the process is undefined in that case:

Start with d=1, s=""
Whenever you encounter a *, multiply d by 2. Whenever you encounter another character, concatenate it to the end of s and subtract 1 from d. If now d=0, halt and return s

Defined Examples:

d->d
769->7
abcd56->a
*abcd56->ab
**abcd56->abcd
*7*690->769
***abcdefghij->abcdefgh

Undefined Examples: (note that the empty string would be one of these as well)

*7
**769
*7*
*a*b
*

Your job is to take a string and return the shortest *-string that produces that string.

Program Examples:

7->7
a->a
ab->*ab
abcd->**abcd
769->*7*69

Your program should handle any string containing at least one character and only non-* ASCII printable characters. You can never return strings for which the process is undefined, since by definition they cannot produce ANY strings.

Standard loopholes and I/O rules apply.

JavaScript (ES6), 61 bytes

f=(s,d=2)=>s?d>s.length?s[0]+f(s.slice(1),d-2):'*'+f(s,d*2):s

Recursive function that does the following:

If d is less than or equal to remaining string length divided by 2:

Append * to output and multiply d by 2
Else:

Shift the string and append to output, subtract 1 from d.

See it in action:

f=(s,d=2)=>s?d>s.length?s[0]+f(s.slice(1),d-2):'*'+f(s,d*2):s

input.oninput = e => output.innerHTML = f(input.value);
<input id="input" type="text"/>


String Permutations - case and order Challenge
For any string that is composed of alphabetical characters of any case, make a function that returns a list of all of it's variations, order and case-wise empty strings returns empty list.
Test Cases

"" -> []
"a" -> ['a', 'A']
"ab" -> ['ab', 'Ab', 'aB', 'AB', 'ba', 'Ba', 'bA', 'BA']
"abc" -> ['abc', 'Abc', 'aBc', 'ABc', 'abC', 'AbC', 'aBC', 'ABC', 'bac', 'baC', 'bAc', 'bAC', 'Bac', 'BaC', 'BAc', 'BAC', 'CBa', 'CBA', 'cba', 'cbA', 'cBa', 'cBA', 'Cba', 'CbA', 'caB', 'cAb', 'cAB', 'cab', 'CaB', 'CAb', 'CAB', 'Cab', 'Acb', 'AcB', 'acb', 'acB', 'aCb', 'aCB', 'ACb', 'ACB', 'Bca', 'BcA', 'bca', 'bcA', 'bCa', 'bCA', 'BCa', 'BCA']
'aa' -> ['aa', 'Aa', 'aA', 'AA']  (for duplicate letters extra, duplicate permutations are allowed if necessary)
As the permutations rack up quickly you only need to handle up to 4 ASCII letter chars.
This is code-golf, so the shortest code in bytes wins!

Python 2, 89 bytes

lambda s:map(list,map(permutations,product(*zip(s.swapcase(),s))))
from itertools import*

Try it online!

Doesn't work in Python 3. Swap case idea from HyperNeutrino.


Finding the most 'unique' word Using you language of choice, write the shortest function/script/program you can that will identify the word with the highest number of unique letters in a text.

Unique letters should include any distinct character using UTF-8 encoding.

Upper and lower case versions of the same character are different and distinct; 'a' != 'A'

Words are bound by any whitespace character.
'Letters' are any symbol which can be represented by a single unicode character.
The text document must be read in by your code -- no preloading/hard-coding of the text allowed.
The output should be the word, followed by the count of unique letters.

llanfairpwllgwyngyllgogerychwyrndrobwllllantysiliogogogoch - 18
Any delimiter/spacing between the two values is up to you, so long as there is at least one character to separate them.

In the event more than one word exists with the highest count, print all words for that count, with one new line delimiting.

superacknowledgement - 16
pseudolamellibranchiate - 16
This is code golf, so shortest code wins.

This answer on English.SE inspired me to create this challenge. The example uses just a word list, but any text should be able to be processed.

APL (56)

{⎕ML←3⋄⊃{⍵,⍴∪⍵}¨W[⍙]⍴⍨↑+/∆∘.=∆←∆[⍙←⍒∆←↑∘⍴∘∪¨W←⍵⊂⍨⍵≠' ']}

This is a function (question says that's allowed) that takes a string and returns a matrix of words and unique lengths.

Usage:

      {⎕ML←3⋄⊃{⍵,⍴∪⍵}¨W[⍙]⍴⍨↑+/∆∘.=∆←∆[⍙←⍒∆←↑∘⍴∘∪¨W←⍵⊂⍨⍵≠' ']}'The quick brown fox jumps over the lazy dog.'
quick 5
brown 5
jumps 5

Explanation:

⎕ML←3: set migration level to 3 (so that ⊂ is partition instead of enclose)
W←⍵⊂⍨⍵≠' ': store in W the given string, where each partition consists of non-whitespace characters.
⍙←⍒∆←↑∘⍴∘∪¨W: get the amount (⍴) of unique (∪) elements in each part (¨) of W, and store these in ∆, then get the sort order when sorted downwards on this (⍒) and store that in ⍙.
∆[⍙...]: sort ∆ by ⍙, so now we have the unique lengths in order.
∆∘.=∆←∆: store the sorted ∆ back in ∆, and see which elements of ∆ are equal.
↑+/: sum the rows (now we know how many elements are equal to each element) and then take the first item (now we know how many elements are equal to the first element, i.e. how many of the words are tied for first place.)
W[⍙]⍴⍨: sort W by ⍙, and take the first N, where N is the number we just calculated.
{⍵,⍴∪⍵}¨: for each of these, get the word itself and the amount of unique characters in the word
⊃: format as matrix


Return the first N primes With a twist; your algorithm has to be less complex than O(X2) where X is the Nth prime. Your solution post should include the character count and the theoretical complexity in terms of X (or N, which ~= X/ln(X) and so will usually be more efficient)

Here's a hint solution in C# (O(Xln(sqrt(X))), 137 chars):

   public List<int> P(int n){var r = new List<int>{2}; int i=3; while(r.Count<n) if(!r.TakeWhile(x=>x<Math.Sqrt(i)).Any(x=>i%x==0)) r.Add(i++); else i++; }

J, 4 characters
p:i.

Usage:
   p:i.10
2 3 5 7 11 13 17 19 23 29

The problem with using J here is that I don't really know how efficient it is. I'd assume that as a language specialising in "mathematical, statistical, and logical analysis of data", that the algorithm used to generate the primes is pretty good.
I did look at the C source for clues, but it turns out that the C source for J is almost as unreadable as J itself. :-)
(The file is called v2.c for anyone who wants to have a look)