Simulating Exploding Dice Your task is to make a program that takes in an integer n > 1, and outputs the roll of a single n-sided die. However, this dice follows the rules for exploding dice.

When you roll the die, check what value you rolled. If you got the maximum for that kind of die (on a standard d4 that would be 4, or 6 on a d6, etc.), roll again and add the new roll to that total. Each roll continues adding to the total, until you don't roll the max number anymore. That final number is still added though.

Your program should take in a single integer n, and roll the exploding n-sided die. Here's an example distribution to show what it should look like for n=4. Note that you should never output any multiples of n, since they will always explode.

You can assume the stack size for any recursion you do is infinite, and your random function must meet our standards for randomness (built-in random generator or time/date). Your random function should also be as uniform as possible, vs. something like a geometric distribution, since these are dice we're talking about.

x86 Machine Code (for Intel Ivy Bridge and later), 17 bytes

31 C9 0F C7 F0 31 D2 F7 F6 42 01 D1 39 F2 74 F2 C3

The above bytes of code define a function that simulates an exploding die. It takes a single input, passed in the ESI register, indicating the maximum number of the die. It returns a single value in the ECX register, which is the result of the rolls.

Internally, it uses the RDRAND instruction to generate a random number. This uses a random number generator (RNG) that is built into the hardware on Intel Ivy Bridge processors and later (some AMD CPUs also support this instruction).

The logic of the function is otherwise quite straightforward. The generated random number is scaled to lie within the desired range using the standard technique ((rand % dieSize) + 1), and then it is checked to see if it should cause an explosion. The final result is kept in an accumulator register.

Here is an annotated version showing the assembly language mnemonics:

           unsigned int RollExplodingDie(unsigned int dieSize)
31 C9        xor     ecx, ecx    ; zero-out ECX, which accumulates the final result
           Roll:
0F C7 F0     rdrand  eax         ; generate a random number in EAX
31 D2        xor     edx, edx    ; zero-out EDX (in preparation for unsigned division)
F7 F6        div     esi         ; divide EDX:EAX by ESI (the die size)
                                 ;   EAX receives the quotient; EDX receives the remainder
42           inc     edx         ; increment the remainder
01 D1        add     ecx, edx    ; add this roll result to the accumulator
39 F2        cmp     edx, esi    ; see if this roll result should cause an explosion
74 F2        jz      Roll        ; if so, re-roll; otherwise, fall through
C3           ret                 ; return, with result in ECX register

I am cheating a bit. All standard x86 calling conventions return a function's result in the EAX register. But, in true machine code, there are no calling conventions. You can use any registers you want for input/output. Using ECX for the output register saved me 1 byte. If you want to use EAX, insert a 1-byte XCHG  eax, ecx instruction immediately before the ret instruction. This swaps the values of the EAX and ECX registers, effectively copying the result from ECX into EAX, and trashing ECX with the old value of EAX.

Try it online!

Here's the equivalent function transcribed in C, using the __builtin_ia32_rdrand32_step intrinsic supported by GCC, Clang, and ICC to generate the RDRAND instruction:

#include <immintrin.h>

unsigned int RollExplodingDie(unsigned int dieSize)
{
    unsigned int result = 0;
Roll:
    unsigned int roll;
    __builtin_ia32_rdrand32_step(&roll);
    roll    = ((roll % dieSize) + 1);
    result += roll;
    if (roll == dieSize)   goto Roll;
    return result;
}

Interestingly, GCC with the -Os flag transforms this into almost exactly the same machine code. It takes the input in EDI instead of ESI, which is completely arbitrary and changes nothing of substance about the code. It must return the result in EAX, as I mentioned earlier, and it uses the more efficient (but larger) MOV instruction to do this immediately before the RET. Otherwise, samezies. It's always fun when the process is fully reversible: write the code in assembly, transcribe it into C, run it through a C compiler, and get your original assembly back out!


The Fatal Error Challenge Objective

Write a routine that accepts a string of printable ASCII characters, s, and returns a string containing the same characters as s,  reordered so that no two-character substring appears more than once. The program must process all benchmark strings (see below) in under one minute each on a modern computer. I will also award a special bonus of 50 rep to the lowest scoring answer that processes any valid 30-character string in under one minute.

For example, given the input Mississippi, a valid output would be issiMspiips (no two-character substrings appear twice), while an invalid output would be ipMsispiiss (since the substring is appears twice).

The routine may take the form of:

a complete program reading from stdin (or equivalent) or the command line, and outputting to stdout (or equivalent)
a function accepting a single string argument and returning a string

You may assume that the input string always admits at least one valid output.

The Challenge

Your routine must comprise 5 or more lines of code separated by newlines. Empty lines (which includes lines containing only whitespace) are ignored in all contexts and do not count towards total line count.

Swapping any two lines in your source code must produce a fatal error. By "fatal error", we refer to any of the following conditions:

the source code fails to compile, with the compiler/interpreter declaring a fatal error
the routine aborts with a runtime fatal error or an unhandled runtime exception
the routine is forced into an abrupt, abnormal program termination that produces no output of any kind except for a possible error message and/or stack dump

Alternatively, contiguous blocks of code containing no newline characters may be used in place of lines. These blocks should each be displayed on their own line in the source file, with the understanding that newlines are stripped out before the source code is compiled/interpreted.

For example, the code

aaaa
bbbb
cccc

would condense to

aaaabbbbcccc

before being evaluated.

In this mode, the fatal error condition applies to swapping any two code blocks (and thus to swapping lines in the source code before newlines are stripped out). Hence in the above example the routines aaaaccccbbbb, bbbbaaaacccc, and ccccbbbbaaaa must all produce fatal errors, either at compiletime or runtime.

Submissions using this alternative mode should declare its use.

Scoring

Let n be the number of non-empty textlines in your source file, with n ≥ 5. Let c be the number of bytes comprised by the longest textline (by byte length) in your source file, not counting any trailing newline.

A submission's score is given by c(n + 10).

The submission with the lowest score is the winner.

Best of luck. ;)

Benchmark Strings

Abracadabra Alacazam
Is Miss. Mississauga Missing?
Ask Alaska's Alaskans
GGGGAAAATTTTCCCCgggaaatttccc
A Man A Plan A Canal Panama

PHP, score = 289 (17×(7+10))

PHP's built-in functions make it quite easy to do this badly. The following code just shuffles the string until a valid result is obtained:

function f($s){
while(preg_match(
'/(..).*?\1/',$s)
+preg_match('/(.'
.')\1\1/',$s))$s=
str_shuffle(
$s);return $s;}

Benchmarks

Average and maximum execution times calculated using the following code:

$s = 'Mississippi';
$t_total = 0;
$t_max = 0;
for ($i=0; $i<10; $i++) {
  $t0 = microtime(true);
  echo f($s);
  $t = microtime(true) - $t0;
  printf("  %10.7f\n",$t);
  $t_total += $t;
  if ($t > $t_max) $t_max = $t;
}
printf("Avg: %10.7f secs; Max: %10.7f secs\n",$t_total/$i, $t_max);

Results:

Mississippi: Avg:  0.0002460 secs; Max:  0.0005491 secs
Anticonstitutionnellement: Avg:  0.0001470 secs; Max:  0.0002971 secs
Pneumonoultramicroscopicsilicovolcanoconiosis: Avg:  0.0587177 secs; Max:  0.1668079 secs
Donaudampfschiffahrtselektrizitatenhauptbetriebswerkbauunterbeamtengesellschaft*: Avg:  9.5642390 secs; Max: 34.9904099 secs
baaacadaeafbbcbdbebfccdcecfdde†: Avg:  5.0858626 secs; Max:  9.8927171 secs

* I changed ä to a to avoid multi-byte issues
† This was the hardest 30-character string I could come up with. It's actually the first 30 characters of the De Bruijn sequence for k='abcdef' and n=2, with the first 'b' moved to avoid an instant match.


Conways's Game of Life: Most newborn generating starting pattern General rules

The universe of the Game of Life is an infinite two-dimensional orthogonal grid of square cells, each of which is in one of two possible states, alive or dead. Every cell interacts with its eight neighbours, which are the cells that are horizontally, vertically, or diagonally adjacent. At each step in time, the following transitions occur:

Any live cell with fewer than two live neighbours dies, as if caused by underpopulation.
Any live cell with two or three live neighbours lives on to the next generation.
Any live cell with more than three live neighbours dies, as if by overpopulation.
Any dead cell with exactly three live neighbours becomes a live cell, as if by reproduction.

The initial pattern constitutes the seed of the system. The first generation is created by applying the above rules simultaneously to every cell in the seed—births and deaths occur simultaneously. The rules continue to be applied repeatedly to create further generations. (Source: Wikipedia )

Specific rules

For this challenge, we will modify a few rules:

The grid is not infinite. We will provide in the inputs the size of the grid. It will not act as a Torus nether.
The game stops when the grid reach a state it has already reached before. This prevents patterns infinite loop and can manage empty grids too.

Challenge

Write a program/function that takes four positive integer as input:

x: starting pattern width
y: starting pattern height
n: grid width
m: grid height

and finds the starting pattern that will generate the most amount of cells through the whole game, and outputs that number. (You can also outputs the corresponding pattern if needed)

The patterns is always centered on the grid. If you need to center with odd numbers, the pattern should be slightly closer to the upper left corner. Refer to that drawing for better understanding where the green area is the pattern already centered:

Specifications

Standard I/O rules apply.
Standard loopholes are forbidden.
This challenge is not about finding the shortest approach in all languages,  rather, it is about finding the shortest approach in each language.
Your code will be scored in bytes, usually in the encoding UTF-8, unless  - specified otherwise.
Explanations, even for "practical" languages, are encouraged.

Example

Let's do a small example together. For this example, the pattern size will be x = y = 3 and the grid size will be n = m = 3

The program will test any possible starting pattern. After running it, we find that the maximum amount of generated cells during one whole game is 11.

It is obtained following those steps:

Green cells are alive, lime cells are newborn and brown cells just died. One out of two grid is just the transition between two states. The starting pattern is the first state of the game, in the upper left corner. The game ended when there was no living cells left, but most of the time the game end with a repeating infinite pattern.

Here we can get to 11 by counting every lime cells during the transitions. It corresponds to the total amount of generated cells through the whole game.

Test cases

Input            Output

3 3 3 3          11,    *[[0, 0, 1], [1, 1, 0], [0, 0, 1]]
3 3 5 5          46,    *[[0, 0, 1], [1, 1, 1], [0, 0, 1]]
3 3 12 12        596,   *[[1, 0, 1], [1, 1, 1], [1, 1, 1]]
2 3 6 3          18,    *[[0, 1], [1, 1], [0, 1]]
3 2 5 5          34,    *[[0, 1, 0], [1, 1, 1]]
4 4 9 9          1067,  *[[1, 0, 1, 1], [1, 1, 0, 1], [0, 0, 0, 1], [1, 0, 1, 1]]

* not needed, just here to help you debugging

Good luck..

Disclaimer

Thank you @totallyhuman for your Fibonacci Sequence post, from which I borrowed the presentation style. I found it very clear and I hope you don't mind me using the same layout ;)

  This challenge differs from basic Game of Life implementation since
  it asks to test out every starting pattern possible, count the number of
  generated cells for each of those and check for infinite repeating
  pattern.

Pyth, 65 63 bytes

M}3-BGHeSm+F.n<VVM.:.ugVVuCmsM.:++0k03G2NNd)2muCm.[Hk0GQd^^U2EE

Test suite

Input is taken as:

n,m
x
y

On the input 3,3,12,12, I got 594, not 596, with the same grid as the OP, so I'm not sure what's up.

How it works:

^^U2EE: Generate all possible patterns

muCm.[Hk0GQd: Pad them to the appropriate size. Written as pad, rotate, repeat.

uCmsM.:++0k03G2N: Generate the number of live neighbors for each cells. Written as pad, take subsequences of size 3, sum them, rotate, repeat.

M}3-BGH ... gVV ... N: Pair that with the original grid, use both to calculate the new cells. We do this by checking whether live neighbors including the center, optionally minus whether it was alive, contains a 3. I really like this VV trick, so I wrote a helper function (M}3-BGH) so I could do it twice. (see below)

.u ... d): Do that until it stops changing, return all intermediate steps.

.: ... 2: Take all consecutive pairs.

<VVM: Map each pair to the number of new cells born. I'm particularly proud of <VVM, I thought that was very clever.

m+F.n: Map each grid to its total number of cells born.

eS: Max


Trim and Count the Decimals In this challenge, you will write a program to output how many decimal places are in the input string and trim the input if needed.

Examples

-12.32
2

32
0

3231.432
3

-34.0
0 -34

023
0 23

00324.230
2 324.23

10
0

00.3
1 0.3

0
0

-04.8330
3 -4.833

Rules

Input will be a string which can be taken through, STDIN, function arguments or the closest equivalent
Output can be through function return, STDOUT, or the closest equivalent.
There is no limit on the size for the input integer except for your languages maximum string length.
If the input has any unnecessary (leading or trailing) zeros:

You should take them out
Output the amount of decimal place in the new number
Output the new number separated by a separator (e.g. space, newline, comma)

Input will always match this RegEx: -?\d+(\.\d+)?, or if you don't speak RegEx:

There could be a - at the beginning implying a negative number. Then there will be at least one digit. Then there could be... a . and some more digits.
To check if an input is valid, check here

No Regex

This is code-golf so shortest code in bytes wins

Python 2, 165 180 bytes

At first I was thinking about writing my first Pyth program, got it to count the digits after the potential comma. But then I got quite annoyed, I don't know how you'd enjoy that language, guess it's just for winning purposes. Anyway here's my solution (edited since it didn't work for large numbers):

def t(i):
 o,a='',i
 while a[-1]=='0':
  a=a[:-1]
 while a[0]=='0':
  a=a[1:]
 if a[-1]=='.':a=a[:-1]
 if'.'in a:o=str(len(a)-a.index('.')-1)
 else:o='0'
 if a!=i:o+=" "+a
 print o

In case anybody wants to build on my work in Pyth: ~b@+cz"."" "1Wq@b_1"0"~b<b_1)plrb6 To see where you're at, you might want to insert a p between @+.


Find the diameter of a word graph Introduction

A popular word puzzle is to convert one word into another via a series of steps which replace only one letter and which always result in a valid word. For example, BAG can be converted to DOG via a path of five steps:

BAG -> BAT -> CAT -> COT -> COG -> DOG

Shorter paths also exist in this case; for example:

BAG -> BOG -> DOG

If one drew a graph whose vertices were labelled by words, with an edge between any pair of words that differ by one letter, then the shortest path from "BAG" to "DOG" would consist of two edges.

Challenge

You are to write a program which receives as input a "dictionary" of words which all have  the same length, representing all allowable words that can appear as steps along a path. It should output at least one "longest shortest path", that is, a path between two of the words which is:

no longer than any other path between those two words;
at least as long as the shortest possible path between any other pair of words in the list.

In the context of the graph described above, the length of such a path is the diameter of the graph.

In the degenerate case where none of the input words can be transformed into any of the others, output at least one path of length zero, that is, a single word.

Examples

The input ["bag", "bat", "cat", "cot", "dot", "dog"] should yield a path traversing all six words in that order (or reverse order), since the shortest path from "bag" to "dog" within this dictionary is the longest achievable, five steps.
The input ["bag", "bat", "bot" , "cat", "cot", "dot", "dog"] should yield the path "bag, bat, bot, dot, dog" and/or its reversal.
The input ["code","golf","male","buzz","mole","role","mold","cold","gold","mode"] should yield a path between "code and "golf".
The input ["one", "two", "six", "ten"] corresponds to a graph with no edges, so output one or more single-word (zero-length) paths.
If the input contains any two words of unequal length, the output is undefined.

Rules

Standard code golf rules apply
There will be multiple "shortest" paths. You must output at least one, but are free to output as many as you wish.
You are free to decide how the input dictionary is passed into your program.
Shortest code in bytes wins.

APL (Dyalog Classic), 84 80 77 76 74 66 61 bytes

{⍵⌷⍨{⍵,⍨⊃⍋(1≠a⌷⍨⊃⍵),⍪⍺⌷a}⍣d/⊃⍸a=d←⌈/512|,a←⌊.+⍨⍣≡9*⍨2⌊⍵+.≠⍉⍵}

Try it online!

input and output are character matrices

⍵+.≠⍉⍵ matrix of hamming-like distances between words

9*⍨2⌊ leave 0s and 1s intact, turn 2+ into some large number (512=29, used as "∞")

⌊.+⍨⍣≡ floyd&warshall's shortest path algorithm

⌊.+ like matrix multiplication but using min (⌊) and + instead of + and × respectively
⍨ use the same matrix on the left and right
⍣≡ repeat until convergence

d←⌈/512|, length of longest (not "∞") path, assigned to d

⊃⍸a= which two nodes does it connect, let's call them i and j

{⍵,⍨⊃⍋(1≠a⌷⍨⊃⍵),⍪⍺⌷a}⍣d/ reconstruct the path

{ }⍣d/ evaluate the { } function d times. the left arg ⍺ is always i. the right arg ⍵ starts as j and gradually accumulates the internal nodes of the path
(1≠a⌷⍨⊃⍵),⍪⍺⌷a build a 2-column matrix of these two vectors:

1≠a⌷⍨⊃⍵ booleans (0 or 1) indicating which nodes are at distance 1 to the first of ⍵
⍺⌷a distances of all graph nodes to ⍺

⊃⍋ index of the lexicographically smallest row
⍵,⍨ prepend to ⍵

⍵⌷⍨ index the original words with the path


is_gaussian_prime(z)? Task
Write a function that accepts two integers \$a,b\$ that represent the Gaussian integer \$z = a+bi\$ (complex number). The program must return true or false depending on whether \$a+bi\$ is a Gaussian prime or not.
Definition
\$a+bi\$ is a Gaussian prime if and only if it meets one of the following conditions:

\$a\$ and \$b\$ are both nonzero and \$a^2 + b^2\$ is prime
\$a\$ is zero, \$|b|\$ is prime and \$|b| = 3 \text{ (mod }4)\$
\$b\$ is zero, \$|a|\$ is prime and \$|a| = 3 \text{ (mod }4)\$

Details
You should only write a function. If your language does not have functions, you can assume that the integers are stored in two variables and print the result or write it to a file.
You cannot use built-in functions of your language like isprime or prime_list or nthprime or factor. The lowest number of bytes wins. The program must work for \$a,b\$ where \$a^2+b^2\$ is a 32bit (signed) integer and should finish in not significantly more than 30 seconds.
Prime list
The dots represent prime numbers on the Gaussian plane (x = real, y = imaginary axis):

Some larger primes:
(9940, 43833)
(4190, 42741)
(9557, 41412)
(1437, 44090)

C, 149 118 characters

Edited version (118 characters):

int G(int a,int b){a=abs(a);b=abs(b);int n=a*b?a*a+b*b:a+b,
d=2;for(;n/d/d&&n%d;d++);return n/d/d|n<2?0:(a+b&3)>2|a*b;}

This is a single function:

G(a,b) returns nonzero (true) if a+bi is a Gaussian prime, or zero (false) otherwise.

It folds the integer primality test into an expression n/d/d|n<2 hidden in the return value calculation. This golfed code also makes use of a*b as a substitute for a&&b (in other words a!=0 && b!=0) and other tricks involving operator precedence and integer division. For example n/d/d is a shorter way of saying n/d/d>=1, which is an overflow-safe way of saying n>=d*d or d*d<=n or in essence d<=sqrt(n).

Original version (149 characters):

int Q(int n){int d=2;for(;n/d/d&&n%d;d++);return n/d/d||n<2;}
int G(int a,int b){a=abs(a);b=abs(b);return!((a|b%4<3|Q(b))*(b|a%4<3|Q(a))*Q(a*a+b*b));}

Functions:

Q(n) returns 0 (false) if n is prime, or 1 (true) if n is nonprime. It is a helper function for G(a,b).
G(a,b) returns 1 (true) if a+bi is a Gaussian prime, or 0 (false) otherwise.

Sample output (scaled up 200%) for |a|,|b| ≤ 128:


Reverse-ish a string! Your task: write a program/function that when given a string containing only ASCII characters, outputs/returns the string in reverse-ish.

Example:

1) Input

Hello, World!

2) Number unique characters in input. (Input string separated by pipes (|) for readability)

H|e|l|l|o|,| |W|o|r|l|d|!
1 2 3   4 5 6 7   8   9 10

3) For duplicate characters, find the first occurrence of that character and number the duplicate character with the same number as the first.

H|e|l|l|o|,| |W|o|r|l|d|!
1 2 3 3 4 5 6 7 4 8 3 9 10

4) Reverse the string, but not the numbers.

!|d|l|r|o|W| |,|o|l|l|e|H
1 2 3 3 4 5 6 7 4 8 3 9 10

5) Delete the characters above repeat numbers. (Deleted characters represented with an asterisk.)

!|d|l|*|o|W| |,|*|l|*|e|H
1 2 3 3 4 5 6 7 4 8 3 9 10

6) Replace the deleted characters with the character that appears over the first occurrence of the number that the deleted character is over.

!|d|l|l|o|W| |,|o|l|l|e|H
1 2 3 3 4 5 6 7 4 8 3 9 10

7) Output

!dlloW ,olleH

Test cases:

Input -> Output
"Hello, World!" -> "!dlloW ,olleH"
"18464399" -> "99343488"
"Code Golf" -> "floG eloC"
"abcdefgABCDEFG" -> "GFEDCBAgfedcba"
"Mmm, marshmallows" -> "swwllwmhsrwm  mms"
"15147" -> "74751"

Pyth, 1 byte
X

Verify all the test cases.
Pyth has wonderful built-ins :-)

Pyth,  8  7 bytes
sm@_QxQ

Verify all the test cases.
How it works
This is the more interesting non-built-in approach.
sm@_QxQ  - Full program.

 m       - Map over the input.
  @_Q    - Get the index in the reversed input.
     xQ  - Of the first index of each character in the String.
s        - Join the list.


Permute a string using Bit-Reversal Previously, we computed the Bit-Reversal Permutation where we found how the order of indices would be permuted. In that case, we received an input n which was the order of the permutation of the indices where the length was 2n. However, this time, we are given a string of length m = 2k for some k. Now we want to apply the permutation indices of order k to a string.

Task

Your goal is to create a function or program that given a string where the length is a power of 2, output the permutation of it using bit-reversal.

As an example, the string 'codegolf' has length 8 which is a power of 2, that is 8 = 23. We learned in the previous challenge that the bit-reversal permutation of order 3 is [0, 4, 2, 6, 1, 5, 3, 7] which means that we select the characters from the input string using that order of indices.

Input                  Output
0 1 2 3 4 5 6 7        0 4 2 6 1 5 3 7
c o d e g o l f        c g d l o o e f

This is one possible method of solving this task. Since we do not require the order of indices as output, there may be shorter algorithms which avoid generating the indices and rely on permuting characters only.

Test Cases

Input = Output
"z" = "z"
"cg" = "cg"
"code" = "cdoe"
"golf" = "glof"
"codegolf" = "cgdlooef"
"aaaazzzz" = "azazazaz"
"LynngDaie dneers" = "Legendary Dennis"
"hieroglyphically" = "hpoaeillihglrcyy"
"Programming Puzzles N' Code-Golf" = "PliorNPGosgem zlrenda'uog  -mCzf"
"super spectacular dazzling dream" = "srenrzcrpdt sllau cg zueeaadpiam"

Rules

This is code-golf so the shortest code wins.
Builtins are allowed.
The input string will only be in ASCII. The length of the input string will always be a power of 2.

Haskell, 72 bytes

This is "permuting characters only", but is it shorter than a different approach?

s(a:b:c)|(x,y)<-s c=(a:x,b:y)
s n=(n,n)
r a|[_]<-a=a|(x,y)<-s a=r x++r y

s is a helper function to seperate the characters from even and odd positions, r is the bit reversal permutation function:

Prelude> r "codegolf"
"cgdlooef"


Given a string, Return its Cumulative Delta Related

Explanation

Given a string such as DCBA, convert it to ASCII ordinals, such as 68 67 66 65. Then, take the differences between each value, eg 67 - 68 = -1, 66 - 67 = -1... giving -1 -1 -1 Now as long as there is more than 1 left over value, repeat getting the differences.

For a 3 letter string, your pathway should be similar to

A   F   G
65  70  71
-5  -1
-4

And for a 5 letter string...

B   A   C   E   D   F
66  65  67  69  68  70
1   -2  -2  1   -2
3   0   -3  3
3   3   -6
0   9
-9

The Challenge

Take a string input through any Standard IO Method, and output the value of the cumulative delta as described above.

Test Cases

input: cows
output: 8

input: helloworld
output: 905

input: aaaaaa
output: 0

input: abcdef
output: 0

input: ghfie
output: 20

input: CODEGOLF
output: 185

Rules

Standard Loopholes Apply
The input will only consist of ASCII letters that are either all uppercase or all lowercase
Your code MUST work for both lower and upper case.
The input will contain at least 2 characters.
The output may be positive or negative, as long as its absolute value matches the absolute value of the cumulative delta.
This is marked as code-golf, as such, shortest answer in bytes wins!

Python 3, 71 bytes

s=input();k=r=0
for c in s:r=ord(c)-r*k/(len(s)-k);k+=1
print(round(r))

Test it on Ideone.

Alternate version, 58 bytes (inexact)

If an approximate result is enough – e.g., -904.9999999999993 ≈ -905 for input helloworld – then the following solution works as well.

f=lambda s,k=1:len(s)and-~-len(s)*f(s[1:],k+1)/k+ord(s[0])

Test it on Ideone.

Background

Proposition Let f be a variadic function that maps the code points s0, ⋯, sn to their cumulative delta with sign (-1)n, i.e.,

Then

Proof The statement is clearly true when n = 0. Suppose that it holds for n - 1, where n > 0.

By the recursive definition of f and the hypothesis,

By induction, the statement holds for all non-negative values of n.

How it works

Since

we can rewrite the proposition as follows.

The iterative implementation does precisely this. Numerators are computed by incrementing k, denominators by subtracting k from the length of the input string s, i.e., n+1.

Unfortunately, not all fractions will evaluate to integers, so the result is computed using floating point arithmetic and finally rounded to the nearest integer.

The recursive implementation does roughly the same, but it keeps track of the denominator via the auxiliary variable k and computes the numerator by subtracting 1 from the length of the remaining string (~-len(s)).


Write a program that always outputs "2012" - even if it's modified! This idea is not mine, though I don't know where it originated. I once met it in a programming contest very long ago (1998, if I remember correctly). The task is to write a program in your favorite language that outputs 2012 and only 2012. The catch is that the program must still output 2012 after any one of its characters is modified. The modification can be either insertion, deletion or replacement. Of course, the modification will be such that the program is still syntactically valid.

Since I don't know all the programming languages, I have to ask the audience to help me and test the answers submitted.

Added: Many have commented that my definition of acceptable modifications is too vague. Here's my second attempt: The allowed modifications will leave your program syntactically valid and will not cause it to crash. There, I think that should cover all the compile-time, link-time and run-time errors. Though I'm sure that there will be some odd edge case in some language anyway, so when that comes up we'll look at it individually.

C, 53 characters
main(){register*a="2012";(puts("2012"==a?a:"2012"));}

A bit longer than the scripting language answers, and follows the same basic principle. Relies on the fact that due to the constraints of C's syntax, the only letters that would be possible to change without making the program invalid are within the strings!
Edit: Shaved off 4 characters.
Reedit: Robustness increased, shaved off one character.
Re-redit: Longer, but more robust. Just try your & now! (Correctly this time).
Update: Shortened a bit; defeats most approaches seen so far.
Update: Changed int to void; should defeat the last possible approach to break it I can think of.
Update: I thunk of another approach; replacing the last a (may it rot) with 0; using two-letter names should deal with that problem.
Update: Last update revoked; assuming changes causing runtime errors are disallowed; a will work just fine.
Update: Backtracking some more; attempting to dereference *a will also segfault; so using void to tease a compile error out of it should not be necessary.
Update: And a final shortening; that relies on the string "2012" being placed at but one address (which is common); and that literal strings are read-only (also common).
Update: It cost me two characters, but I defeated your puny semi-colon!


Solve the Global Debt, the Code Golf way The leaders of the world have met and have finally admitted that the best (and only) way of resolving global economic woes is to take stock of how much they owe each other and just pay each other off with huge cheques. They have hired you (ironically, at the lowest contract rate possible) to work out the best means of doing so.

After much deliberation, and asking someone to draw a simple example they've come up with the following spec.

Each country is represented by their ISO 3166-1 alpha-2 code: US for the USA, AU for Australia, JP for Japan, CN for China and so on...

A ledger is drawn up as a series of country entries and the amounts
owing to each country.
Each country's entry starts off with their domain ID a colon, and how much they have in surplus/deficit (in billions of Euro), followed by a semicolon, then a coloned
comma-separated list of the countries and how much (in billions of
Euro) they owe.
If a country owes nothing to another country, no mention of that country is entered after that semicolon separator.
Deficits are indicated as negative numbers, surplus is indicated as a positive number.
Values can also be floats.
The ledger must be taken from STDIN. The end of the ledger is indicated by a carriage return on a blank line. The tally must be delivered to STDOUT.

An example of a ledger:

Input:
AU:8;US:10,CN:15,JP:3
US:14;AU:12,CN:27,JP:14
CN:12;AU:8,US:17,JP:4
JP:10;AU:6,US:7,CN:10

The system then works out how much each country owes and is owed and determines their surplus/deficit, for example, for AU:

AU = 8 (current surplus) -10 (to US) -15 (to CN) -3 (to JP) +12 (from US) +8 (from CN) +6 (from JP) = 6

When all the computing is done, a tally must be shown:

Output:
AU:6
US:-5
CN:35
JP:8

Your job is to create this system, capable of taking any number of ledger entries for any number of countries and capable of determining how much each country has in deficit/surplus when everything is paid out.

The ultimate test is for you to use your code to resolve the debt owed between the following countries in the test case below. These figures were taken from BBC News as of June 2011. (http://www.bbc.com/news/business-15748696)

For the purposes of the exercise, I have used their respective GDP as their current surplus... Please bear in mind that this is strictly an exercise in code quality assurance... there will be no talk of global economic resolution here in this question... If you want to talk economics I'm sure there's another subdomain in SE that handles it...

US:10800;FR:440.2,ES:170.5,JP:835.2,DE:414.5,UK:834.5
FR:1800;IT:37.6,JP:79.8,DE:123.5,UK:227,US:202.1
ES:700;PT:19.7,IT:22.3,JP:20,DE:131.7,UK:74.9,US:49.6,FR:112
PT:200;IT:2.9,DE:26.6,UK:18.9,US:3.9,FR:19.1,ES:65.7
IT:1200;JP:32.8,DE:120,UK:54.7,US:34.8,FR:309,ES:29.5
IE:200;JP:15.4,DE:82,UK:104.5,US:39.8,FR:23.8
GR:200;DE:15.9,UK:9.4,US:6.2,FR:41.4,PT:7.5,IT:2.8
JP:4100;DE:42.5,UK:101.8,US:244.8,FR:107.7
DE:2400;UK:141.1,US:174.4,FR:205.8,IT:202.7,JP:108.3
UK:1700;US:578.6,FR:209.9,ES:316.6,IE:113.5,JP:122.7,DE:379.3

Now, be the economic savior of the world!

Rules:

Shortest code wins... this is code-golf after all...
Please provide your output of the major test case with your code answer...


Implement bag operations A bag, also called a multiset, is an unordered collection. You can call it a set that allows duplicates, or a list (or an array) that is not ordered/indexed. In this challenge, you are asked to implement bag operations: addition, difference, multiplication, division, counting and equality test.

Operations

The specified operations may not be conventional.

addition combines two bags into one, conserving the total number of each value
[1,2,2,3] + [1,2,4] = [1,1,2,2,2,3,4]
difference removes from a bag each element of another bag, or does nothing if no such element
[1,2,2,4] - [1,2] = [2,4]  [1,2,3] - [2,4] = [1,3]
multiplication multiplies each element in the bag.
[1,2,3,3,4] * 3 = [1,1,1,2,2,2,3,3,3,3,3,3,4,4,4] 2 * [1,3] = [1,1,3,3]
division is an uncommon one: each n equal elements are put in n equal new bags, elements that cannot form an n-group remain in the bag. Return any one of the n new bags.
[1,1,2,2,2] / 2 = [1,2] [1,2,2,3,3,3] / 3 = [3]
counting counts how many divisor bags can be produced from the dividend bag
[1,1,2,2,2,2,3,3,3] c [1,2,3] = 2
equality test checks if two bags have the same numbers of each element
[1,2,2,3] == [3,2,1,2] = truthy [1,2,3] == [1,2,2,3] = falsy (can also use = for this)

If you are using your own symbols for the operators, please specify.

Formats

Bags will be displayed as lists of the form [1,1,2,3,4]. You can use any other bracket than square ones, or even use quotes, or nothing at all. The elements will be integers(mathematically, not necessarily int) for the purpose of this question. Bags do not have to be sorted.

The input format will be two bags or a bag and an integer, with an operator. You can specify your own format as long as it contains these three.

The output format should be a single bag of the same format.

Rules

you may not use built-in functions, operations or libraries (including the standard library) that already implement these; it's ok though to use list concatenation and multiplication since they are by definition list operations, not bag operations (which happen to basically do the same thing)
standard loopholes apply
shortest answer wins

Test cases

[1,2,2,3] + [1,2,4]
[1,1,2,2,2,3,4]

[1,2,2,4] - [1,2]
[2,4]

[1,2,3] - [2,4]
[1,3]

[1,2,3,3,4] * 3
[1,1,1,2,2,2,3,3,3,3,3,3,4,4,4]

2 * [1,3]
[1,1,3,3]

[1,1,2,2,2] / 2
[1,2]

[1,2,2,3,3,3] / 3
[3]

[1,1,2,2,2,2,3,3,3] c [1,2,3]
2

[3,2,1,2] == [1,2,2,3]
truthy

[1,2,3] == [1,2,2,3]
falsy

APL (155)

∆←{O←⍺⍺⋄'+'=O←⎕CR'O':R[⍋R←⍺,⍵]⋄'-'=O:⍺{⍵≡⍬:⍺⋄(⍺/⍨(⍳⍴⍺)≠⍺⍳⊃⍵)∇1↓⍵}⍵⋄(⍬≡⍴⍵)∧K←'×'=O:⍵/⍺⋄K:⍺/⍵⋄'÷'=O:∪⍺⌿⍨⍵≤+/⍺∘.=⍺⋄'⊂'=O:⍵{(∪⍺)≢∪⍵:0⋄1+⍺∇⍵-∆⍺}⍺⋄⍺[⍋⍺]≡⍵[⍋⍵]}⋄⎕

This defines an operator ∆ 'bag', which defines bag operations for given functions. I.e. +∆ would be addition. It then reads a line from the keyboard and evaluates it as an APL expression.

The functions are:

+∆, addition
-∆, subtraction
×∆, multiplication
÷∆, division
⊂∆, counting
≡∆, equivalence (though due to golfing any unrecognized function will do equivalence)

Explanation:

∆←{...}: define an operator ∆:

O←⍺⍺: store the given function in O (⎕CR won't work with ⍺⍺ directly)
O←⎕CR'O': get the string representation of that function
'+'=O...:: for addition,

⍺,⍵: join the two lists together
R[⍋R←...]: and sort the result

'-'=O:: for subtraction,

⍺{...}⍵: run the following recursive function:

⍵≡⍬:⍺: if the subtrahend is empty, return the minuend
⍺/⍨(⍳⍴⍺)≢⍺⍳⊃⍵∇1↓⍵: otherwise, remove the first element of the subtrahend from both the subtrahend and the minuend and try again

(⍬=⍴⍵)∧K←'×'=O: for multiplication, and if the right argument is not a bag:

⍵/⍺: replicate each element in the left argument by the right argument

K:: ...and if the right argument is a bag:

⍺/⍵: replicate each element in the right argument by the left argument (this is so that multiplication is commutative)

'÷'=O:: for division,

⍵≤⍺∘.+⍺: see which elements in ⍺ occur at least ⍵ times,
⍺/⍨: select those from ⍺,
∪: and remove all duplicates from that list

'⊂'=O:: for counting,

⍵{...}⍺: run the following recursive function:

(∪⍺)≢∪⍵:0: if one list contains elements the other doesn't, the result is 0
1+⍺∇⍵-∆⍺: otherwise, subtract the dividend from the divisor, try again, and increment the result.

⋄: if none of the above, do the equivalence test:

⍺[⍋⍺]≡⍵[⍋⍵]: sort both lists and see if they are equal

⎕: read an expression from the keyboard, evaluate it, and output the result.

Test cases:

      ∆←{O←⍺⍺⋄'+'=O←⎕CR'O':R[⍋R←⍺,⍵]⋄'-'=O:⍺{⍵≡⍬:⍺⋄(⍺/⍨(⍳⍴⍺)≠⍺⍳⊃⍵)∇1↓⍵}⍵⋄(⍬≡⍴⍵)∧K←'×'=O:⍵/⍺⋄K:⍺/⍵⋄'÷'=O:∪⍺⌿⍨⍵≤+/⍺∘.=⍺⋄'⊂'=O:⍵{(∪⍺)≢∪⍵:0⋄1+⍺∇⍵-∆⍺}⍺⋄⍺[⍋⍺]≡⍵[⍋⍵]}⋄⎕
⎕:
      1 2 2 3 +∆ 1 2 4
1 1 2 2 2 3 4
      ∆←{O←⍺⍺⋄'+'=O←⎕CR'O':R[⍋R←⍺,⍵]⋄'-'=O:⍺{⍵≡⍬:⍺⋄(⍺/⍨(⍳⍴⍺)≠⍺⍳⊃⍵)∇1↓⍵}⍵⋄(⍬≡⍴⍵)∧K←'×'=O:⍵/⍺⋄K:⍺/⍵⋄'÷'=O:∪⍺⌿⍨⍵≤+/⍺∘.=⍺⋄'⊂'=O:⍵{(∪⍺)≢∪⍵:0⋄1+⍺∇⍵-∆⍺}⍺⋄⍺[⍋⍺]≡⍵[⍋⍵]}⋄⎕
⎕:
      1 2 2 4 -∆ 1 2
2 4
      ∆←{O←⍺⍺⋄'+'=O←⎕CR'O':R[⍋R←⍺,⍵]⋄'-'=O:⍺{⍵≡⍬:⍺⋄(⍺/⍨(⍳⍴⍺)≠⍺⍳⊃⍵)∇1↓⍵}⍵⋄(⍬≡⍴⍵)∧K←'×'=O:⍵/⍺⋄K:⍺/⍵⋄'÷'=O:∪⍺⌿⍨⍵≤+/⍺∘.=⍺⋄'⊂'=O:⍵{(∪⍺)≢∪⍵:0⋄1+⍺∇⍵-∆⍺}⍺⋄⍺[⍋⍺]≡⍵[⍋⍵]}⋄⎕
⎕:
      1 2 3 -∆ 2 4
1 3
      ∆←{O←⍺⍺⋄'+'=O←⎕CR'O':R[⍋R←⍺,⍵]⋄'-'=O:⍺{⍵≡⍬:⍺⋄(⍺/⍨(⍳⍴⍺)≠⍺⍳⊃⍵)∇1↓⍵}⍵⋄(⍬≡⍴⍵)∧K←'×'=O:⍵/⍺⋄K:⍺/⍵⋄'÷'=O:∪⍺⌿⍨⍵≤+/⍺∘.=⍺⋄'⊂'=O:⍵{(∪⍺)≢∪⍵:0⋄1+⍺∇⍵-∆⍺}⍺⋄⍺[⍋⍺]≡⍵[⍋⍵]}⋄⎕
⎕:
      1 2 3 3 4 ×∆ 3
1 1 1 2 2 2 3 3 3 3 3 3 4 4 4
      ∆←{O←⍺⍺⋄'+'=O←⎕CR'O':R[⍋R←⍺,⍵]⋄'-'=O:⍺{⍵≡⍬:⍺⋄(⍺/⍨(⍳⍴⍺)≠⍺⍳⊃⍵)∇1↓⍵}⍵⋄(⍬≡⍴⍵)∧K←'×'=O:⍵/⍺⋄K:⍺/⍵⋄'÷'=O:∪⍺⌿⍨⍵≤+/⍺∘.=⍺⋄'⊂'=O:⍵{(∪⍺)≢∪⍵:0⋄1+⍺∇⍵-∆⍺}⍺⋄⍺[⍋⍺]≡⍵[⍋⍵]}⋄⎕
⎕:
      2 ×∆ 1 3
1 1 3 3
      ∆←{O←⍺⍺⋄'+'=O←⎕CR'O':R[⍋R←⍺,⍵]⋄'-'=O:⍺{⍵≡⍬:⍺⋄(⍺/⍨(⍳⍴⍺)≠⍺⍳⊃⍵)∇1↓⍵}⍵⋄(⍬≡⍴⍵)∧K←'×'=O:⍵/⍺⋄K:⍺/⍵⋄'÷'=O:∪⍺⌿⍨⍵≤+/⍺∘.=⍺⋄'⊂'=O:⍵{(∪⍺)≢∪⍵:0⋄1+⍺∇⍵-∆⍺}⍺⋄⍺[⍋⍺]≡⍵[⍋⍵]}⋄⎕
⎕:
      1 1 2 2 2 ÷∆ 2
1 2
      ∆←{O←⍺⍺⋄'+'=O←⎕CR'O':R[⍋R←⍺,⍵]⋄'-'=O:⍺{⍵≡⍬:⍺⋄(⍺/⍨(⍳⍴⍺)≠⍺⍳⊃⍵)∇1↓⍵}⍵⋄(⍬≡⍴⍵)∧K←'×'=O:⍵/⍺⋄K:⍺/⍵⋄'÷'=O:∪⍺⌿⍨⍵≤+/⍺∘.=⍺⋄'⊂'=O:⍵{(∪⍺)≢∪⍵:0⋄1+⍺∇⍵-∆⍺}⍺⋄⍺[⍋⍺]≡⍵[⍋⍵]}⋄⎕
⎕:
      1 2 2 3 3 3 ÷∆ 3
3
      ∆←{O←⍺⍺⋄'+'=O←⎕CR'O':R[⍋R←⍺,⍵]⋄'-'=O:⍺{⍵≡⍬:⍺⋄(⍺/⍨(⍳⍴⍺)≠⍺⍳⊃⍵)∇1↓⍵}⍵⋄(⍬≡⍴⍵)∧K←'×'=O:⍵/⍺⋄K:⍺/⍵⋄'÷'=O:∪⍺⌿⍨⍵≤+/⍺∘.=⍺⋄'⊂'=O:⍵{(∪⍺)≢∪⍵:0⋄1+⍺∇⍵-∆⍺}⍺⋄⍺[⍋⍺]≡⍵[⍋⍵]}⋄⎕
⎕:
      1 1 2 2 2 2 3 3 3 ⊂∆ 1 2 3
2
      ∆←{O←⍺⍺⋄'+'=O←⎕CR'O':R[⍋R←⍺,⍵]⋄'-'=O:⍺{⍵≡⍬:⍺⋄(⍺/⍨(⍳⍴⍺)≠⍺⍳⊃⍵)∇1↓⍵}⍵⋄(⍬≡⍴⍵)∧K←'×'=O:⍵/⍺⋄K:⍺/⍵⋄'÷'=O:∪⍺⌿⍨⍵≤+/⍺∘.=⍺⋄'⊂'=O:⍵{(∪⍺)≢∪⍵:0⋄1+⍺∇⍵-∆⍺}⍺⋄⍺[⍋⍺]≡⍵[⍋⍵]}⋄⎕
⎕:
      3 2 1 2 ≡∆ 1 2 2 3
1
      ∆←{O←⍺⍺⋄'+'=O←⎕CR'O':R[⍋R←⍺,⍵]⋄'-'=O:⍺{⍵≡⍬:⍺⋄(⍺/⍨(⍳⍴⍺)≠⍺⍳⊃⍵)∇1↓⍵}⍵⋄(⍬≡⍴⍵)∧K←'×'=O:⍵/⍺⋄K:⍺/⍵⋄'÷'=O:∪⍺⌿⍨⍵≤+/⍺∘.=⍺⋄'⊂'=O:⍵{(∪⍺)≢∪⍵:0⋄1+⍺∇⍵-∆⍺}⍺⋄⍺[⍋⍺]≡⍵[⍋⍵]}⋄⎕
⎕:
      1 2 3 ≡∆ 1 2 2 3
0


Check printer - Convert to English text from the input value. Check printer function (or subroutine) - Convert to English text from the input value. 12.34 -> "twelve dollars and thirty four cents". For the range .01 to 9999.99 assuming valid input.

Common Lisp, 95

Newline not counted in:
(lambda(n &aux(d(floor n))(c(round(*(- n d)100))))
(format()"~R dollar~P and ~R cent~P"d d c c))

Sample use (assigning it to f):
CL-USER> (f .01)
"zero dollars and one cent"
CL-USER> (f 12.34)
"twelve dollars and thirty-four cents"
CL-USER> (f 9999.99)
"nine thousand nine hundred ninety-nine dollars and ninety-nine cents"


Mod 7 in Manufactoria A simple Manufactoria challenge.  Compute the input modulo 7.  The input will be in big-endian binary (blue=1, red=0).  The output should be in the same format.

Test cases provided.  The smallest part count wins.

http://pleasingfungus.com/Manufactoria/?ctm=Mod7;Input:_binary_number_big_endian._Output:_that_binary_number_mod_7;bbb:|brrr:b|brrrr:br|bb:bb|bbrrb:brr|brrrrb:brb|bbrb:bbr;13;3;1;

(if the input mod 7 is 0, output nothing.)

The algorithm is quite straightforward: Compute the modulus using a state machine (the largest part with eight branches - one of the states is duplicated for logistical purposes), then encode and collect the results. Since almost every result contains a one digit, an extra compression step is employed to reduce the amount of parts.

Designed in yEd, then transcribed to Manufactoria.

Uses way too many conveyer belts, in my opinion.


EOC Vault Password Rank 3 Puzzle - Vault Password The shortest reliable password testing code

Introduction

I started playing Empire of Code recently, and there was some challenge. The player is supposed to write a piece of Python or Javascript code to detect if the string passed to it is reliable password, that is, it contains at least one lowercase Latin letter, one uppercase Latin letter and one digit and has at least 10 characters.

It was quite easy for me to fit within the 130 characters limit for rank 3 using Javascript, however, I spent a lot of time trying to fit within the 100 characters limit for rank 3 using Python. Some guy said that he has managed to fit in 71 characters for Python. I tried hard but still couldn't reduce the code to less than 90 characters. Is it possible to use even less than 71 characters?

Winning condition:
The shortest Python code (or Javascript), which solves given problem, wins. You may assume whatever was assumed in the original problem description in the game, given below.

Remark: The solution should define a function or method called "golf" which takes the password as the first parameter and returns a boolean value indicating whether the given password satisfies the criterion.

  Challenge Vault Password
  [The following description is merged from two versions of the problem description (for Python and
  for Javascript), copied from the game site
  https://empireofcode.com/ ]

  We've installed a new vault to contain our valuable resources and
  treasures, but before we can put anything into it, we need a suitable
  password for our new vault. One that should be as safe as possible.

  The password will be considered strong enough if its length is greater
  than or equal to 10 characters, it contains at least one digit, as
  well as at least one uppercase letter and one lowercase letter. The
  password may only contain ASCII latin letters or digits, no
  punctuation symbols.

  You are given a password. We need your code to verify if it meets the
  conditions for a secure password.

  In this mission the main goal to make your code as short as possible.
  The shorter your code, the more points you earn. Your score for this
  mission is dynamic and directly related to the length of your code.

  Input: A password as a string.

  Output: A determination if the password safe or not as a boolean, or any data type that can be converted and processed as a boolean.
  When the results process, you will see the converted results.

  Example:

  golf('A1213pokl') === false

  golf('bAse730onE') === true

  golf('asasasasasasasaas') === false

  golf('QWERTYqwerty') === false

  golf('123456123456') === false

  golf('QwErTy911poqqqq') === true

  Precondition:

  0 < |password| ≤ 64

  The password matches the regexp expression "[a-zA-Z0-9]+"

  Scoring:

  Scoring in this mission is based on the number of characters used in
  your code (comment lines are not counted).

  Rank1:

  Any code length.

  Rank2:

  Your code should be shorter than 230 characters for Javascript code or
  shorter than 200 characters for Python code.

  Rank3:

  Your code should be shorter than 130 characters for Javascript code or
  shorter than 100 characters for Python code.

Python, 59 bytes
golf=lambda s:(9<len(s))*(s.lower()>s>s.upper())*'?'>min(s)

(Still) probably not optimal.


Make a Rectangle from a Triangle You can depict a triangular number, T(N), by writing one 1 on a line, then two 2's on the line below, then three 3's on the line below that, and so on until N N's. You end up with a triangle of T(N) numbers, hence the name.
For example, T(1) through T(5):
1

1
22

1
22
333

1
22
333
4444

1
22
333
4444
55555

To keep things nicely formatted we'll use the last digit of the number for N > 9, so T(11) would be:
1
22
333
4444
55555
666666
7777777
88888888
999999999
0000000000
11111111111

Now pretend like each row of digits in one of these triangles is a 1-by-something polyomino tile that can be moved and rotated. Call that a row-tile.
For all triangles beyond T(2) it is possible to rearrange its row-tiles into a W×H rectangle where W > 1 and H > 1. This is because there are no prime Triangular numbers above N > 2. So, for N > 2, we can make a rectangle from a triangle!
(We're ignoring rectangles with a dimension of 1 on one side since those would be trivial by putting every row on one line.)
Here is a possible rectangle arrangement for each of T(3) through T(11). Notice how the pattern could be continued indefinitely since every odd N (except 3) reuses the layout of N - 1.
N = 3
333
221

N = 4
44441
33322

N = 5
55555
44441
33322

N = 6
6666661
5555522
4444333

N = 7
7777777
6666661
5555522
4444333

N = 8
888888881
777777722
666666333
555554444

N = 9
999999999
888888881
777777722
666666333
555554444

N = 10
00000000001
99999999922
88888888333
77777774444
66666655555

N = 11
11111111111
00000000001
99999999922
88888888333
77777774444
66666655555

However, there are plenty of other ways one could arrange the row-tiles into a rectangle, perhaps with different dimensions or by rotating some row-tiles vertically. For example, these are also perfectly valid:
N = 3
13
23
23

N = 4
33312
44442

N = 5
543
543
543
541
522

N = 7
77777776666661
55555444433322

N = 8
888888881223
666666555553
444477777773

N = 11
50000000000
52266666634
57777777134
58888888834
59999999994
11111111111

Challenge
Your task in this challenge is to take in a positive integer N > 2 and output a rectangle made from the row-tiles of the triangles of T(N), as demonstrated above.
As shown above, remember that:

The area of the rectangle will be T(N).

The width and height of the rectangle must both be greater than 1.

Row-tiles can be rotated horizontally or vertically.

Every row-tile must be depicted using the last digit of the number it represents.

Every row-tile must be fully intact and within the bounds of the rectangle.

The output can be a string, 2D array, or matrix, but the numbers must be just digits from 0 through 9.
The output does not need to be deterministic. It's ok if multiple runs produce multiple, valid rectangles.
The shortest code in bytes wins!

Python 2, 59 bytes

n=input()
c=~n%2
while c<n:print`n%10`*n+`c%10`*c;n-=1;c+=1

Try it online!

Prints like:

55555
44441
33322

It looks kind-of redundant to update n-=1;c+=1 where sum n+c remains unchanged. I feel like there's a better way, but I haven't seen it so far. Bounty is up for grabs!

60 bytes

n=input()
b=a=n/2
while n-b:b+=1;print`a%10`*a+`b%10`*b;a-=1

Try it online!

Prints like:

22333
14444
55555

Based on ideas by @newbie.


Combined 100 year birthday I was recently adding up the ages of myself and my wife and kids and realised that at some point in the not-too-distant future our ages will all add up to exactly 100 years.
Challenge
For an input consisting of a combined (total) age and a list of birth dates, output the date on which the combined ages all add up to the given total.

Input combined age (in years) will be a positive integer
Input list of birth dates will be a list (whatever format is convenient for your language) of dates that must contain numerical representation of Day, Month and Year.  Number of days since a specific epoch is not acceptable.  You may assume the list of input dates is sorted in chronological order.
Output will be a single date in the same format as input dates
For the purposes of the combined age, 1 year is considered to be exactly 365.25 days
For some inputs, it will be impossible to find a date after all the birth dates when they all add up to the combined age.  For instance consider two birth dates that are 20 years apart, but we want a combined of 10 years.  In that case, the output would be the 10th birthday of the older birth date.  In other words, individual ages are considered to be 0 for all dates before that individual's birth date
The output will be the first date on which the combined ages add up to at least the input age
You may use built-in date-time functions
You must support dates going back as far as 1970/01/01.

Examples
Here I'm giving all dates in YYYY/MM/DD format, but you may whatever format you like.
Input                                               Output

 10  2000/01/01                                     2010/01/01
100  1975/03/05,1978/07/23,2008/11/12,2012/12/20    2018/11/22
100  1975/03/06,1978/07/23,2008/11/12,2012/12/20    2018/11/23
100  1975/03/09,1978/07/23,2008/11/12,2012/12/20    2018/11/23
100  1975/03/10,1978/07/23,2008/11/12,2012/12/20    2018/11/24
  3  1990/08/01,1995/07/02                          1993/08/01
 50  1975/03/05,1978/07/23,2008/11/12,2012/12/20    2001/11/13

Note that in the last two examples, the output date lies within the range of input dates, as per rule 5.

Mathematica 138 107 237 bytes
My first attempts were sloppy and unworthy. This should work generally, provided that the birth dates are given in order of earliest to latest, as in the test cases.
The test cases were well-chosen and difficult to implement correctly.
The code turned out way longer than I had hoped.
The general logic is to

Solve for x (in days) such that the distance from x to each date of birth sums to the target passage of time (e.g 100 years converted to days).
If the earliest date + x days > latest date of birth, remove the latest date of birth and repeat step (1), Else move to (3).
Return (earliest date + x days)

t_~f~d_:=If[DateDifference[a=DateObject[DatePlus[d[[1]],Solve[t 365.25==Tr@(x-Join[{0},
QuantityMagnitude@(DateDifference[d[[1]],#,"Day"]&/@Rest@d)]),{x}][[1,1,2]]]/.
{y_,m_,n_,h_}:>{y,m,n+1}],d[[-1]]]>Quantity[0,"Days"],f[t,Most@d],a]

Test Cases
f[10, {{2000, 1, 1}}]
f[100, {{1975, 3, 5}, {1978, 7, 23}, {2008, 11, 12}, {2012, 12, 20}}]
f[100, {{1975, 3, 6}, {1978, 7, 23}, {2008, 11, 12}, {2012, 12, 20}}]
f[100, {{1975, 3, 9}, {1978, 7, 23}, {2008, 11, 12}, {2012, 12, 20}}]
f[100, {{1975, 3, 10}, {1978, 7, 23}, {2008, 11, 12}, {2012, 12,  20}}]
f[3, {{1990, 8, 1}, {1995, 7, 2}}]
f[50, {{1975, 3, 5}, {1978, 7, 23}, {2008, 11, 12}, {2012, 12, 20}}]


Hilbert's binary Hotel In this challenge you will be asked to implement any function (or full program) that fulfills two properties.  Those properties are:

Your function must be an injective (reversible) function from the polynomials with non-negative integer coeffecients to the non-negative integers.  This means no two unequal inputs can map to an equal output.
Your function must preserve the total number of "on bits" from its input to its output.  This means if you count the 1 bits of each coefficient of the polynomial, their sum should be the same as the number of 1 bits in the binary representation of the output.  For example 9 is 1001 in binary so it has 2 1 bits.

IO

A non-negative integer polynomial is the same as a infinite list of non-negative integers such that after a certain point all the integers are zero.  Thus, polynomials may be represented either by infinite lists (although this is probably undesirable) or by finite lists with implicit zeros after the end of the list.

The key distinction between polynomials and finite lists is that adding a zero to the end of a list will change the list:

While adding a zero to the end of a polynomial does not change its value:

Thus if your function takes a finite list representing a polynomial as input, adding a zero must not change its result.

When representing polynomials as lists, you may represent them either with the first or last entry representing the constant term.  For example you could have either of the following possibilities:

In the first case, adding zeros to the end of the list should not change the result; in the second case, adding zeros to the front of the list should not change the result.

Of course if your language supports polynomials you may take those as inputs.

Output should be a non-negative integer output via any standard methods.

This is code-golf so answers will be scored in bytes, with fewer bytes being better.

Jelly, 8 bytes

BFṢḄæ«ÆẸ

Try it online!

Left inverse, 5 bytes

Bċ0ÆE

Try it online!

How it works

BFṢḄæ«ÆẸ  Main link. Argument: A (array)

B         Binary; convert each integer in A to base 2.
 F        Flatten; concatenate the resulting binary arrays.
  Ṣ       Sort the resulting bit array.
   Ḅ      Convert from base 2 to integer, yielding an integer x with as much set
          bits as there are set bits in A.
      ÆẸ  Unexponents; convert A = [a1, a2, ...] to y = (p1**a1 + p2**a2 + ...),
          where pn is the n-th prime number.
          By the fundamental theorem of arithmetic, the resulting integer is unique
          for each array A without trailing zeroes.
    æ«    Bitshift left; compute x * 2**y.


Make a simple IRC bot. Task

  Make a simple IRC bot which does simple task like greeting user.

Detail

(You may see this RFC document.)

Write a complete program that perform these:

The program inputs nickname and realname from the user.

All nickname and realname which form is [A-Za-z0-9]+ should be allowed, but it isn't  important whether other forms are allowed. For example, if the user wants 1234qwerty as nickname and 5319009 as realname, the program should use those names, but it isn't important whether the program can use ^^☆Rick Astley☆^^ (which includes non-alphabet&decimals) as (nickname or realname) or not, even thought this name may be rejected by the server.

The program inputs serverAddress from the user.

The form of serverAddress is serverIP:serverPort, where serverIP is the IP address of the server and serverPort is the port num of the server.

The program connects to port serverPort at IRC server serverIP, and it should set it's nickname as nickname and realname as realname by sending USER realname 0 * :realname and NICK nickname.
The program inputs a single channelName which doesn't include #, and join to the channel #channelName.
Send a private message Hello, world! to the #channelName channel like this: PRIVMSG #channelName :Hello, world!
Then, the program does these:

A. If someone joins, greeting him by saying Hello, @! to #channelName, where @ is the nickname of him/her.

B. If the program is kicked, try re-joining.

C. If a person is kicked or banned, say POW HAHA.

D. If a person leaves (PART or QUIT), say Goodbye, @!, where @ is the nickname of him/her.

E. If someone says some text including Turing test or turing test, say I'm a human!.

F. If someone says some text including 6*9, quit by sending QUIT :42 to the server.

G. If someone says some text including all your base are belong to us(case-insensitive), quit by sending QUIT :What you say! to the server.

H. If someone says some text preceding with a space and above acts aren't performed by the text, say the sum of charcode of all (except the first space) chars in the text.

If an error is occurred

If an error (such as connection error or invalid nickname) is occurred, you can do what you want to do. For example, if the nickname is already in use, the program may stop, gets a new nickname from the user, or automatically change the nickname and retry.

Restriction

The program

Should not use any internal functions or libraries which is for IRC client/bot making. i.e. something like IRC client libraries
Should prompt what it'll input, before it gets an input. For example, before inputs serverAddress, it should prompt Write the address of server:, serverIP:serverPort > , serverAddress >, or some text that the user can recognize.
Should work on several IRC servers using UTF-8. (i.e. not for single server)
's messages send to server shouldn't be NOTICE. (RFC 2812, 3.3.2 Notice : The difference between NOTICE and PRIVMSG is that automatic replies MUST NEVER be sent in response to a NOTICE message.)
Should send a message where the request came from (#channelName or nickname).
Should PONG when PINGed, of course.

PS

Well, I just made this, because there was no puzzle about IRC bot.

Edit

After reading @dmckee's comment, I changed the rule for choosing winner.

Default bonus = +0
If somehow the program can connect to a channel (even if it's not #channelName), bonus = 1
If the program can perform step 1~5, bonus *= 2.
For each tasks A~H in step 6, if the program implements, bonus *= 1.2.
For each six restrictions, if the program follows that, bonus *= 1.05.

and score = int(codelength/bonus).

Program with lowest score is winner. If two answers have same score, then the answer with highest votes wins.

EDIT Edit : I think 1.2 and 1.05 in step 4 and 5 should be adjusted slightly bigger.. What do you think about this?

The winner is decided, however, I think there was too few entries.

Anyone still may submit the code.. :P

Python - 125 points

304 chars
follows steps 1-5 (works for me on irc.freenode.net:6667. if you try there, remember IDENT might take a while, so give it 20+ seconds to connect and speak)
follows 4 restrictions (assuming the NOTICE restriction which is a bit unclear. the UTF restriction counts because python won't choke if it doesn't need to parse any UTF).

score math (python):

bonus = 1 # connects to channel
bonus *= 2 # steps 1-5
for i in xrange(4):
    bonus *= 1.05 # 4 restrictions

int(304.0/bonus)
> 125

code:

import socket
i=raw_input
u=i('user# ')
n=i('nick# ')
h,p=i('host:port# ').split(':',1)
p=int(p)
c='#'+i('chan# ')
z=0
while 1:
 try:
  def s(m): z.send(m+'\r\n')
  z.recv(9)
 except:
  z=socket.socket();z.connect((h,p));s('USER '+n+' 0 * :'+n);s('NICK '+n);s('JOIN '+c);s('PRIVMSG '+c+' :Hello, world!')


Alternating Fibonacci In the alternating Fibonacci sequence, you first start with 1 and 1 as usual.

However, instead of always adding the last two values to get the next number, you alternate starting with adding, and every other time you subtract instead.

The sequence starts like this:

1
1
2    # 1 + 1
-1   # 1 - 2
1    # 2 + -1
-2   # -1 - 1
-1   # 1 + -2
-1   # -2 - -1
-2   # -1 + -1
1    # -1 - -2
-1   # -2 + 1
2    # 1 - -1
1    # -1 + 2
1    # 2 - 1

etc.

Notice that after it starts over once it gets to 1 and 1 again.

Given a number N, print the Nth term of the alternating fibonacci sequence.

Remember, this is code-golf, so the code with the smallest number of bytes wins.

JavaScript (ES6), 25 bytes

n=>"334130110314"[n%12]-2

0-indexed. You can shorten the string with a slightly recursive version, though it adds 6 bytes:

f=n=>"3341301"[n]-2||f(13-n%12)

This is still shorter than the definitive recursive formula:

f=n=>n<2||f(n-2)+f(n-1)*(-n%2|1)


Scheduling a chess tournament Introduction
Right now I'm participating a chess tournament. I got inspired by the tournament schedule. Right now, I'm in a competition with three other players. That means with the four of us, we are playing 3 rounds. The schedule goes as following:
Round 1: 1-4 3-2
Round 2: 3-4 2-1
Round 3: 1-3 4-2

This is also known as Round Robin. Also, this is a valid schedule. We say that a schedule is valid, when it satisfies the following conditions:

Every player plays once against another player.
1-2 means that player 1 has white. Every player has or (N / 2 - 0.5) or (N / 2 + 0.5) times white, with N being the amount of rounds.

For example, in the above example, there are 3 rounds. So N = 3. As you can see, the amount of rounds equals the amount of players - 1. A player has either

N / 2 - 0.5 = 1 time white, or
N / 2 + 0.5 = 2 times white.

In the above example:

player 1 has 2 times white,
player 2 has 1 time white,
player 3 has 2 times white,
player 4 has 1 time white.

The task
Given an even integer > 1 representing the amount of players in the competition, output the tournament schedule.
Test cases:
Input = 4, that means N = 3
Input:     Output:
4          1-4 3-2
           3-4 2-1
           1-3 4-2

Input = 10, that means N = 9
Input:     Output:
10         1-10  2-9  3-8  4-7  5-6
           10-6  7-5  8-4  9-3  1-2
           2-10  3-1  4-9  5-8  6-7
           10-7  8-6  9-5  1-4  2-3
           3-10  4-2  5-1  6-9  7-8
           10-8  9-7  1-6  2-5  3-4
           4-10  5-3  6-2  7-1  8-9
           10-9  1-8  2-7  3-6  4-5
           5-10  6-4  7-3  8-2  9-1

Input = 12, that means N = 11
Input:     Output:
12         1-14    2-13   3-12   4-11   5-10   6-9    7-8
           14-8    9-7    10-6   11-5   12-4   13-3   1-2
           2-14    3-1    4-13   5-12   6-11   7-10   8-9
           14-9    10-8   11-7   12-6   13-5   1-4    2-3
           3-14    4-2    5-1    6-13   7-12   8-11   9-10
           14-10   11-9   12-8   13-7   1-6    2-5    3-4
           4-14    5-3    6-2    7-1    8-13   9-12   10-11
           14-11   12-10  13-9   1-8    2-7    3-6    4-5
           5-14    6-4    7-3    8-2    9-1    10-13  11-12
           14-12   13-11  1-10   2-9    3-8    4-7    5-6
           6-14    7-5    8-4    9-3    10-2   11-1   12-13
           14-13   1-12   2-11   3-10   4-9    5-8    6-7
           7-14    8-6    9-5    10-4   11-3   12-2   13-1

Of course, the extra whitespaces I used between the numbers is optional but not necessary. You may output it in any form you like, as long as it's readable.
Note: The above examples aren't just the only valid outputs. There certainly are more valid outputs.
This is code-golf, so the submission with the least amount of bytes wins!


Output with the same length always With challenges like Output with the same length as the code and Create output twice the length of the code, I thought of a separate, but similar challenge.

The task is to produce an output. It can either be a string, a list of characters, or whatever is the default output format of your program. However, your output must always be the same length, regardless of the input. And more importantly, the output should be different for different inputs.

Input

A single integer \$n\$, the ranges of which is determined by the choice of language. If your language has variable length integers, the range is \$-2^{31} \leq n < 2^{31}\$.

Output

A string or a list of characters, or a print to STDOUT or STDERR. You may only use one of these methods. The output should be of the same length regardless of the input, but it is up to you to define which length that is. The output may not contain the digit characters 0-9, or the minus sign -. The output should be deterministic.

You should be able to prove that for every output there is only one possible input, either by a formal proof, an argument, or a brute-force search.

This is a code golf question, so shave off any extraneous bytes. All languages are welcome, the more the better!

JavaScript (ES8), 33 bytes

Expects the input in the range of safe JS integers: \$-2^{53}\le n < 2^{53}\$.

Returns a string of 76 characters.

n=>btoa(n.toString(2)).padEnd(76)

Try it online!

How?

Step 1

The input is first converted to binary. This preserves the leading minus sign for negative numbers.

Examples:

123 → "1111011"
-77 → "-1001101"

Step 2

The resulting string is encoded in base-64.

It means that each block of 1 to 3 characters will be turned into a new block of 4 characters. This conversion is safe because none of the resulting blocks contain the forbidden symbols (digits or minus sign).

3-character blocks

"-10" -> "LTEw" | "011" -> "MDEx"
"-11" -> "LTEx" | "100" -> "MTAw"
"000" -> "MDAw" | "101" -> "MTAx"
"001" -> "MDAx" | "110" -> "MTEw"
"010" -> "MDEw" | "111" -> "MTEx"

A single final block of 1 or 2 characters has to be encoded if the length of the binary string is not a multiple of 3:

1-character blocks

"0"   -> "MA==" | "1"   -> "MQ=="

2-character blocks

"-1"  -> "LTE=" | "10"  -> "MTA="
"00"  -> "MDA=" | "11"  -> "MTE="
"01"  -> "MDE=" |

Step 3

The final output is padded with trailing spaces.


Obtain a number from 4 numbers using any combination of mathematical operations Given 4 numbers n1, n2, n3, n4, and a goal n5, obtain n5 using n1 through n4 combined with any operations.

Eg. Given four numbers 2,3,4,5 and the goal as 8, output (one of many) is 2-3+4+5

EDIT: This is a variation of a game played at my son's school. Paranthesis, powers, unary operations (log, factorial) are allowed; the expressions tend to get complicated.
However, unary operations can be applied only once on a number. Essentially, the tree should be:

                          goal
                           /\
                          /  \
                         /    \
                expression1   expression2
                   /\                /\
                  /  \              /  \
                 /    \            /    \
               term1  term2     term3  term4

where term#i  is either
1. one of the numbers, or
2. one of the numbers with an unary operation.

Python - 146 chars

from itertools import*
f=lambda*l:[s for s in((3*"%s%%s"+"%s")%a%o for o in product(*['+-/*']*3)for a in permutations(l[:4]))if eval(s)==l[4]]


Code golf ABC's: The ASCII Box Challenge Given two positive integers, 'a' and 'b', output an ascii-art "box" that is a characters wide and b characters tall. For example, with '4' and '6':

****
*  *
*  *
*  *
*  *
****

Simple right? Here's the twist: The border of the box must be the characters of "a" and "b" alternating. This starts at the top left corner, and continues in a clockwise spiral. For example, the previous example with 4 and 6 should be

4646
6  4
4  6
6  4
4  6
6464

A and B may be two-digit numbers. For example, the inputs "10" and "3" should output this:

1031031031
1        0
3013013013

In order to keep the output relatively small, you do not have to support three or more digit numbers. Also, since inputs are restricted to positive integers, '0' is an invalid input, which you do not have to handle.

Here are some more test cases:

Input: (3, 5)
Output:

353
5 5
3 3
5 5
353

Input: (1, 1)
Output:

1

Input: (4, 4)
Output:

4444
4  4
4  4
4444

Input: (27, 1)
Output:

271271271271271271271271271

Input: (1, 17)
Output:

1
1
7
1
1
7
1
1
7
1
1
7
1
1
7
1
1

Input: (12, 34):
Output:

123412341234
4          1
3          2
2          3
1          4
4          1
3          2
2          3
1          4
4          1
3          2
2          3
1          4
4          1
3          2
2          3
1          4
4          1
3          2
2          3
1          4
4          1
3          2
2          3
1          4
4          1
3          2
2          3
1          4
4          1
3          2
2          3
1          4
432143214321

You may take input and output in any reasonable format, and standard loopholes are banned. Since this is code-golf, the shortest answer in bytes wins!

Pyth, 65 51 bytes

juXGhHX@GhHeH@jkQ~hZ{s[+L]0UhQ+R]thQUeQ+L]teQ_UhQ+R]0_UeQ)m*;hQeQ
AQjuXGhHX@GhHeH@jkQ~hZ{s[,L0G,RtGH_,LtHG_,R0H)m*;GH

Try it online!


Divide into 2 isosceles triangles Given the measures of two of the interior angles of a triangle (x and y; the other angle can be easily calculated with 180 - x - y), draw a line segment that cuts this triangle into two isosceles triangles. You need to output the angle measures of both of your triangles.
However, because the base angles are the same, you only need to output the list [apex angle, base angle] of the divided triangles for both of the isosceles triangles. You can output the divided triangles in any order.
An example
Say your input is 100, 60.

Let's take a look at the complete triangle first. The triangle looks approximately like this.

   100

60            20

Now we try to divide one of the angles such that two divided triangles are both isosceles triangles.

       100

(40,20)           20

Now our bottom triangle is an isosceles triangle, since both of the base angles
of the bottom triangle are 20. The angle measures of the bottom triangle
looks approximately like this.

       140
20             20

Now, is the top triangle an isosceles triangle?

    100
          40
40

It is an isosceles triangle, because two of the angle measures are 40.

Therefore, for [100, 60], you need to output [[100, 40], [140, 20]].

Example cases
[20, 40] -> [[140, 20], [100, 40]]
[45, 45] -> [[90, 45], [90, 45]]
[36, 72] -> [[108, 36], [36, 72]]
[108, 36] -> [[108, 36], [36, 72]]
[44, 132] -> [[92, 44], [4, 88]]

Specifications

You can always assume that the triangle is dividable into two isosceles triangles.
You can output one of the many solutions of the cases; for example, you can also output [20, 40] -> [[100, 40], [20, 80]] for the first test case.

Python 3.8 (pre-release), 123 129 bytes

g=lambda*p:[[180-2*x,x]for x in p]
f=lambda a,b:((c:=180-a-b)==90or c>45>2in{a/b,b/a})*g(a,b)or(c/3in{a,b})*g(c/3,c/3*2)or f(b,c)

Try it online!
A function that takes in 2 angles, and returns the 2 isosceles triangles. If the given triangle cannot be divided, the function loops forever.


ASCII Doodling: Laser in a Box Sometimes when I'm doodling, I draw a rectangle, start with a diagonal from one of the corners, and then just trace out a line by "reflecting" it whenever I hit a side of the rectangle. I continue with this until I hit another corner of the rectangle (and hope that the aspect ratio of my rectangle was not irrational ;)). This is like tracing out the path of a laser shone into a box. You're to produce the result of that with ASCII art.

As an example, consider a box of width 5 and height 3. We'll always start in the top left corner. The # marks the boundary of the box. Note that the width and height refer to the inner dimensions.

#######    #######    #######    #######    #######    #######    #######
#\    #    #\    #    #\   \#    #\  /\#    #\  /\#    #\/ /\#    #\/\/\#
# \   #    # \  /#    # \  /#    # \/ /#    # \/ /#    #/\/ /#    #/\/\/#
#  \  #    #  \/ #    #  \/ #    # /\/ #    #\/\/ #    #\/\/ #    #\/\/\#
#######    #######    #######    #######    #######    #######    #######

The Challenge

Given the (positive) width and height of the box, you should produce the final result of tracing out the laser. You may write a program or function, taking input via STDIN (or closest alternative), command-line argument, function argument and output the result via STDOUT (or closest alternative), or via function return values or arguments.

You may use any convenient list, string or number format for input. The output must be a single string (unless you print it to STDOUT, which you may of course do gradually). This also means you can take the height first and the width second - just specify the exact input format in your answer.

There must be neither leading nor trailing whitespace on any line of the output. You may optionally output a single trailing newline.

You must use space, /, \ and # and reproduce the test cases exactly as shown.

Test Cases

2 2
####
#\ #
# \#
####

3 2
#####
#\/\#
#/\/#
#####

6 3
########
#\    /#
# \  / #
#  \/  #
########

7 1
#########
#\/\/\/\#
#########

1 3
###
#\#
#/#
#\#
###

7 5
#########
#\/\/\/\#
#/\/\/\/#
#\/\/\/\#
#/\/\/\/#
#\/\/\/\#
#########

22 6
########################
#\  /\  /\  /\  /\  /\ #
# \/  \/  \/  \/  \/  \#
# /\  /\  /\  /\  /\  /#
#/  \/  \/  \/  \/  \/ #
#\  /\  /\  /\  /\  /\ #
# \/  \/  \/  \/  \/  \#
########################

Pyth, 43 41 39 bytes

K*\#+2QKVvzp<*QXX*dyivzQN\\_hN\/Q\#\#)K

Try it online: Pyth Compiler/Executor. Input the numbers in the following order: height first line, width second line.

Thanks to isaacg, who helped saving two bytes.

Explanation:

My solution doesn't trace the laser, it uses a simple pattern that includes the gcd. If m, n are the dimensions of the box, let d = gcd(m, n). The size of the pattern is exactly 2*d x 2*d.

E.g. the repeating pattern for 7 5

#########
#\/\/\/\#
#/\/\/\/#
#\/\/\/\#
#/\/\/\/#
#\/\/\/\#
#########

is

\/
/\

(gcd(7, 5) = 1, size of pattern is 2 x 2)

And the repeating pattern for 22 6

########################
#\  /\  /\  /\  /\  /\ #
# \/  \/  \/  \/  \/  \#
# /\  /\  /\  /\  /\  /#
#/  \/  \/  \/  \/  \/ #
#\  /\  /\  /\  /\  /\ #
# \/  \/  \/  \/  \/  \#
########################

is

\  /
 \/
 /\
/  \

(gcd(22, 6) = 2, size of pattern is 4 x 4)

My solution does the following thing for each of the lines: it simply generates one line of the pattern, repeats it a few times and cut's it at the end so that it fit's into the box.

K*\#+2QK   implicit: Q is the second input number (=width)
K          K =
 *\#+2Q        "#" * (2 + Q)
       K   print K (first line)

Vvzp<*QXX*dyivzQN\\_hN\/Q\#\#)K  implicit: vz is the first input number (=height)
VQ                               for N in [0, 1, ..., vz-1]:
           ivzQ                             gcd(vz,Q)
          y                               2*gcd(vz,Q)
        *d                           string with 2*gcd(vz,Q) space chars
       X       N\\                   replace the Nth char with \
      X           _hN\/              replace the -(N+1)th char with /
    *Q                               repeat Q times
   <                   Q           only use the first Q chars
  p                     \#\#       print "#" + ... + "#"
                            )    end for
                             K   print K


The Image of the Dragon I saw a cool gif of the twin dragon curve made from a square, and wondered what would happen if we started from another base image.  So I wrote a program to do this.

It's so cool that I thought it would be fun to do it as a challenge.

Task

You will take in a square image with an edge length that is a power of 2 (greater than 4).

To make this image you should start by dividing your image into 4 vertical bands of equal size and shifting adjacent bands one 8th of the size of the image in opposite directions (shifted bands should wrap around to the other side).  You should then repeat this process each time splitting the image into twice as many divisions and shifting by half as far as the previous time.  Each iteration you should alternate between vertical and horizontal shifts.  You should iterate until the shift requires you to shift by a fractional number of pixels (this will always be 1/2) at which point you are done.

When shifting vertically odd numbered bands from the left (zero-indexed) should shift down while even shift up.  When shifting horizontally odd numbered bands from the top should shift left while even numbered bands should shift right.

You need only output/display the end result of the transformation, not all the intermediate steps like in the gif.

This is code-golf so the goal is to minimize the length of you source code as measured in bytes.

Worked through example

I will work through the cat gif shown at the top of the page frame by frame.

Here is the starting image:

This image is 512 by 512 pixels.  We will break it in 4 bands to start and shift each band by 1/8 the image size (64 pixels) vertically.

We will now divide it into twice as many bands (8 bands) and shift it half as far as last time (32 pixels).  This time we will shift horizontally.

We will now shift vertically again this time splitting into 16 bands and shifting each band by 16 pixels.

32 bands, 8 pixels, horizontal shift

64 bands, 4 pixels, vertical shift.

128 bands, 2 pixels, horizontal shift.

256 bands, 1 pixel, vertical shift.

Since the next shift would require us to move each band by half a pixel we will stop at this point and output the result.

Test cases

I have a working script that can make these images so I thought I would let you guys choose the images for the test cases.  So if you have a square image that is a power of 2 wide that you would like to see become dragonified.  Feel free to send it to me and I'll make it a test case.

You should also test on a plain white or solid black image so that you can determine whether or not pixels are disappearing or not.

MATLAB, 237 bytes

function A=r(A);n=size(A,1);p=@(a,v)permute(a,[v,3]);k=n/8;v=1:2;while k>=1;b=mod(0:n-1,4*k)<2*k;x=find(b);y=find(~b);c=[k+1:n,1:k;n-k+1:n,1:n-k];A=p(A,v);c=c(3-v,:);A(x,:,:)=A(x,c(1,:),:);A(y,:,:)=A(y,c(2,:),:);A=p(A,v);k=k/2;v=3-v;end

Took a little bit of guess work as I did not understand the procedure from the specs, but with the help of the image it worked.


Bitwise Operators in Brainfuck Your task is to create one brainfuck program for each of the following binary operators. Each program should take one or two 8-bit numbers (A and B) from input and calculate the specified operation:

A XOR B
A AND B
A OR B
A Shifted Left by 1 (circular shift)
NOT A

You do not have to implement all 5. Score is calculated by:

#totalCharacters + {4000 * #problemsNotCompleted}

So valid scores are from zero (best) to 20,000(nothing completed).

I don't care where you store the result, or whether or not you preserve the input. Assume 8-bit cells, and as many empty cells as you need to the right only.

You may assume the numbers are already in whatever memory location works best for you, so you don't need to worry about IO operations.


Locally invert a Polynomial Challenge

Given a polynomial p with real coefficients of order 1 and degree n, find another polynomial q of degree at most n such that (p∘q)(X) = p(q(X)) ≡ X mod X^(n+1), or in other words such that p(q(X)) = X + h(X) where h is an arbitrary polynomial with ord(h) ≥ n+1. The polynomial q is uniquely determined by p.

For a polynomial p(X) = a(n)*X^n + a(n+1)*X^(n+1) + ... + a(m)*X^m where n <= m and a(n) ≠ 0,a(m) ≠ 0, we say n is the order of p and m is the degree of p.

Simplification: You can assume that p has integer coefficients, and a(1)=1 (so p(X) = X + [some integral polynomial of order 2]). In this case q has integral coefficients too.

The purpose of this simplification is to avoid the issues with floating point numbers. There is however a non-integral example for illustration purposes.

Examples

Consider the Taylor series of exp(x)-1 = x + x^2/2 + x^3/6 + x^4/24 + ... and ln(x+1) = x - x^2/2 + x^3/3 - x^4/4 + ... then obviously ln(exp(x)-1+1)= x.
If we just consider the Taylor polynomials of degree 4 of those two functions we get with the notation from below (see testcases) p = [-1/4,1/3,-1/2,1,0] and q = [1/24, 1/6, 1/2, 1,0] and (p∘q)(X) ≡ X mod X^5

Consider the polynomial p(X) = X + X^2 + X^3 + X^4. Then for q(X) = X - X^2 + X^3 - X^4 we get

(p∘q)(X) = p(q(X)) = X - 2X^5 + 3X^6 - 10X^7 +...+ X^16 ≡ X mod X^5

Testcases

Here the input and output polynomials are written as lists of coefficients (with the coefficient of the highest degree monomial first, the constant term last):

p = [4,3,2,0];  q=[0.3125,-.375,0.5,0]

Integral Testcases:

p = [1,0]; q = [1,0]

p = [9,8,7,6,5,4,3,2,1,0]; q = [4862,-1430,429,-132,42,-14,5,-2,1,0]

p = [-1,3,-3,1,0]; q = [91,15,3,1,0]

Python 2 + sympy, 128 bytes

We locally invert the polynomial by assuming that q(x) = x, composing it with p, checking the coefficient for x2, and subtracting it from q. Let's say the coefficient was 4, then the new polynomial becomes q(x) = x - 4x2. We then again compose this with p, but look up the coefficient for x3. Etc...

from sympy import*
i=input()
p=Poly(i,var('x'));q=p*0+x
n=2
for _ in i[2:]:q-=compose(p,q).nth(n)*x**n;n+=1
print q.all_coeffs()


Delete the first periodic digit We all know that whenever a rational number is written in decimal, the result is either terminating or (eventually) periodic. For example, when 41/42 is written in decimal, the result is

0.9 761904 761904 761904 761904 761904 761904 761904 ...

with an initial sequence of digits 0.9 followed by the sequence 761904 repeated over and over again. (A convenient notation for this is 0.9(761904) where the parentheses surround the block of repeating digits.)

Your goal in this challenge is to take a positive rational number, delete the first digit that's part of the repeating sequence, and return the resulting rational number. For example, if we do this to 41/42, we get

0.9  61904 761904 761904 761904 761904 761904 761904 ...

or 0.9(619047) for short, which is 101/105.

If the rational number has a terminating decimal expansion, like 1/4 = 0.25 does, nothing should happen. You can think of 1/4 either as 0.250000000... or as 0.249999999... but in either case, deleting the first digit of the repeating part leaves the number unchanged.

Details

The input is a positive rational number, either as a pair of positive integers representing the numerator and denominator, or (if your language of choice allows it and you want to) as some sort of rational-number object.
The output is also a rational number, also in either form. If the result is an integer, you may return the integer instead of a rational number.
If taking a pair of numbers as input, you may assume they're relatively prime; if producing a pair of numbers as output, you must make them be relatively prime.
Be careful that you find the first digit that starts a repeating block. For example, one could write 41/42 as 0.97(619047) but that doesn't make 2041/2100 (with the decimal expansion 0.97(190476)) a valid answer.
You may assume that in the input you get, the first periodic digit is after the decimal point, making 120/11 = 10.909090909... invalid input: (its first periodic digit could be considered the 0 in 10). You may do anything you like on such input.
This is code-golf: the shortest solution wins.

Test cases

41/42 => 101/105
101/105 => 193/210
193/210 => 104/105
104/105 => 19/21
1/3 => 1/3
1/4 => 1/4
2017/1 => 2017/1
1/7 => 3/7
1/26 => 11/130
1234/9999 => 2341/9999

Wolfram Language (Mathematica), 59 bytes
FromDigits@MapAt[RotateLeft@*List@@#&,RealDigits@#,{1,-1}]&

Try it online!
Explanation
RealDigits@#

Find the decimal digits of the input.
MapAt[RotateLeft@*List@@#&, ..., {1,-1}]

If there are repeating digits, RotateLeft them. (List@@# prevents the code from attempting to rotate the last decimal digit if the rational number is terminating).
FromDigits@

Convert to rational.


Koch Snowflake - codegolf The Koch snowflake (also known as the Koch star and Koch island) is a mathematical curve and one of the earliest fractal curves to have been described. It is based on the Koch curve, which appeared in a 1904 paper titled "On a continuous curve without tangents, constructible from elementary geometry" (original French title: "Sur une courbe continue sans tangente, obtenue par une construction géométrique élémentaire") by the Swedish mathematician Helge von Koch.

Here are some ascii representations of various iterations:

n=1
__
\/

n=2
__/\__
\    /
/_  _\
  \/

n=3
      __/\__
      \    /
__/\__/    \__/\__
\                /
/_              _\
  \            /
__/            \__
\                /
/_  __      __  _\
  \/  \    /  \/
      /_  _\
        \/

Since there is obviously a limit to the resolution of the ascii representation, we must enlarge the size of the snowflake by a factor of 3 for each iteration to show the extra detail.

Write the shortest code to output the snowflake in the same style for n=4

Your program should not take any input.
Your program should write the snowflake to the console.

Python, 650 612 594 574 characters

n='\n'
S='_a/G\F I\n'
A=dict(zip(S,('III','   ','__/','  G','\  ','F__','   ','III','')))
B=dict(zip(S,('III','   ','\  ',' aF','/a ','  G','   ','III','')))
C=dict(zip(S,('___','aaa','/  ','GII','II\\','  F','   ','III','')))
def T(s):
 a=b=c=d=r=u''
 for k in s:
    a+=A[k];b+=B[k];c+=C[k]
    if k=='I':a=a[:-3]+('II\\'if'a '==d[1:3]else'GII'if' a'==d[:2]else 3*k)
    d=d[3:]
    if k==n:d=c.replace('____','__/F').replace('aaaa','aa  ').replace('/  a','/a  ').replace('a  F','  aF');r+=a+n+b+n+d+n;a=b=c=''
 return r
print T(T(T('__\n\G\n'))).translate({97:95,71:47,73:32,70:92})

This works by expanding the triangle by a factor of 3 each time.  To do that, we need to keep track of whether each symbol is a left or right boundary (e.g. how / is expanded depends on which side of the / is the inside).  We use different symbols for the two possible cases, as follows:

_: _, outside on the top
a: _, outside on the bottom
/: /, outside on the left
G: /, outside on the right
\: \, outside on the left
F: \, outside on the right
<space>: inside
I: outside

The d variable handles the special case where the expansion of an a needs to extend into the 3x3 in the next row.


Fill in the grid randomly Given positive integer n < 10, create a 2 dimensional matrix where each location is filled with its x and y index (starting from the top left).

For example:

Input: 2

00 10
10 11

Input: 3

00 10 20
01 11 21
02 12 22

Once the grid is created, randomly fill each index. This can be with an 'x' or any other way to denote a spot has been filled.

You determine which location to fill by randomly generating indices to fill the matrix. You can only fill n^2 times so you cannot fill as many times as you want until the matrix is completely filled. At the end the matrix must be filled so you must do some work to make sure that you check the random numbers that you use to fill to make sure that spot is not already filled.

Refresh or print after each fill in order to show the progression of the filling iterations.

Example for filling:

Input: 2

00 10
01 11

00 is randomly chosen:

XX 10
01 11

01 is randomly chosen:

XX 10
XX 11

00 is randomly chosen, but since it's already been chosen a re-roll chooses 10:

XX XX
XX 11

11 is randomly chosen:

XX XX
XX XX

Do not print out the random numbers as visually I should be able to see which index was selected. By this I mean do not print "11 is randomly chosen:". It is here for exploratory sake.

Since this is code-golf The shortest code wins.

Have fun and happy golfing!

05AB1E, 29 bytes

<ÝDâJU[X¹ä»,XÐÙg#Jþ2ô.R„  :)U

Try it online!

Space chosen as the char for the removed numbers (as it looks nice), but it could be replaced with any char without affecting byte-count.

Explanation

                                # implicit input n
<ÝDâ                            # cartesian product of [0..n-1] and [0..n-1]
    JU                          # join pairs and store in X
      [     XÐÙg#               # loop until there's only spaces left in X
       X¹ä                      # split X into n pieces
          »,                    # join rows by space and columns by newlines and print
                 Jþ             # join X to string and remove all non-digits
                   2ô.R         # split in pieces of 2 and pick a pair at random
                       „  :)    # replace this pair with 2 spaces
                            U   # and store in X


Surface of the 3x3x3 cube as a graph Your task is to generate a graph with 54 vertices, each corresponds to a facet on a Rubik's cube. There is an edge between two vertices iff the corresponding facets share a side.

Rules

You may choose to output an adjacency list, adjacency matrix, edge list, or any reasonable format to represent a graph in an algorithm. (A visual graph readable by a human is generally not a reasonable format in an algorithm in most cases.)
You may make either every vertex adjacent to itself, or none adjacent to itself.
You may either include both directions for each edge (count one or two times for self-loops), or output exactly one time for each edge, but not mix the ways.
You may renumber the vertices, skip some numbers, or even use non-number labels for the vertices in any way you want. You should also post the numbering if it isn't obvious, so others could check your answer in easier ways.
This is code-golf. Shortest code in bytes wins.

Example output

This is the numbering of vertices used in the example:

          0  1  2
          3  4  5
          6  7  8
 9 10 11 18 19 20 27 28 29 36 37 38
12 13 14 21 22 23 30 31 32 39 40 41
15 16 17 24 25 26 33 34 35 42 43 44
         45 46 47
         48 49 50
         51 52 53

Output as an adjacency list (vertex number before each list is optional):

0 [1 3 9 38]
1 [2 4 0 37]
2 [29 5 1 36]
3 [4 6 10 0]
4 [5 7 3 1]
5 [28 8 4 2]
6 [7 18 11 3]
7 [8 19 6 4]
8 [27 20 7 5]
9 [10 12 38 0]
10 [11 13 9 3]
11 [18 14 10 6]
12 [13 15 41 9]
13 [14 16 12 10]
14 [21 17 13 11]
15 [16 51 44 12]
16 [17 48 15 13]
17 [24 45 16 14]
18 [19 21 11 6]
19 [20 22 18 7]
20 [27 23 19 8]
21 [22 24 14 18]
22 [23 25 21 19]
23 [30 26 22 20]
24 [25 45 17 21]
25 [26 46 24 22]
26 [33 47 25 23]
27 [28 30 20 8]
28 [29 31 27 5]
29 [36 32 28 2]
30 [31 33 23 27]
31 [32 34 30 28]
32 [39 35 31 29]
33 [34 47 26 30]
34 [35 50 33 31]
35 [42 53 34 32]
36 [37 39 29 2]
37 [38 40 36 1]
38 [9 41 37 0]
39 [40 42 32 36]
40 [41 43 39 37]
41 [12 44 40 38]
42 [43 53 35 39]
43 [44 52 42 40]
44 [15 51 43 41]
45 [46 48 17 24]
46 [47 49 45 25]
47 [33 50 46 26]
48 [49 51 16 45]
49 [50 52 48 46]
50 [34 53 49 47]
51 [52 44 15 48]
52 [53 43 51 49]
53 [35 42 52 50]

APL (Dyalog Classic), 34 30 bytes

-4 thanks to jimmy23013

4≥+/¨|∘.-⍨,(⍳3)∘.⌽7 ¯1∘.,○⍳3 3

Try it online!

outputs an adjacency matrix with each vertex adjacent to itself

⍳3 3 generate an array of (0 0)(0 1)(0 2)(1 0)(1 1)(1 2)(2 0)(2 1)(2 2)

○ multiply all by π

7 ¯1∘., prepend 7 or -1 in all possible ways

(⍳3)∘.⌽ rotate coord triples by 0 1 2 steps in all possible ways

+/¨|∘.-⍨, compute manhattan distance between each pair

4≥ it must be no greater than 4 for neighbouring facets


Composition of permutations – the group product Given two permutations in disjoint cycle form, output their product/composition in disjoint cycle form.

To find the composition, convert the disjoint cycles to permutations in two-line notation. Each number in a disjoint part of a cycle is mapped to the number following it in the same part. It wraps around. So 1 -> 5, 5 -> 1, 2 -> 4, 4 -> 2. If a number is not found, 3 -> 3, it is mapped to itself. The first disjoint cycle could also be written (1 5)(2 4)(3). These mappings are converted to two lines, like so (note that the order of P and Q are reversed):

[T]he product of two permutations is obtained by rearranging the columns of the second (leftmost) permutation so that its first row is identical with the second row of the first (rightmost) permutation. The product can then be written as the first row of the first permutation over the second row of the modified second permutation.

Wikipedia article

Rules:

Input will be given as a list of lists or similar format
You may not take something like (1 5)(2 4) as [5, 4, 3, 2, 1], already in two-line form (mapping index to value)
Not all numbers have to occur in each group, so you could have (1 5)·(1 2), resulting in (2 5 1).
Your output should be able to be used as your input.
You do not need to support input with an empty cycle (1 5)·(). That would instead be given as (1 5)·(1) or something equivalent.
Since cycles wrap around, the order doesn't matter as long as the result is correct.
You can start at zero or one. It doesn't matter, because the results are the same.
The numbers can be larger than 9.
You may not include the same number more than once in the output. So [[1],[1]] is not allowed.
Note that this operation is not commutative! I put Q before P, because that's what Wikipedia did. You can choose any order, but specify which if it's different.
Shortest code wins
Built-ins are allowed, but if you use one, show a solution without using it as well.

Examples:
Not all equivalent output possibilities are shown
Input
Output

[[1, 5], [2, 4]], [[1, 2, 4, 3]]
[[1, 4, 3, 5]] (or [[4, 3, 5, 1]] or ...)

[[1, 5]], [[1, 2]]
[[2, 5, 1]]

[[10, 2, 3]], [[2]]
[[3, 10, 2]]

[[1]], [[3]]
[[]] (or [[1]] or something equivalent)

[[10,2,3,15],[1,7],[5,6],[14,4,13,11,12]], [[5,6,7,9,14],[2,8,3,10],[1,11]]
[[12, 14, 6, 1], [8, 15, 10, 3, 2], [13, 11, 7, 9, 4]]

(arguments in reverse order from above gives a different answer)
[[5,6,7,9,14],[2,8,3,10],[1,11]], [[10,2,3,15],[1,7],[5,6],[14,4,13,11,12]]
[[9, 14, 4, 13, 1], [10, 8, 3, 15, 2], [7, 11, 12, 5]]

Haskell, 157 148 bytes

EDIT:

-9 bytes: That could indeed be golfed more. Removed redundant parentheses around p++q. Swapped argument order of g. Got rid of d by starting iterate with p x, after which takeWhile no longer tied with fst + span. Made iterate infix.

Doing this while I'm late... probably can golf some more.

It was simpler, and seemed to be allowed, so the output includes single-element cycles.

q#p=g(p++q>>=id)$f q.f p
f p a=last$a:[y|c<-p,(x,y)<-zip(0:c)(c++c),x==a]
g(x:l)p|c<-x:fst(span(/=x)$p`iterate`p x)=c:g[x|x<-l,x`notElem`c]p
g[]p=[]

Try it online!

How it works:

# is the main function. q#p takes two lists of lists of numbers, and returns a similar list. The tests seem to have Q before P so I used the same order.
f p converts the permutation p from disjoint cycle form to a function, after which f q and f p can be composed with the usual composition operator ..

The list comprehension iterates through the cycles c, searching for a and finding its successor. If the comprehension finds nothing, a is just returned.
zip(0:c)(c++c) is a list of pairs of elements of c and their successors. Since the question lets us "start at one" we can use 0 as a dummy value; it's cheaper to prepend that to zip's first argument than to use tail on the second.

g l p takes a list l of elements, and a permutation function p, and returns the list of cycles touching the elements.

Here c is the cycle containing the first element x of the list, the other elements of c are found by iterating from p x until x is found again. When recursing to find the remaining cycles, all elements of c are first removed with a list comprehension.


Minimize Least Used Binary Bits in Fractions Introduction
For a given rational number r, find a pair of integers p,q so that p/q=r and the number of less used bits in p and q are minimized (details below).
Challenge
A positive rational number r can be expressed as the ratio of two positive integers, r=p/q. The representation is not unique. For each of these representations, both p and q can be expressed in its binary form and the number of 0s and 1s in the representation can be counted (not including leading zeros).
We count the number of appearance of the less appeared digit for both p and q (denoted g(p) and g(q)) and finally define f(p,q)=max(g(p),g(q)).
For example, the number 35 can be written as 35/1 or 175/5, and we convert both the numerator and the denominator to binary. Then we can count
35 -> 100011, 3 zeros, 3 ones. g(35)=min(3,3)=3
 1 ->      1, 0 zero ,  1 one.  g(1)=min(1,0)=0

f(35,1)=max(g(35),g(1))=3.

And for 175/5
175 -> 10101111. 2 zeros, 6 ones. g(175)=min(2,6)=2
  5 ->      101. 1 zero,  2 ones.   g(5)=min(1,2)=1.

f(175,5)=max(g(175),g(5))=2.

Therefore, if we want to minimize f(p,q) while keeping the rate of p/q constant, p=175,q=5 is a better choice than p=35,q=1. An even better choice is p=1015,q=29 since f(1015,29)=1. It is also easy to prove that there are no valid choice that makes f(p,q) equals 0, so this the optimal choice.
Your task is to write a full program or function that computes a choice of (p,q) for a given rational number r such that f(p,q) is minimized (sub-optimal solutions are OK but there are penalties), while keeping the program as short as possible.
Test cases
The outputs are not unique.
Input
Output

63/1
63/1 0

17/9
119/63 1

35/1
1015/29 1

563/1
2815/5 2

You may also wish to see whether you can get an answer without penalty(see below) for 595/1.
Scoring
Your score will be composed of two parts: the code-length and the penalties. The code-length is measured in bytes.
The penalties are calculated by running your program on all test cases in the given test set. For each r in the test set, if your program outputs p,q, you get a penalty of max(f(p,q)-2,0). That is, you get no penalty (nor bounty) for any answer that gives a f value less than or equal to 2.
The final score is calculated by final_penalty*codelength^(1/4), with lower score better.
Test set
The test set for calculating the penalty can be found in this
pastebin.
Basically, it contains all rational numbers which when expressed in reduced fraction p/q has the property 128>p>q (and of course, (p,q) coprime), along with all integers from 128 to 1023(inclusive). The second column in the pastebin are the f(p,q) calculated by a naive method. The final line in the pastebin shows the total penalty of this naive method. It is 2343.
Specs

Input can be given in any reasonable form. For example, a rational if your program supports it, or a tuple or a list of the numerators and denominators in any order (and you should assume them to be coprime). Same flexiblility for output.
You need to output p and q in a reasonable form and also f(p,q) (To avoid 0-byte programs, thanks to @Lynn).
You should be able to score your own program (Thanks for the suggestion by @user202729). So in your answer, please specify all of the following: the final penalty, the code length in bytes, and the score. Only the score needs to be included in the title of your answer.

Node.js, Score = 7873
This is both naive and rather long...

Code size = 129 bytes
Total penalty = 2336
Score = round(1291/4 * 2336) = 7873

Takes input as [p, q]. Returns [p', q', f(p, q)].

f=(a,r=[k=6e3])=>k--?f(a,(i=Math.max(...a.map(n=>(g=n=>n?g(n>>1,n&1?++o:++z):o<z?o:z)(a=(p=a,n*k),o=z=0))))>r[2]?r:[p,a,i],k--):r

Try it online! for the test cases
or compute the total penalty by processing the whole test set

Alternate version, Score = 8426
A modified version to reach a total penalty of 2330. But it's not worth it...

Code size = 171 bytes
Total penalty = 2330
Score = round(1711/4 * 2330) = 8426

Same I/O format as the main version.
f=(a,r=[k=5e3])=>k--?f(a,(i=Math.max(...a.map(n=>(g=n=>n?g(n>>1,n&1?++o:++z):o<z?o:z)(a=(p=a,n*([7007,7901,16239,32695,130527,261599][k]||k-5)),o=z=0))))>r[2]?r:[p,a,i]):r

Try it online!
It includes some hardcoded values for the highest multipliers. They were found by generating all bitmasks m with up to 32 bits and no more than 5 0's, keeping the values for which m mod p = 0, checking the score of q * m / p and finally doing the same operation with the inverted bitmask of m of the same length (no more than 5 1's with all other bits set to 0).