Convert calendar dates to week dates and vice versa

Javascript: 422 characters

Originally this had 825 characters, and was still a bit comprehensible and legible, beside the fact of being golfed. I was sure that it could be reduced in something between 10% to 20%. This answer passed by tons of edits from me and got suggestions from @Ismael Miguel and specially from @DocMax resulting in an extremely-golf-crushed source down to 422 characters, with the side-effect of making it heavily obfuscated, a reduction of almost 49%. Really thanks for both, I wish that you two could get a badge for this. I did not thought that it could be reduced by so much.

Here is the code, 422 characters:

x=prompt(E=eval);W=x[f=5]=='W';A=x.match(/\d+/g);y=+A[a=0];for(t="'012011223445569'[z]-30+30*z";q=a%4<1&(a%100>0|a%400<1),a++<y;f=(f+1+q)%7)v=f;z=w=+A[1]-W;r=+A[2];if(W){w+=f>3;h=7*w+r-f;for(z=1;h-q*(z>2)>=E(t);++z);w=1+(10+z--)%12;d=h-q*(z<3)-E(t);y+=z?z>12:-1}else{g=r+E(t)-(w>1&&!q+w-2?2-q:2);d=(f+g)%7;w=0|g/7+(f<4);w=w>11&r-d>26?(++y,1):w<1?(--y,53^v>3):w}alert(y+(W?'-':'-W')+(w>9?'':0)+w+'-'+(!W|++d>9?'':0)+d+'\n')

Pretty complex. Here a (somewhat long) partially-ungolfed (but still badly obfuscated) and commented version:

x = prompt(E = eval); // Receives input, but has a side-effect of having a strange message in the prompt box.

// Year 0 of the Gregorian calendar (if such thing existed) would start on a 5=Friday. (0=Monday, 6=Sunday)
W = x[f = 5] == 'W'; // Checks if there is a W in the sixth char.
A = x.match(/\d+/g); // Divide the input in 3 numbers.

y = +A[a = 0]; // Parse the year.

// The t variable is used to create a table with cumulative months length starting from December of the previous year, this table is acessed by using the eval() function.
// Calculate the weekday of 01/01 of the year in the f variable. Do that by counting Gregorian calendar years from 0 until now.
// Count 2 weekdays for leap years and 1 for non-leap years.
// The variable q defines if the year is a leap year.
// The v variable stores the weekday of 01/01 of the prevoius year.
// The % 7 ensures that the weekday are kept in the interval 0-6, where 0 is Monday and 6 is Sunday.
for (t = "'012011223445569'[z] - 30 + 30 * z"; q = a % 4 < 1 & (a % 100 > 0 | a % 400 < 1), a++ < y; f = (f + 1 + q) % 7)
  v = f;

z = w = +A[1] - W; // Parse the second number, might be the week number or the month, accordingly to the W.
r = +A[2]; // Parse the third number, might be the week day or the day in the month, accordingly to the W.

// Converts week date to calendar date.
if (W) {

  // The expression "7 * (f > 3) - f" maps the offset between the calendar date and the week date in the following manner:
  // {0Mon:1, 1Tue:0, 2Wed:-1, 3Thu:-2, 4Fri:4, 5Sat:3, 6Sun:2}
  // Obtain the day within the year and store it in h.
  w += f > 3;
  h = 7 * w + r - f;

  // Finds the day offset in the table to the corresponding month.
  for (z = 1; h - q * (z > 2) >= E(t); ++z);

  // This calculates the day in the month and the month.
  w = 1 + (10 + z--) % 12;
  d = h - q * (z < 3) - E(t);

  // Fix-up the year, if needed.
  y += z ? z > 12 : -1

// Converts calendar date to week date.
} else {

  // Calculate how many days passed since 01/01
  g = r + E(t) - (w > 1 && !q + w - 2 ? 2 - q : 2);

  // Knowing the week day in which the year started and how many days passed since 01/01, calculate the week day of the given date.
  d = (f + g) % 7;

  // Calculates how many weeks passed since 01/01 and add one week if the year started on Monday, Tuesday, Wednesday or Thursday.
  w = 0 | g / 7 + (f < 4);

  // If we are in the last 3 days of the year, and 01/01 will fall on Monday, Tuesday, Wednesday or Thursday,
  // then we advance to the first week of the next year.
  // Do this by checking r + 3 - (d - 2) > 31, where:
  //   r is the date;
  //   (d - 2) is the weekday (d=1 for monday, 7 for sunday);
  //   (3 - (d - 2)) is the number of days until the week's Thursday and;
  //   > 31 means January of the next year.
  // r + 3 - (d - 2) > 31 is simplified to r - d > 26.
  w = w > 11 & r - d > 26 ? (++y, 1)

  // If we are at the 0th week of the year, go back to the last week of the previous year.
  // If the last year started on Friday, Saturday or Sunday this would be the 52nd week. It is the 53rd otherwise.
    : w < 1 ? (--y, 53 ^ v > 3)

  // Neither of the previous two cases.
    : w
}

// Output it.
alert(y + (W ? '-' : '-W') + (w > 9 ? '' : 0) + w + '-' + (!W | ++d > 9 ? '' : 0) + d + '\n')

The prompt box comes with the message with the serialization of the eval function. Ignore this message, it is just a side-effect of golfing some chars.

It passes for all provided test cases. If given invalid input, the behaviour is undefined.

Here are the test cases, had some bugs in previous versions (specially with the last two lines):

2014-02-27  <-->  2014-W09-4
2008-12-30  <-->  2009-W01-2
2010-01-03  <-->  2009-W53-7
2011-04-23  <-->  2011-W16-6
2012-01-01  <-->  2011-W52-7

In case you are curious, here it is the original, 825 characters code:

p=parseInt;x=prompt();y=p(x.substr(0,4));f=6;j="a%4<1&(a%100>0|a%400<1)";for(a=1583;a<y;a++)f+=eval(j)?2:1;f%=7;q=eval(j);if(x.contains('W')){w=p(x.substr(6,2))-1;r=p(x.substr(9))-1;u=f<1?3:f<5?1-f:f-4;h=w*7+r+u+1;e=q?1:0;d=h<1?(m=12,y--,h+31):h<32?(m=1,h):h<60+e?(m=2,h-31):h<91+e?(m=3,h-59-e):h<121+e?(m=4,h-90-e):h<152+e?(m=5,h-120-e):h<182+e?(m=6,h-151-e):h<213+e?(m=7,h-181-e):h<244+e?(m=8,h-212-e):h<274+e?(m=9,h-243-e):h<305+e?(m=10,h-273-e):h<335+e?(m=11,h-304-e):h<366+e?(m=12,h-334-e):(m=1,y++,h-365-e);alert(y+'-'+(m<10?'0':'')+m+'-'+(d<10?'0':'')+d+'\n')}else{m=p(x.substr(5,2));d=p(x.substr(8));g=d-1;for(b=1;b<m;b++)g+=[31,q?29:28,31,30,31,30,31,31,30,31,30,31][b-1];v=(f+g)%7;w=~~(g/7)+(f>0&f<5?1:0);if(v<1)w--,v=7;if(m>11&d>28&32-d+f>3)w=1,y++;if(w<1)w=53,y--;alert(y+'-W'+(w<10?'0':'')+w+'-'+(v<1?7:v)+'\n')}


1 character typo generating most error messages from C++ compilation

gcc 4.5.2, Score: 8579.15 (or 14367.49 for filename "a.C", may update later)

Original file, 29 bytes, compiles clean (a.cpp):

#if 0
#include"a.cpp"
#endif

Modified file, 30 bytes:

#iff 0
#include"a.cpp"
#endif

Errors:

$ gcc -c a.cpp 2>&1 | wc -c
1286873

Score:

1286873 / (30 * 5) = 8579.15

Head and tail of error output:

a.cpp:1:2: error: invalid preprocessing directive #iff
In file included from a.cpp:2:0:
a.cpp:1:2: error: invalid preprocessing directive #iff
In file included from a.cpp:2:0,
                 from a.cpp:2:
a.cpp:1:2: error: invalid preprocessing directive #iff
In file included from a.cpp:2:0,
                 from a.cpp:2,
                 from a.cpp:2:
a.cpp:1:2: error: invalid preprocessing directive #iff
In file included from a.cpp:2:0,
                 from a.cpp:2,
                 from a.cpp:2,
                 from a.cpp:2:
a.cpp:1:2: error: invalid preprocessing directive #iff
In file included from a.cpp:2:0,
                 from a.cpp:2,
                 from a.cpp:2,
                 from a.cpp:2,
                 from a.cpp:2:
a.cpp:1:2: error: invalid preprocessing directive #iff
In file included from a.cpp:2:0,
                 from a.cpp:2,
                 from a.cpp:2,
                 from a.cpp:2,
                 from a.cpp:2,
                 from a.cpp:2:

... And so on, backing out with second error after max include depth:

a.cpp:3:2: error: #endif without #if
In file included from a.cpp:2:0,
                 from a.cpp:2,
                 from a.cpp:2,
                 from a.cpp:2,
                 from a.cpp:2:
a.cpp:3:2: error: #endif without #if
In file included from a.cpp:2:0,
                 from a.cpp:2,
                 from a.cpp:2,
                 from a.cpp:2:
a.cpp:3:2: error: #endif without #if
In file included from a.cpp:2:0,
                 from a.cpp:2,
                 from a.cpp:2:
a.cpp:3:2: error: #endif without #if
In file included from a.cpp:2:0,
                 from a.cpp:2:
a.cpp:3:2: error: #endif without #if
In file included from a.cpp:2:0:
a.cpp:3:2: error: #endif without #if
a.cpp:3:2: error: #endif without #if

Note:
- If .C ends up qualifying as a valid extension then score is 1,206,869 / (28 * 3) = 14,367.49.
- If Dennis' suggested second #include is added, file name "a.cpp", score is 80,797,292,934 / (46 * 5) = 351,292,578.97


Kotlin, 397 393 bytes

Unnamed lambda.

You can try it here, but you'll have to paste the source in yourself because the editor doesn't seem to save programs in UTF-8 encoding. The ungolfed version is a full program, so you should be able to use that in its entirety.

Golfed

{n:Int->operator fun String.mod(x:Int){(1..x).map{print(this)}};val l={s:String->s.padStart(n/10+2)};var s=(1..n).map{"${n*4+1-it}".reversed()};val z={i:Int->l(" ")%1;s.map{print(it.getOrElse(i,{' '}))};"\n"%1};(s[0].length-1 downTo 0).map(z);l("┌")%1;"┴"%n;"┐\n"%1;(1..n).map{l("$it┤")%1;" "%n;"├${n*3+1-it}\n"%1};l("└")%1;"┬"%n;"┘\n"%1;s=(1..n).map{"${n+it}"};(0..s.last().length-1).map(z)}

(Sort of) Ungolfed

fun main(args: Array<String>) {
    var q = { n: Int ->
        operator fun String.mod(x: Int) {
            (1..x).map { print(this) }
        }

        val l = { s: String ->
            s.padStart(n / 10 + 2)
        }

        var s = (1..n).map { "${n * 4 + 1 - it}".reversed() }

        val z = { i: Int ->
            l(" ")%1
            s.map { print(it.getOrElse(i, { ' ' })) }
            "\n"%1
        }

        (s[0].length - 1 downTo 0).map(z)

        l("┌")%1
        "┴"%n
        "┐\n"%1

        (1..n).map { l("$it┤") % 1;" " % n;"├${n * 3 + 1 - it}\n" % 1 }

        l("└")%1
        "┬"%n
        "┘\n"%1

        s = (1..n).map { "${n + it}" }
        (0..s.last().length - 1).map(z)
    }

    q(30)
}

Saved a bunch of bytes by overloading the % operator and using it to print. I'll probably revisit this later - I think I can save quite a few bytes if I use mod or some other operator as a concatenation function. More interpolation and less print calls.


Chef has no string types, so the ingredients are positive integers. 0 is used to separate the starting list from used ingredients and to end the used ingredients list.

A, B: stack
    T, J, IN: int
    T = 1
    A.push(0) // used as the marker for the bottom of the stack
    IN = input() // input the first list
    while(IN):
        A.push(IN)
        IN = input()
    IN = input() // for each used ingredient
    while(IN):
        B.push(0)
        while(T): // move all ingredients up to and including the one we are moving right now to the second stack
            T = A.peek() - IN
            B.push(A.pop())
        A.push(B.pop())
        if(A.peekUnderTop() != 0):
            A.swapTopTwoItems()
        T = B.pop() // move the ingredients from the second stack back to the first
        while(T):
            A.push(T)
            T = B.pop()
        T = IN // to make it non-zero for next iteration
        IN = input(0
    print(A.inverted())


HTML/CSS, 1047
I could golf this a lot more by deleting the -webkit prefixes etc., but this will do for the time being:

It is a period of civil
war. Rebel spaceships, striking from a hidden base, have won their first victory
against the evil Galactic Empire.

During the battle, Rebel spies managed to
steal secret plans to the Empire's ultimate weapon, the DEATH STAR, an armored
space station with enough power to destroy an entire planet.

Pursued by
the Empire's sinister agents, Princess Leia races home aboard her starship,
custodian of the stolen plans that can save her people and restore freedom to
the galaxy...

Live demo


Jelly on Linux, 6 bytes

5ịO×32

Try it online!

Usage note: the question says "write the shortest code you need to determine whether an executable binary program supplied as parameter", and that's exactly what you need to do here; supply the entire executable binary program as the parameter. Not its filename, the program itself. (I hope you have a fairly understanding shell!) The TIO link uses the shortest known ELF program Linux will run, by Brian Raiter as the example program.

Linux uses ELF as its executable format. It turns out that the fifth byte of an ELF program specifies the processor bitwidth it's designed for: 0x01 for a 32-bit program, or 0x02 for a 64-bit program. So all we have to do is extract the byte in question (5ị), convert it from a character to a number (O), and multiply by 32 (×32).

There's probably a language that can use this exact algorithm more succinctly, but I wanted to post this answer to demonstrate the algorithm.


kdb k, 101 bytes
1@"\n"/:{"\n"/:{" "/:(r@&{~#&x=a}'!#r),(,$1+a@x),,c@x}'!#c::(r::" "\:x)@a::-1+.:'.z.x}'-1_"\n"\:0::0;

Me: (reads the word "transpose" in the title) K will be perfect for this! It'll kick everything else's hind!
20 minutes and 101 bytes later
Me: Idiot.


Regex (.NET, Perl, PCRE, JavaScript, ... flavours), 25 bytes

Yes, this will create some debate again, whether a regular expression is a valid program, but I'll pre-empt that and say that this submission is just for fun and doesn't need to be considered for the winner. (As opposed to the 31 byte Perl variant at the bottom ;).)

So here is a pure regex replacement solution.

Pattern (note the trailing space):

o(( *)\n#*)(?=\2) |o

Replacement (note the leading space):

 $1o

The byte count is for the sum of the two.

You can test it at http://regexhero.net/tester/. Make sure to choose Unix-style line endings and "preserve pasted formatting" when pasting. If it still doesn't work, you still have pasted Windows-style line endings. The easiest fix in that case is to replace \n with \r\n in the pattern to see that it works.

Here is a 48 byte ECMAScript 6 function using this

f=(s)=>s.replace(/o(( *)\n#*)(?=\2) |o /,' $1o')

Finally, I've also got an actual program. It's 31 bytes of Perl (including two bytes for p and 0 flags; thanks to Ventero for the suggestion!).

s/o(( *)\n#*)(?=\2) |o / $1o/

If you want to test it, don't even save it in a file, just do

perl -p0e 's/o(( *)\n#*)(?=\2) |o / $1o/' < hill.txt


Befunge-98 (FBBI), 344 296 248 bytes

20020xxnngg33%%!!2200gg''00--3300gg33%%!!4400gg55%%!!22kk++55##rr55kk::00gg\\11pp00gg\\11++11pp22++00::pp00gg\\11++00gg--!!zz!!22**++00::gg00gg8844**--!!55++jj..''gg::00rr00::gg\\--..''220011''0011::''002211''223311''00441144kkppgg11001100::99oo@@

Try it online!

Verification!

Befunge-98 is the first esoteric language that I could find that was both 2D and had file output. This is a full solution (with a trailing newline) stored in a file named as a tab character. It outputs as 0-indexed, and outputs the first index in a run of characters (though there's only ever pairs).

There's a few golfs to be made, especially as there are 15 no-ops in the code, now just one no-op! I will be working on making this shorter, with the goal of getting to or below 200 bytes.


Java 7, 89
void g(char[]a,float b){for(int i=0,l=a.length;i<(int)(l*b);)System.out.print(a[i++%l]);}

takes char[] and float and outputs to STDOUT. basic looping.


Simple single-player board game, expected score distribution

Stax, 56 55 bytesCP437
üZÄ^3Γ╥£X╜T∩L╖á↨→╘Oïë╢Δ╥∙Eü╦5├jC╩XpN◘╘♥«╟╝☻y╞╘wé↔Ioÿ≈⌐─

Run and debug online!
Warning: Takes a long time (around 5 minutes in my box) to run the large example.
Credits to the almighty rubber duck for -1 byte.
Input is a list of numbers. Scoring x points is represented by -x, and Move y steps forward and follow the instruction there is represented by y. So for example the small test case will be represented as [-1,2,-1].
Outputs in rational number, the output for the large case is like this:
7 3/128
8 1/128
9 3/256
10 9/256
11 3/256
12 25/512
13 1/64
14 1/64
15 75/1024
16 33/1024
17 123/2048
18 1/64
19 3/256
20 45/512
21 3/64
22 67/1024
23 5/512
24 11/1024
25 33/512
26 39/1024
27 39/1024
28 1/512
29 3/1024
30 183/4096
31 97/4096
32 231/8192
33 1/256
34 3/1024
35 65/4096
36 71/4096
37 145/8192
38 1/128
39 9/1024
40 57/4096
41 1/64
42 79/8192
43 1/256
44 37/4096
45 127/8192
46 41/4096
47 93/16384
49 15/4096
50 55/8192
51 15/4096
52 45/16384

Alternative version
Calculates the probability recursively instead of enumerating every possibility. Much faster. Not really golfed.
00\sn+~]]01\]]+Yd;%{;%=zi^]?i]+ys@iXd{{dx2<;x|i-v@1<+!C_E2u*s;x@0|m-s\mm:f;i({i+|i=!Ci2+mys@{{B;x@0|m-+rm+F{o{h}/{hh0_{H+F\m]ys+YdFUUv\ys@:fo{h}/mhh0_{H+F\J
Try and debug online!
The two different algorithms give the same result.
Explanation
Uses the unpacked version to explain. The size of the game board is stored in register x. The current position on the board is stored in register y. There is an extra flag (boolean) denoted bFlip that is stored on the stack, used to indicate the type of last instruction.
The complete unpacked version is 66 bytes.
X|2{v:Bx)0Y1~s{^,*y+Ycx>{d1~}{v;@c1<c~{-}{y+Yd}?}?F,dmo|RmNx|2u*+J

I will explain it part by part.
X|2{v:Bx)0Y1~s{     F,dm
X|2                        `2^x`
   {v                  m    For `[0..2^x-1]` do the following
     :Bx)                   Binary representation of the current loop index
                            Padded with zeros to make the length `l`.
                            Each binary represents a sequence of coin flip outcomes
         0Y1~s              Initialize `y` and current score to `0`, and `bFlip` to true
              {     F       Play the game as indicated by the sequence of coin flip outcomes
                     ,d     Clean up: remove `bFlip` from the stack.

The block that plays the game:
{^,*y+Ycx>{d1~}{v;@c1<c~{-}{y+Yd}?}?F
{                                   F    The loop as stated above
 ^                                       Increment current flip result
                                         Map the original [0,1] to [1,2], denote this as `n`.
  ,*                                     If last instruction is of the type `Score k points` (`k` may be `0`)
    y+Y                                      Move forward `n` steps and save the new current position to register `y`.
       cx>{   }{                  }?     If already moved past the end
           d1~                               Mark this instruction as `Score 0 points` (or `Do nothing`)
                                         Else
                v;@                          Get current instruction
                   c1<c~                     Get the type of current instruction and remember it
                        { }{    }?           If the current instruction is `Score k points`
                         -                       Score `k` points
                                             Else
                            y+Yd                 Move forward as the instruction indicates

After executing this, we have a list with 2^x elements containing the scores of all possible coin flips, with equal probabilities. The rest of the program is just converting them to the output.
o|RmNx|2u*+J
o|R             Convert to a list of pairs of [element, count of appearance]
   m            Map the array elements with the rest of the program, output the results on separate lines
    Nx|2u*+     Divide the count of appearance by `2^x` to get probability
           J    Join the two elements with a space


Mathematica, 97 bytes (SBCS)

Or@@(Equal@@(a@u/#)&/@(a/@NestList[RotateLeft,v,Length@v]))
a@l_:=Norm[#〚1〛-#〚2〛]&/@l~Subsets~{2}

You can try it online!

The function a computes all the pairwise distances between any two vertices of the polygon.

The main function applies this to the first list and to every rotation of the second list, to try and find the corresponding vertices. The rotation of the second list is correct if all the corresponding distances have been scaled accordingly.

Thanks to @J42161217 for saving me some 3 bytes


Javascript, 137 135 134 132 113 110 108 101 99 94 93 92 90 bytes
This is originally based on HP Williams solution, with some improvements outside the regex, and a couple of tweaks within it, plus a couple of bytes from Primo.
s=>s[0]+
  /.$/.exec(s.toUpperCase()
    .match`.* .|.*Z|...S.S?|T..|M[I-T]+|[AFINOUW][^O]V?|.*`
  )

(Linebreaks for readability only)
Commentary for the regex:
.*( .|z)|      // Two-or-three word states, plus Arizona
...s.s?|       // Mississippi, Missouri, Massachussetts, Alaska, and (non-harmfully) Kansas
M[i-t]+|       // Montana, Minnesota, Michigan
[AFINOUW][^o]v?|  // All the other first-two-letter states, avoiding Iowa/Connecticut/Louisiana, plus Nevada
T..|           // Tennessee, Texas
.+             // Everything else is first-and-last

Alternative regex's (same length):
/...(a$|z|s.s?|.* .)|M[i-t]+|T..|[AFINOUW].v?|.*/
/.*( .|z)|...s.s?|Te.|M[i-t]+|[^GHKMPVo]{2}v?|.*/
/.*( .|z)|...s.s?|M[i-t]+|[^GHKMPVo]{2}[vnx]?|.*/

History
92
s=>s[0]+
/.*( .|z)|...s.s?|T..|M[i-t]+|[AFINOUW][^o]v?|.*/
.exec(s)[0].slice(-1).toUpperCase()

94
s=>s[0]+/.*( .|z)|...s.s?|M[io]n?t?|[AFIOUWN][^o]v?|T..|.*/
.exec(s)[0].slice(-1).toUpperCase()

99
s=>s[0]+/.*( .|z|l.*k)|T..|M.ss.s?|M[io]n?t?|[AFIOUWN][^o]v?|.*/
.exec(s)[0].slice(-1).toUpperCase()

101
s=>s[0]+/.+[A-Zz]|Nev?|.*sk|M.ss.s?|M[io]n?t?|[AFIOUW][^o]|Te.|.+/
.exec(s)[0].slice(-1).toUpperCase()

108
 s=>s[0]+/MI(N|SSO|S)|[CDGHKLPV].*|.* .|.*[XZV]|.*?N[NTE]|.*(SK|D$|WA)|../
.exec(s.toUpperCase())[0].slice(-1)

110
s=>s[0]+/MI(N|SSO|S)|[CGHKLPV].*|.* .|.*[XZV]|.*?N[NTE]|.*(SK|[ED]$|WA)|../
.exec(s.toUpperCase())[0].slice(-1)

113
s=>s[0]+/^MI(N|SSO|S)|^[CGHKLPV].*|.*?( .|[XZV])|.*?N[NTE]|.*(SK|[ED]$|WA)|../
.exec(s.toUpperCase())[0].slice(-1)

132
s=>(S=s.toUpperCase(),' ._SSO_^MI[NS]_^[CGHKLPV].*_.V_N[TNE]_SK_[ED]$_WA_Z_X_..'
.split`_`.some(p=>s=S.match(p)),S[0]+s[0].slice(-1))

134
s=>' ._SSO_^MI[NS]_^[CGHKLPV].*_.V_N[TNE]_SK_E$_D$_WA_Z_X_..'.split`_`
.map(p=>s=(z=s.toUpperCase().match(p))?s[0]+z[0].slice(-1):s)&&s

135
s=>' ._SSO_^MI[NS]_LASK_^[CGHKLPV].*_NT_EN_[DE]$_WA_.[XVZ]_..'.split`_`
.map(p=>s=(z=s.toUpperCase().match(p))?s[0]+z[0].slice(-1):s)&&s

137
s=>' ._OWA_SSO_ONT_^MI[NS]_LASK_^[CGHKLPV].*_EN_[DE]$_.[XVZ]_..'.split`_`.
map(p=>s=(z=s.toUpperCase().match(p))?s[0]+z[0].slice(-1):s)&&s


JavaScript (ES6), 881 871 bytes

Takes the input string in all caps.

s=>(o={},'HEelLIithBEeryllMGagnesCAalcTIitanVanadCRhromGAallGEermanSEelenRBubidSRtrontYttrZRirconTCechnetRUuthenRHhodPDalladCDadmTEellurBAarCEerPRraseodymNDeodymPMromethSMamarEUuropGDadolinTBerbDYysprosERrbTMhulLUutetREhenIRridTLhallFRrancRAadACctinTHhorPArotactinUranAMmericCMurESinsteinFMermMDendelevLRawrencRFutherfordDBubnSGeaborgMTeitnerDSarmstadtRGoentgenFLlerovMCoscovLVivermorHydrogenBoronCarbonNitrogenOxygenFluorineNEeonALluminumPhosphorusSulfurCLhlorineARrgonMNanganeseZNincASrsenicBRromineKRryptonMOolybdenumIodineXEenonLAanthanumTAantalumPTlatinumATstatineRNadonTSennessineOGganessonNAsodiumKpotassiumFEironAGsilverWtungstenAUgoldHGmercury'.split(/([A-Z]+|[a-z]+)/).map((r,i,a)=>i%4-3?0:o[e=a[i-2]]=i>339?r[0].toUpperCase()+r.slice(1):e[0]+r+(i<235?'ium':'')),g=([c,...s],r)=>c?c<'A'|c>'Z'?g(s,r+c):o[c]&&g(s,r+o[c])||o[c+=s.shift()]&&g(s,r+o[c]):r)(s,'')||s

Extended test cases

Because this challenge is also a variant of the exact cover set problem, I've added the following test cases:

"NA" → "Sodium"
"NAG" → "N" + "AG" → "NitrogenSilver"
"NAP" → "NA" + "P" → "SodiumPhosphorus"

let f =

s=>(o={},'HEelLIithBEeryllMGagnesCAalcTIitanVanadCRhromGAallGEermanSEelenRBubidSRtrontYttrZRirconTCechnetRUuthenRHhodPDalladCDadmTEellurBAarCEerPRraseodymNDeodymPMromethSMamarEUuropGDadolinTBerbDYysprosERrbTMhulLUutetREhenIRridTLhallFRrancRAadACctinTHhorPArotactinUranAMmericCMurESinsteinFMermMDendelevLRawrencRFutherfordDBubnSGeaborgMTeitnerDSarmstadtRGoentgenFLlerovMCoscovLVivermorHydrogenBoronCarbonNitrogenOxygenFluorineNEeonALluminumPhosphorusSulfurCLhlorineARrgonMNanganeseZNincASrsenicBRromineKRryptonMOolybdenumIodineXEenonLAanthanumTAantalumPTlatinumATstatineRNadonTSennessineOGganessonNAsodiumKpotassiumFEironAGsilverWtungstenAUgoldHGmercury'.split(/([A-Z]+|[a-z]+)/).map((r,i,a)=>i%4-3?0:o[e=a[i-2]]=i>339?r[0].toUpperCase()+r.slice(1):e[0]+r+(i<235?'ium':'')),g=([c,...s],r)=>c?c<'A'|c>'Z'?g(s,r+c):o[c]&&g(s,r+o[c])||o[c+=s.shift()]&&g(s,r+o[c]):r)(s,'')||s

console.log(f('HI!'))
console.log(f('THIS IS AN EXAMPLE'))
console.log(f('NEON'))
console.log(f('SNIP'))
console.log(f('NA'))
console.log(f('NAG'))
console.log(f('NAP'))

How?

Preliminary optimization

We ignore the following 26 elements entirely, because they can safely be replaced with two symbols of one character among BCFHIKNOPSUVWY:

Bh, Bi, Bk, Cf, Cn, Co, Cs, Cu, Hf, Ho, Hs, In, Nb,
Nh, Ni, No, Np, Os, Pb, Po, Pu, Sb, Sc, Si, Sn, Yb

Encoding and decoding the elements

We use an interlaced list of element symbols in upper case and element names in lower case. Symbols are always stored as-is, while names are shortened according to the following rules:

If the first letter of the name matches the first letter of the symbol, we omit it.
If the element passes rule #1 and its name ends in "ium", we omit this suffix.

Examples:

Ag / Silver: "AGsilver"
K / Potassium: "Kpotassium"
Zn / Zinc: "ZNinc"
He / Helium: "HEel"

The 58 elements that trigger both rules are stored at the beginning of the list, followed by the 27 elements that trigger rule #1 only, followed by the 7 elements that do not trigger any rule.

We decode this list to populate the lookup table o, where the keys are the symbols and the values are the decoded element names:

"HEelLIith[...]HGmercury"       // encoded list
.split(/([A-Z]+|[a-z]+)/)       // split it by character case, which gives:
                                // [ '', 'HE', '', 'el', '', 'LI', '', 'ith', etc. ]
.map((r, i, a) =>               // for each item 'r' at position 'i' in this array 'a':
  i % 4 - 3 ?                   //   if we're not currently pointing to an element name:
    0                           //     do nothing
  :                             //   else:
    o[e = a[i - 2]] =           //     save o[e], where e = element symbol
      i > 339 ?                 //     if symbol/name first letters do not match:
        r[0].toUpperCase() +    //       we need to capitalize the first letter of the name
        r.slice(1)              //       and keep the rest unchanged
      :                         //     else:
        e[0] +                  //       we use the first letter of the symbol,
        r +                     //       followed by the name,
        (i < 235 ? 'ium' : '')  //       followed by the 'ium' suffix when appropriate
)                               // end of map()

Covering the input string

We try to replace all upper-case letters in the input string with element symbols, using the recursive function g() which eventually returns a replacement string or undefined if no exact cover is found:

g = ([c,                                  // c = next character
         ...s],                           // s = array of remaining characters
                r) =>                     // r = replacement string
  c ?                                     // if there's still at least one character:
    c < 'A' | c > 'Z' ?                   //   if it's not an upper-case letter:
      g(s, r + c)                         //     just append it to 'r'
    :                                     //   else:
      o[c] && g(s, r + o[c]) ||           //     try to find a symbol matching 'c'
      o[c += s.shift()] && g(s, r + o[c]) //     or a symbol matching 'c' + the next char.
  :                                       // else:
    r                                     //   success: return 'r'


C 108
Thanks to Jonathan Frech this answer is now incredibly shorter
Thanks to @ceilingcat for some very nice pieces of golfing - now even shorter
i;main(c,v)char**v;{for(;++i<c;printf("%c\"%s\":%s",!~-i*79+44,v[i],++*v))*(*v=index(i[v],58))=0;puts("}");}

Try it online!


05AB1E, 60 57 bytes
[N>’¸¸.Â‚‹º.ŒŒ/›´?€¼=ƒËŠˆ&€®=ÿ’.wD2è'eQ#“e":"“¡¦ε'"¡н]\)˜

Beats all other answers.
[N>’...’.wD2è'eQ#“e":"“¡¦ε'"¡н]\)˜  # trimmed program
[               #                   # while...
            è                       # character in...
        .wD                         # data of response from URL...
                                    # (implicit) "http://" concatenated with...
   ’...’                            # "api.stackexchange.com/tags?site=codegolf&page=ÿ"...
                                    # (implicit) with ÿ replaced by...
 N                                  # current index in loop...
  >                                 # plus 1...
            è                       # at index...
           2                        # literal...
                #                   # is not...
               Q                    # equal to...
             'e                     # literal...
        .w                          # push data of response from URL...
                                    # (implicit) "http://" concatenated with...
   ’...’                            # "api.stackexchange.com/tags?site=codegolf&page=ÿ"...
                                    # (implicit) with ÿ replaced by...
 N                                  # current index in loop...
  >                                 # plus 1...
                      ¡             # split by...
                “e":"“              # literal...
                       ¦            # excluding the first...
                        ε           # with each element replaced by...
                            н       # first element of...
                                    # (implicit) current element in map...
                           ¡        # split by...
                         '"         # literal
                             ]      # exit map
                             ]      # exit infinite loop
                              \     # delete top element of stack
                               )    # push stack...
                                ˜   # flattened
                                    # implicit output


Golf with a bowling ball: hello world with high complexity yet short code

C# - 1/3

string x = null;
Console.WriteLine(x??x??x??...??x??"Hello, world!");

Score calculation:

lim(x→x/(x*3+53))
x→∞

If you feel the need to wrap this all in a class with a Main method... it doesn't change the score.


Haskell, 64 62 59 57 45 35 31 bytes

d l=sum(zipWith(*)[1..]l)/sum l

Try it online!


05AB1E, 13 bytes

εD>)ÅÈε€θγg}{

Try it online!

Thanks to Emigna for the heads-up on spec changes.

Explanation

εD>)ÅÈε€θγg}{ – Full program.
ε             – For each book...
 D            – Push two copies of it.
  >           – Increment all the elements of the second copy.
   )          – Wrap the whole stack into a list.
    ÅÈ        – Produces the lists of even natural numbers lower or equal to each element.
      ε       – For each (the modified copies of the book):
       €θ     – Get the last item of each.
         γg   – And split into chunks of equal adjacent elements.
           }  – Close the loop.
            { – Sort the resulting list.


MATL, 20 bytes
U|sG36ZA13\[BID1]m+g

Input is a string enclosed in single quotes. Output is 1 for truthy or 0 for falsy.
Try it online! Or verify all test cases.
How it works
U|s      % Take input implicitly. Interpret as number, absolute value, sum
G36ZA    % Push input again. Convert from base-36
13\      % Modulo 13
[BID1]   % Push array [6 3 8 1]
m        % True if member: gives 1 iff the result from modulo 13 is in the array
+g       % Add, convert to logical. Display implicitly

This performs two tests on the input:

Try to interpret the input as a number, and detect if it is nonzero. The function used to interpret a string as a number outputs an empty array if it's not possible; and the sum of the entries of an empty array is 0. So it suffices to try the conversion, take the absolute value, and sum. This gives a positive value if the input contains a nonzero number, and 0 otherwise.
Assuming the input string doesn't represent a number, we need to classify it into one of the two given sets. To do this, the input is interpreted as the digits of a number expressed in base-36, using alphabet '01...9ab...z'. The base conversion function is case-insensitive and ignores digits not present in the alphabet (in our case, '-'). It turns out that the modulo 13 of the resulting number is 1, 3, 6 or 8 for the truthy strings, and doesn't give any of those values for the falsy strings. So it can be used as a signature. We thus perform modulo 13 and see if the result is any of those four values. This gives 1 if it is, or 0 otherwise.

The final result should be truthy if any of the two conditions is met, and falsy otherwise. So we add the two numbers resulting from 1 and 2 above and convert to logical, which gives 1 or 0 as standardized truthy/falsy values.


Brainfuck
Oh god why did I do this to myself?
It is actually possible to find each BF symbol by itself as a code snippet in some answer somewhere. The interesting bit was piecing together bits of other people's code, each representing a block of BF instructions. Unfortunately there are basically no unmatched [ and ] symbols out there, so I had to cheat a bit for those, and I had to get an awful lot of mileage out of a funky Haskell snippet which had a bunch of pluses in it. There are probably others out there. Beyond that, here's some Frankensteined code:
byte x = 1;
byte y = 2;
byte z = x + y;   // ERROR: Cannot implicitly convert type 'int' to 'byte'
addop = do {symb "+"; return Op Add}  +++ do {symb "-"; return Op Sub}
addop = do {symb "+"; return Op Add}  +++ do {symb "-"; return Op Sub}
addop = do {symb "+"; return Op Add}  +++ do {symb "-"; return Op Sub}
[
int a = (b > 10) ? some_value
                 : another_value;
addop = do {symb "+"; return Op Add}  +++ do {symb "-"; return Op Sub}
int a = (b > 10) ? c : d;
byte x = 1;
byte y = 2;
byte z = x + y;   // ERROR: Cannot implicitly convert type 'int' to 'byte'
addop = do {symb "+"; return Op Add}  +++ do {symb "-"; return Op Sub}
addop = do {symb "+"; return Op Add}  +++ do {symb "-"; return Op Sub}
addop = do {symb "+"; return Op Add}  +++ do {symb "-"; return Op Sub}
?"<<-"
]
exec >{space}> (command)
byte z = (int) x + (int) y;
addop = do {symb "+"; return Op Add}  +++ do {symb "-"; return Op Sub}
find . -type f -print -exec cat {} \;
git reset .
byte x = 1;
byte y = 2;
byte z = x + y;   // ERROR: Cannot implicitly convert type 'int' to 'byte'
addop = do {symb "+"; return Op Add}  +++ do {symb "-"; return Op Sub}
addop = do {symb "+"; return Op Add}  +++ do {symb "-"; return Op Sub}
System.out.print("B");
addop = do {symb "+"; return Op Add}  +++ do {symb "-"; return Op Sub}
fatal: Failed to resolve 'HEAD' as a valid ref.
while read p; do
echo $p
done < $filename
static HMODULE hMod = NULL;
  static bool once = false;
  if (!once++)
    hMod = LoadLibrary("xxx");
 if (originalValue.length > size) {
static HMODULE hMod = NULL;
  static bool once = true;
  if (once--)
    hMod = LoadLibrary("xxx");
$ cd /usr/local/wherever
$ grep timmy accounts.txt
addop = do {symb "+"; return Op Add}  +++ do {symb "-"; return Op Sub}
addop = do {symb "+"; return Op Add}  +++ do {symb "-"; return Op Sub}
addop = do {symb "+"; return Op Add}  +++ do {symb "-"; return Op Sub}
ls -ld $(find .)
git commit --amend -m "New commit message"
wget -q -O - $line
git rebase --interactive $parent_of_flawed_commit
find . -type f -user 'user1' -maxdepth 1

And, since my mother is British, the output is quite simply hello mum
Bibliography:
https://stackoverflow.com/questions/17845014/what-does-the-regex-mean
[ and ], with apologies
https://stackoverflow.com/a/21460161/2581168
find . -type f -print -exec cat {} \;

https://stackoverflow.com/questions/6161328/what-exactly-does-this-do-exec-command
exec >{space}> (command)

https://stackoverflow.com/questions/20130538/what-is-in-haskell
addop = do {symb "+"; return Op Add}  +++ do {symb "-"; return Op Sub}

https://stackoverflow.com/questions/21947452/why-is-printing-b-dramatically-slower-than-printing
System.out.print("B");

https://stackoverflow.com/questions/941584/byte-byte-int-why
byte x = 1;
byte y = 2;
byte z = x + y;   // ERROR: Cannot implicitly convert type 'int' to 'byte'

https://stackoverflow.com/a/160295/2581168
int a = (b > 10) ? c : d;

And
int a = (b > 10) ? some_value
                 : another_value;

https://stackoverflow.com/questions/13273002/what-does-mean-in-r
?"<<-"

https://stackoverflow.com/questions/3450420/bool-operator-and
static HMODULE hMod = NULL;
static bool once = false;
if (!once++)
    hMod = LoadLibrary("xxx");

And
static HMODULE hMod = NULL;
static bool once = false;
if (!once--)
    hMod = LoadLibrary("xxx");

https://stackoverflow.com/questions/22776085/in-which-case-will-size-originalvalue-length-in-string-constructor-string
if (originalValue.length > size) {

https://stackoverflow.com/questions/3797795/does-mean-stdout-in-bash
wget -q -O - $line

https://stackoverflow.com/questions/179123/how-do-i-edit-an-incorrect-commit-message-in-git/179147#179147
git commit --amend -m "New commit message"

And
git rebase --interactive $parent_of_flawed_commit

https://stackoverflow.com/questions/14763413/grep-ls-output-across-tabs/14763499#14763499
find . -type f -user 'user1' -maxdepth 1

https://stackoverflow.com/questions/945288/saving-current-directory-to-bash-history
$ cd /usr/local/wherever
$ grep timmy accounts.txt

https://stackoverflow.com/questions/348170/undo-git-add-before-commit/682343#682343
fatal: Failed to resolve 'HEAD' as a valid ref.


Jelly, 10 8 6 bytes

2 bytes thanks to @orlp.

2 bytes thanks to @Dennis.

_+\ṠQS

Try it online!

1 for a>b, -1 for a<b, 0 for no majorization.

_+\ṠQS

_       Difference (vectorized)
 +\     Cumulative sum.
   Ṡ    Sign of every difference
    Q   Deduplicate
     S  Sum

If there were both 1 and -1 present (some cumulative sums are bigger, some smaller), then the last step would produce 0.


CJam, 53 51 50 49 bytes
Plain old base conversion...
"FÓîÞ¤ÛYËB[¢O²êÍÓ
}²|äG"299b4b"+ -|"f=B/N*

All characters are well in extended ASCII range (ASCII code 1 to 255), so number of characters == number of bytes.
Try it online here and get the original code here


Bash, 54 48 bytes
-6 bytes by adapting Dominic van Essen's output-prevention trick
printf ":|:
((s+=p<$1?$1-2*p:$1))
p=$1
echo \$s"

This assumes the program must not have any excess output, which turns out to be one of the tricker parts. I expect one of the golfing languages that will output by default at the end of the program would do best here.
Try it online!
Explanation
Example output for 3 concatenated with output for 10 (the concatenated program outputs 7):
:|:
((s+=p<3?3-2*p:3))
p=3
echo $s:|:
((s+=p<10?10-2*p:10))
p=10
echo $s

:|: prevents any echo from a previous fragment from outputting
s is the sum value so far (implicitly 0 at the start of the program)
p is the previous value

Each fragment assumes that the current value is not less than the next value, and thus adds it to the sum. It also checks whether the previous fragment was wrong to assume this (ie. the previous value was less than the current value), and if so corrects the sum by subtracting double the previous value.


Python, 67 bytes

f=lambda n,R=[1]:n-sum(R)and f(n,[R+[R[-1]+1],R[1:]][sum(R)>n])or R

An oddly straightforward strategy: search for the interval R with the right sum.

If the sum is too small, shift the right endpoint of the interval up
one by appending the next highest number.
If the sum is too large, shift up the left endpoint by removing the smallest element
If the sum is correct, output R.

Since the bottom end of the interval only increases, longer intervals are found before shorter ones.


J, 61 56 53 52 bytes
1 :0
('0'".@,~,@,.&' ')[u".@;@}:@,@,."1;:@'=: & &'
)

Try it online!
Note: -3 bytes off TIO for f=:
Operator changes used to match J's built-ins:

** -> ^
/ -> %
= -> ]

Additional notes:

This is adverb that modifies the program to interpret, which is given as a list of 3-element directives.  The resulting verb then takes the input as an argument, and returns the result.
Assumes the program string to execute will be read from right-to-left -- again, this is in keeping with J's normal convention.


Retina, 2 bytes, 10 numbers, by Martin Ender.
Original code:

1

This replaces the empty input by the number 1.
Code that produces 1 - 10 (showing newlines as \n for convenience):
1 : \n1
2 : \n1\n
3 : \n11\n
4 : \n111\n
5 : \n1111\n
6 : \n11111\n
7 : \n111111\n
8 : \n1111111\n
9 : \n11111111\n
10: \n111111111\n

For 2 and onwards, we count the number of empty strings in the previous stage. For 2, there is an empty string before and after the 1. For 3 there is an empty string before the ones, in between the ones and after the ones. This works all the way up to 10.
Try it online


Rebmu (35 32 chars)

u[iG^aNXa[rvA]apGtkFaM?fA]apGscA

Test

>> rebmu/args [u[iG^aNXa[rvA]apGtkFaM?fA]apGscA] [[1 5 10 17 19] [2 5 9 11 13 20]]
== [1 2 5 5 9 10 11 13 17 19 20]

>> rebmu/args [u[iG^aNXa[rvA]apGtkFaM?fA]apGscA] [[2 5 9 11 13 20] [1 5 10 17 19]]
== [1 2 5 5 9 10 11 13 17 19 20]

About

Rebmu is a dialect of Rebol that permits 'mushing' of regular code for situations that require brevity. Unmushed, the code works somewhat like:

u [                     ; until
    i g^ a nx a [       ; if greater? args next args
       rv a             ; reverse args
    ]                   ; (we want the block containing the next value first)

    ap g tk f a         ; append output take first args
    m? f a              ; empty? first args
]                       ; (first block is now empty)

ap g sc a               ; append output second args
                        ; (add the remainder of the second)

I believe this satisfies the O(n) requirement as the until block is at most looped as many times as the length of the input (and the reverse only switches the order of the container of the input blocks, not the blocks themselves). Using take is perhaps a liberty, but is still a minor efficiency hit.

Rebol (83 75 chars)

Just a wee bit different: in Rebol, paths are a shorter expression than first or second. a is the input block containing the two blocks:

until[if a/2/1 < a/1/1[reverse a]append o:[]take a/1 tail? a/1]append o a/2


JavaScript (ES6),  72 68   67 bytes
Expects (max_denominator)(seq). Returns [numerator, denominator].

m=>g=([v,...a],n=0,d=1,N=1,D=0)=>(d+=D*v)<=m?g(a,N,D,N*v+n,d):[N,D]

Try it online!
Commented
m =>             // outer function taking m = maximum denominator
g = (            // inner recursive function taking:
  [v,            //   v = next term from the continued fraction
      ...a],     //   a[] = remaining terms
  n = 0,         //   n = previous numerator
  d = 1,         //   d = previous denominator
  N = 1,         //   N = current numerator
  D = 0          //   D = current denominator
) =>             //
  (d += D * v)   // we compute the new denominator d = D * v + d
                 // this results in NaN if v is undefined,
                 // which forces the comparison to fail
  <= m ?         // if it's less than or equal to m:
    g(           //   do a recursive call:
      a,         //     pass the remaining terms of the continued fraction
      N, D,      //     pass the current numerator and denominator
      N * v + n, //     pass the new numerator
      d          //     pass the new denominator
    )            //   end of recursive call
  :              // else:
    [N, D]       //   we're done: return [N, D]


21 bytes, solves Shortest code to throw SIGILL (safe)
“A{gœỴ¹⁻ėe⁾÷ỤḞḂ4ḷ$»ŒV

Try it online!
This decompresses to the following Python 3 code (which is 22 bytes long, only one byte longer than the compressed version):
import os
os.kill(0,4)

Try it online!
The basic idea is to pick a task that's completely out of scope for Jelly; in this case, we're interacting with the OS, something that Jelly doesn't have builtins for (short of ŒV). So this probably isn't solvable in Jelly without shelling out to Python, and hopefully isn't solvable any more tersely than this.
(In case you're wondering how it works: 4 is the signal number for SIGILL, and os.kill appears to just copy its arguments to the kill(2) system call literally. 0 means "send this signal to every process in my process group", which if the program is run from a shell, will raise a SIGILL in the Python/Jelly program and nothing else. On TIO, the program is being run from TIO's runner, so the SIGILL happens in the runner rather than in the program itself, but there's still a SIGILL being raised.)


Retina, 21 bytes

+`(.)(?!\1)(?i)\1

^$

Try it online!

Like flawr's solution, this just repeatedly deletes adjacent uppercase/lowercase pairs and then checks whether the result is empty or not.

As for how one matches an uppercase/lowercase pair:

(.)     # Match and capture a letter.
(?!\1)  # Ensure that the next character is not the same, to avoid matching
        # "aa" and "AA".
(?i)    # Turn on case-insensitivity.
\1      # Match the backreference. In .NET, when using case insensitivity,
        # backreferences also get case-insensitive, so this *can* still match
        # iff the cases of the two letters are different.


Charcoal, 72 bytes
ＦＳ≡ι(«⊞υⅉＰ⌈┌´·↘→⊞υⅉ»)«≔⊕⊟υιＭ¹⁻ιⅉ┘Ｍ⁻ⅉ⊟υ↑¿υ⊞υ⌈⟦ι⊟υ⟧»,«↑≔ＫＤ⊕ⅈ←ι§≔ι⊖⌕ι┌¦─↘»ι

Try it online! Link is to verbose version of code. Uses lists rather than arrays because they're easier to input. Explanation:
ＦＳ≡ι

Switch over each character of the input as a string.
(«

For a (, ...
⊞υⅉ

... save the vertical position as the top margin, ...
Ｐ⌈┌´·↘→

... assume a single-element list, ...
⊞υⅉ

... and save the vertical position again, this time as the bottom margin.
»)«

For a ), ...
≔⊕⊟υι

... get the bottom margin of this list, plus 1, ...
Ｍ¹⁻ιⅉ

... move to that row, ...
┘

... close the list, ...
Ｍ⁻ⅉ⊟υ↑

... move to and forget the top margin of this list, ...
¿υ⊞υ⌈⟦ι⊟υ⟧

... and update the bottom margin of the containing list if necessary.
»,«

For a ,, ...
↑≔ＫＤ⊕ⅈ←ι

... grab the text on the previous row, ...
§≔ι⊖⌕ι┌¦─

... find the ┌ and change the character after it to a ─, ...
↘

... and move to the next column on the original row.
»ι

Otherwise, just output the current character.
Note that the · is in Charcoal's code page (so because it needs to be quoted it ends up costing me two bytes!) but the box-drawing characters are not. They would normally cost three bytes in Charcoal so as I use them four times I have subtracted 8 bytes from Charcoal's calculation.


Bash, 90 bytes

This works on Ubuntu, and requires evtest. It picks a device that is a keyboard, and saves evtest's output to the file l. If you want a more formatted output, I can do that with more bytes.

echo I\'m gonna log you
sudo evtest /dev/input/by-path/`ls /dev/input/by-path/|grep kbd`>l


Haskell, 139 bytes

q=length
g x|l<-lines x,m<-maximum$q<$>l,s<-[-1..m]>>"═"='╔':s++"╗\n"++(l>>= \z->"║ "++z++([q z..m]>>" ")++"║\n")++'╚':s++"╝"

As an example I'm framing snowman "12333321".

*Main> putStrLn $ g " _===_\n (O.O)\n/(] [)\\\n ( : )"
╔═════════╗
║  _===_  ║
║  (O.O)  ║
║ /(] [)\ ║
║  ( : )  ║
╚═════════╝

How it works:

bind
  l: input split into lines
  m: maximum line length
  s: m+2 times ═

build top line
prepend left frame to each line, pad with spaces, append right frame
build bottom line.


Jelly, 7 bytes

2Rṁxṁµ¡

This is a full program that prints the first n terms.

Try it online!

How it works

2Rṁxṁµ¡  Main link. Argument: n (integer)

     µ   Combine the preceding links into a monadic chain.
      ¡  Set t = n.  Call the chain n times, updating t with the return value after
         each call. Yield the last value of t.
2R           Set the return value to 2 and take its range. Yields [1, 2].
  ṁ          Mold; cyclically repeat 1 and 2 to match t's length.
             In the first run, ṁ promotes t = n to [1, ..., n].
   x         Repeat the k-th element of the result t[k] times.
             In the first run, x repeats each element t = n times.
    ṁ        Mold; truncate the result to match the length of t.
             In the first run, ṁ promotes t = n to [1, ..., n].

Example run

Let n = 5.

The first invocation of the chain repeats 1, 2 cyclically to reach length 5, then each element 5 times, and finally truncates the result to length 5.

  1         2         1         2         1
x 5         5         5         5         5
---------------------------------------------------
  1 1 1 1 1 2 2 2 2 2 1 1 1 1 1 2 2 2 2 2 1 1 1 1 1

  1 1 1 1 1

This yields a list of length 5. The first element is the first element of the Kolakoski sequence.

The second invocation of the chain repeats 1, 2 cyclically to reach length 5, then repeats the kth element j times, where j is the kth element of the previous list, and finally truncates the result to length 5.

   1 2 1 2 1
x  1 1 1 1 1
------------
   1 2 1 2 1

   1 2 1 2 1

This yields another list of length 5. The first two elements are the first two elements of the Kolakoski sequence.

The process continues for three more iterations.

   1 2   1 2   1
x  1 2   1 2   1
----------------
   1 2 2 1 2 2 1

   1 2 2 1 2

   1 2   1   2 1
x  1 2   2   1 2
------------------
   1 2 2 1 1 2 1 1

   1 2 2 1 1

   1 2   1   2 1
x  1 2   2   1 1
----------------
   1 2 2 1 1 2 1

   1 2 2 1 1

These are the first five elements of the Kolakoski sequence.


Putting one tip per answer would be way too many answers.

Learn to think in Brainfuck. It's very different than anything else. Read and write, and rewrite, and rewrite lots of brainfuck programs. The language doesn't give you much to work with, so it's important to use what it does give you flexibly and efficiently. Don't let any abstractions get between you and the language--get in there and grapple with it.
Get very comfortable with nondestructive flow control. To get out of a decision loop, rather than zeroing the starting cell by copying it elsewhere and then copying it back after leaving the loop, it's often better to move the pointer to a pre-existing zero nearby. Yes, this means the pointer will be in different places depending on whether you went through the loop, but that also means those places probably have different arrangements of nearby zeros and nonzeros, which you can use to resynch the pointer location using another loop. This technique is fundamental to good Brainfuck programming, and various forms of it will constantly prove useful.
That and the fact that every > or < costs mean that the details of memory layout are important. Try out as many variations of your layout as you have patience for. And remember, your memory layout does not have to be a rigid mapping of data to locations. It can morph over the course of execution.
On a larger scale, consider and even try implementing a variety of different algorithms. Initially it will not be obvious exactly what algorithm will be best; it may not even be obvious what basic approach will be best, and it will probably be something different than what would be best in a normal language.
If you're dealing with large or variable-sized data, see if there's any way you can possibly deal with it locally, without having to keep track of how big it is or your numerical location within it.
The same data can be two different things. (Most often, a number or character and also a nonzero positional marker. But see random.b, where a bit counter doubles as the value of one cell of a cellular automaton.)
The same code can do two different things, and it's a lot easier to make it do so in a language where code is as generic as <+<. Be alert to such possibilities. In fact, you may occasionally notice, even in what seems to be a well-written program, that there are small portions that could be deleted entirely, nothing added, and the thing would, by happenstance, still run flawlessly.
In most languages, you use a compiler or interpreter frequently to check your program's behavior. The Brainfuck language demands greater conceptual control; if you need a compiler to tell you what your program does, you don't have a firm enough grasp of your program, and you probably need to stare at it some more--at least if you want to have a clear enough image of the conceptual halo of similar programs to be good at golf. With practice, you'll be producing a dozen versions of your program before you try running one, and by that point you'll be 95% sure that your shortest one will run correctly.
Good luck! Very few people bother to write Brainfuck concisely, but I think that's the only way the language can possibly justify continuing attention--as a stunningly obscure art form.


Jelly, 25 bytes

Lẋ@Zɗ⁺ZU$3Ð¡;ŒD$€Ẏw€⁸ẸðÐf

A dyadic link accepting a list of lists of characters (the words) on the left and a list of lists of characters (the rows of the grid) on the right which returns a list of list of characters (the found words).

Try it online!

How?

Filters the words by their existence in the grid tiled to be word-length times as wide and word-length times as high:

Lẋ@Zɗ⁺ZU$3Ð¡;ŒD$€Ẏw€⁸ẸðÐf - Link: words, grid
                       Ðf - filter (the words) keeping those for which
                      ð   - ...the dyadic link to the left ...is truthy:
     ⁺                    -   perform this twice:
    ɗ                     -     last three links as a dyad:
L                         -       length (of the current word)
 ẋ@                       -       repeat (the rows) by (that number)
   Z                      -       transpose (making the rows become the columns)
         3Ð¡              -   repeat three times and collect the results (inc input):
        $                 -     last two links as a monad:
      Z                   -       transpose
       U                  -       upend     (together these rotate by a quarter)
                €         -   for €ach:
               $          -     last two links as a monad:
             ŒD           -       get forward-diagonals
            ;             -       concatenate
                 Ẏ        -   tighten (to get all the runs across the grid)
                    ⁸     -   chain's left argument (the word)
                   €      -   for €ach run:
                  w       -     sublist-index (0 if not found)
                     Ẹ    -   any truthy? (i.e. was the word found?)


FirstRacer Java (5825 + 305*10 = 8875)

Just to have a start. Needs 305 segments on City.

This Java program does it pipelined:

read the image
A* (A star)

2.1 Build the A* search landscape.
2.2. Track back looking only for the best *direct* 8 neighbor cells (N,S,E,W,NE,NW,SE,SW). This finds the shortest track t0 pixelwise.

stay on t0 and optimize it for speed by eliminating pixels. Fullfilling the constraint by never be faster than 7 (this translates to keep at least every 7th pixel).
draw the track into the image
show the resulting image.

package race;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Vector;

import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.WindowConstants;

public class AStar {

    private static BufferedImage img;
    private static int Width;
    private static int Height;
    private static int[][] cost;
    private static int best=Integer.MAX_VALUE;
    private static Point pBest;

    public static void main(String[] args) throws IOException {
        String file = "Q46YG.png";
        img = read(file);
        Width=img.getWidth();
        Height=img.getHeight();

        Vector<Point> track = astar();
        track = optimize(track);
        draw(track);
        System.out.println(10 * track.size());

        JFrame frame = new JFrame(file) {
            public void paint(Graphics g) {
                setSize(Width+17, Height+30+10);
                g.drawImage(img,8,30,null);
            }
        };
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }

    private static Vector<Point> optimize(Vector<Point> track) {
        Vector<Point> opt=new Vector<Point>();
        Point p0 = track.get(0);
        Point p1 = track.get(1);
        int v=0;
        opt.add(p0);
        int vx0=p1.x-p0.x, vy0=p1.y-p0.y;
        for (int i = 2; i < track.size(); i++) {
            Point p = track.get(i);
            if (v<7 && vx0==p.x-p1.x && vy0==p.y-p1.y) {
                v++;
            } else {
                v=0;
                opt.add(p1);
                vx0=p.x-p1.x;
                vy0=p.y-p1.y;
            }
            p1=p;
        }
        opt.add(p1);
        return opt;
    }

    private static void draw(Vector<Point> track) {
        Graphics2D g = img.createGraphics();
        Point p0 = track.get(0);
        for (int i = 1; i < track.size(); i++) {
            Point p1 = track.get(i);
            g.setColor(Color.WHITE);
            g.drawLine(p0.x, p0.y, p1.x, p1.y);
            img.setRGB(p0.x, p0.y, 0xff0000ff);
            img.setRGB(p1.x, p1.y, 0xff0000ff);
            p0=p1;
        }
    }

    private static Vector<Point> astar() {
        Vector<Point> v0=findStart();
        for(int i=0; ; i++) {
            Vector<Point> v1=next(v0);
            if (v1.size()==0) break;
            v0=v1;
        }
        Vector<Point> track=new Vector<Point>();
        Point p0 = pBest;
        int x0=p0.x, y0=p0.y;
        int c0=cost[x0][y0];
        while(true) {
            int x=x0, y=y0;
            track.add(0, new Point(x, y));
            for (int x1 = x-1; x1 <= x+1; x1++) {
                for (int y1 = y-1; y1 <= y+1; y1++) {
                    int i1=getInfo(x1, y1);
                    if ((i1&2)==2) {
                        int c=cost[x1][y1];
                        if (c0>c) {
                            c0=c;
                            x0=x1;
                            y0=y1;
                        }
                    }
                }
            }
            if(x0==x &&y0==y) break;
        }
        return track;
    }

    private static Vector<Point> next(Vector<Point> v0) {
        Vector<Point> v1=new Vector<Point>();
        for (Point p0 : v0) {
            int x=p0.x, y=p0.y;
            int c0=cost[x][y];
            for (int x1 = x-1; x1 <= x+1; x1++) {
                for (int y1 = y-1; y1 <= y+1; y1++) {
                    int i1=getInfo(x1, y1);
                    if ((i1&2)==2) {
                        int c1=c0+1414;
                        if (x1==x || y1==y) {
                            c1=c0+1000;
                        }
                        int c=cost[x1][y1];
                        if (c1<c) {
                            cost[x1][y1]=c1;
                            Point p1=new Point(x1, y1);
                            v1.add(p1);
                            if (i1==3) {
                                if (best>c1) {
                                    best=c1;
                                    pBest=p1;
                                }
                            }
                        }
                    }
                }
            }

        }
        return v1;
    }

    private static Vector<Point> findStart() {
        cost=new int[Width][Height];
        Vector<Point> v=new Vector<Point>();
        for (int i = 0; i < Width; i++) {
            for (int j = 0; j < Height; j++) {
                if (getInfo(i,j)==1) {
                    cost[i][j]=0;
                    v.add(new Point(i, j));
                } else {
                    cost[i][j]=Integer.MAX_VALUE;
                    pBest=new Point(i, j);
                }
            }
        }
        return v;
    }

    /**
     * 1: You can start your car on any yellow pixel,
     * 3: and you must finish by crossing any black pixel.
     * 2: The path of your car must be only on the grey ((c,c,c) where 30 <= c <= 220) track.
     * 0: else
     *
     * @param x
     * @param y
     * @return
     */
    private static int getInfo(int x, int y) {
        if (x<0 || x>=Width || y<0 || y>=Height) return 0;
        int rgb = img.getRGB(x, y);
        int c=0;
        switch (rgb) {
        case 0xffffff00: c=1; break;
        case 0xff000000: c=3; break;
        default:
            int r=0xff&(rgb>>16);
            int g=0xff&(rgb>> 8);
            int b=0xff&(rgb>> 0);
            if (30<=r&&r<=220&&r==g&&g==b) c=2;
        }
        return c;
    }

    private static BufferedImage read(String file) throws IOException {
        File img = new File("./resources/"+file);
        BufferedImage in = ImageIO.read(img);
        return in;
    }

}

I think the Race Track gives you a better impression how FirstRacer works.


Format a floating point number exactly as decimal

CJam, 43

r_'-&\ize999rim<s1e3'0e[W%999/(i_L?\+'.*sW%

Try it online

Explanation:

The program works with exponents up to ±999, close to double precision (64 bit). It separates the minus sign (if present) from the significand, multiplies it by 10999 then does a bit shift with the exponent, which is now an exact calculation. It then pads to the left with zeros if the result has less than 1000 digits, separates the last 999 digits as the fractional part, removes trailing zeros by converting its reverse to integer, adds a decimal point if needed, and puts everything back together.

r_         read and duplicate the significand in string form
'-&        keep only the minus sign, if present
\          swap with the other copy of the significand
iz         convert to integer and get absolute value
e999       multiply by 10^999
ri         read the exponent and convert to integer
m<         shift left by it; negative values will shift right
            the result is an exact non-negative integer
s          convert to string
1e3'0e[    pad to the left with zero characters up to length 1000
            longer strings will be left intact
            we need 1 more than 999 for the 0.xxx case
W%         reverse the string
999/       split into slices of length 999
(          take out the first slice (reversed fractional part)
i          convert to integer
            this removes the leading zeros (trailing in reverse)
_L?        if it's zero, replace with an empty string
\+         concatenate back (to the left) with the second slice
'.*        join the with the dot character
            if the fractional part was zero, we only have the second slice
            (reversed integer part) and there is nothing to join
s          convert to string; this is the reversed result without the sign
W%         reverse back

At the end, the minus sign (if any) and the final string are automatically printed together.


Haskell, 169 150 148 141 132 131 bytes

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

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

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

Usage:

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


Python 3, 71 65 61 bytes

lambda z:sum((ord(s)*1.5**(s<'_')-96)**s.isalpha()for s in z)

By an extraordinary coincidence, (ord(s)-64)*1.5 is equal to ord(s)*1.5-96, so we only have to write -96 once. The rest is pretty straight forward.

Edit: Shaved off some bytes using exponentiation shenanigans.


Mathematica, 85 bytes
#~FromDigits~#2~IntegerDigits~#3//.{p___,a_:0,b_,q___}/;b>⌊#3/2⌋:>{p,a+1,b-#3,q}&

Explanation
#~FromDigits~#2

Convert #1 (1 is implied--input 1, a list of digits) into an integer base #2 (input 2).
... ~IntegerDigits~#3

Convert the resulting integer into base #3 (input 3), creating a list of digits.
... //.{p___,a_:0,b_,q___}/;b>⌊#3/2⌋:>{p,a+1,b-#3,q}

Repeatedly replace the list of digits; if a digit is greater than floor(#3/2), then subtract #3 from it and add 1 to the digit to the left. If there is nothing on the left, insert a 0 and add 1.


APL, 7

In APL you can choose if you want to work with index 0 or index 1.
You do this by setting global variable ⎕IO←0

If we choose to work in index 0 we have:

+\3⌊1⌈⍳

Explanation:

⍳    creates a sequence 0...n   (0 1 2 3 4 5)
1⌈   takes whichever is bigger, number in sequence or 1 (1 1 2 3 4 5)
3⌊   takes whichever is lower, number in sequence or 3 (1 1 2 3 3 3)
+\   partial sums for the sequence (1 2 4 7 10 13)

Try it on tryapl.org


Java: 1523 1512 chars

import java.util.*;class W{int v=99;Map<Integer,String>t;boolean k;public static void main(String[]y){new W().d();}W(){try{java.io.InputStream i=new java.io.File("r").toURL().openStream();t=new HashMap<>();int a=0,x=0,y=0;while((a=i.read())>-1){if(a==10){y++;x=0;continue;}q(x,y,(a>47&a<58?"!":"")+(char)a);x++;}}catch(Exception e){}}void d(){while(!k){k=!k;for(Map.Entry<Integer,String>g:t.entrySet())e(g.getKey(),g.getValue());}for(String b:t.values())if(b.startsWith("$"))System.out.println(b.substring(1));}void e(int a,String s){if(s==null||!s.startsWith("!"))return;int x=a/v,y=a%v;s=s.substring(1);b(s,x,y,x-1,y+1);b(s,x,y,x,y+1);b(s,x,y,x+1,y+1);b(s,x,y,x-1,y);b(s,x,y,x+1,y);b(s,x,y,x-1,y-1);b(s,x,y,x,y-1);b(s,x,y,x+1,y-1);}void b(String p,int m,int n,int x,int y){String s=t.get(x*v+y);if(s==null)return;boolean g=y==n+1;boolean h=y==n-1;boolean i=x==m+1;boolean j=x==m-1;if(z(s,"-=")&n==y){if(i)b(p,x,y,x+1,y);if(j)b(p,x,y,x-1,y);}if(z(s,"|=")&m==x){if(g)b(p,x,y,x,y+1);if(h)b(p,x,y,x,y-1);}if(z(s,"/=")){if(j&g)b(p,x,y,x-1,y+1);if(i&h)b(p,x,y,x+1,y-1);}if(z(s,"\\=")){if(i&g)b(p,x,y,x+1,y+1);if(j&h)b(p,x,y,x-1,y-1);}if(z(s,".")){q(x,y,"!"+p);u();}if(z(s,"~")){q(x,y,"!~("+p+")");u();}if((s.charAt(0)=='%'&n==y-1)|(s.charAt(0)=='&'&n==y+1)){q(x,y,"!("+p+")"+s.charAt(1)+"("+s.substring(2)+")");u();}if(z(s,"OoAaXx")){q(x,y,(n==y+1?"%":"&")+s+p);u();}if(z(s,":")){q(x,y,"$"+p);u();}}void q(int x,int y,String z){t.put(x*v+y,z);}void u(){k=false;}boolean z(String s,String c){return c.indexOf(s)>-1;}}

It gives this output for the sample input:

(~(((5)X(4))O(3)))a(~(1))
((~(((5)X(4))O(3)))a(~(1)))X(((2)x(1))x(3))

In order to squeeze its size:

It does not do any error checking, error handling or input validation, assuming that the input is always valid.
Is limited to 99 lines of input.
Its input file must be called just r, without any file extension in the name.
It does not makes any effort to detect if the parenthesis are or aren't necessary. It assumes that they always are necessary, and since this assumption is false, there is a lot more parenthesis than needed, but since this does not makes it fail the spec anyway, it is no problem.
The order of the parameters to each binary operator is in general unpredictable, as it depends on the velocity that the values are propagated and from cell scanning order. But since all the binary operators are commutative, this should be no problem.

I am sure that it should be possible to reduce it more, but just a bit.

The interpreter is implemented in the form of some sort of cellular automata. It scans the entire field setting values, repeating it as many times as needed until no changes are detected.

Here is an ungolfed version:

import java.util.*;

class Wiring {

    int maxLines = 99;
    Map<Integer, String> circuitState;
    boolean finished;

    public static void main(String[] args) {
        new Wiring().interpret();
    }

    Wiring() {

        try {
            // Always read the input from the "r" file, and do not check if it even
            // exists. BTW, the toURL() method is deprecated, but we don't care about
            // this in code-golfing.
            java.io.InputStream stream = new java.io.File("r").toURL().openStream();

            circuitState = new HashMap<>();
            int byteRead = 0, cellX = 0, cellY = 0;

            while ((byteRead = stream.read()) > -1) {

                // Check for line break;
                if (byteRead == 10) {
                    cellY++;
                    cellX = 0;
                    continue;
                }

                // Populate the circuit cell. Precede numbers with an exclamation mark.
                setCircuitCell(cellX, cellY, (byteRead >= '0' & byteRead <= '9' ? "!" : "") + (char) byteRead);
                cellX++;
        } catch (Exception e) {
        }
    }

    void interpret() {
        while (!finished) {
            finished = !finished; // i.e. finished = false;
            for (Map.Entry<Integer, String> entry : circuitState.entrySet()) {
                analyzeCell(entry.getKey(), entry.getValue());
            }
        }

        // Now print the output. To do that scan for cells marked with "$".
        for (String cell : circuitState.values()) {
            if (cell.startsWith("$")) System.out.println(cell.substring(1));
        }
    }

    void analyzeCell(int cellIndex, String cellValue) {
        // Only the cells with a value marked with "!" are worth to analyze.
        if (cellValue == null || !cellValue.startsWith("!")) return;

        // Convert the cellIndex to a bidimensional coordinate.
        int x = cellIndex / maxLines, y = cellIndex % maxLines;

        // Remove the "!".
        cellValue = cellValue.substring(1);

        // Propagate the cell value to neighbouring cells.
        propagateCellData(cellValue, x, y, x - 1, y + 1);
        propagateCellData(cellValue, x, y, x, y + 1);
        propagateCellData(cellValue, x, y, x + 1, y + 1);
        propagateCellData(cellValue, x, y, x - 1, y);
        propagateCellData(cellValue, x, y, x + 1, y);
        propagateCellData(cellValue, x, y, x - 1, y - 1);
        propagateCellData(cellValue, x, y, x, y - 1);
        propagateCellData(cellValue, x, y, x + 1, y - 1);
    }

    void propagateCellData(String cellValue, int sourceX, int sourceY, int targetX, int targetY) {
        String targetContent = circuitState.get(targetX * maxLines + targetY);

        // If the target cell does not exist, just ignore.
        if (targetContent == null) return;

        boolean targetBelowSource = targetY == sourceY + 1;
        boolean targetAboveSource = targetY == sourceY - 1;
        boolean targetRightToSource = targetX == sourceX + 1;
        boolean targetLeftToSource = targetX == sourceX - 1;

        // Propagate horizontally through wires.
        if (isStringContained(targetContent, "-=") & sourceY == targetY) {
            if (targetRightToSource) propagateCellData(cellValue, targetX, targetY, targetX + 1, targetY);
            if (targetLeftToSource) propagateCellData(cellValue, targetX, targetY, targetX - 1, targetY);
        }

        // Propagate vertically.
        if (isStringContained(targetContent, "|=") & sourceX == targetX) {
            if (targetBelowSource) propagateCellData(cellValue, targetX, targetY, targetX, targetY + 1);
            if (targetAboveSource) propagateCellData(cellValue, targetX, targetY, targetX, targetY - 1);
        }

        // Propagate in the diagonal x=-y.
        if (isStringContained(targetContent, "/=")) {
            if (targetLeftToSource & targetBelowSource) {
                propagateCellData(cellValue, targetX, targetY, targetX - 1, targetY + 1);
            }
            if (targetRightToSource & targetAboveSource) {
                propagateCellData(cellValue, targetX, targetY, targetX + 1, targetY - 1);
            }
        }

        // Propagate in the diagonal x=y.
        if (isStringContained(targetContent, "\\=")) {
            if (targetRightToSource & targetBelowSource) {
                propagateCellData(cellValue, targetX, targetY, targetX + 1, targetY + 1);
            }
            if (targetLeftToSource & targetAboveSource) {
                propagateCellData(cellValue, targetX, targetY, targetX - 1, targetY - 1);
            }
        }

        // If we got a dot, store the value there.
        // Do not forget to mark it with "!", so we can rescan it later.
        if (isStringContained(targetContent, ".")) {
            setCircuitCell(targetX, targetY, "!" + cellValue);
            markThatStateChanged();
        }

        // If we got a "~", store the inverted value there.
        // Do not forget to mark it with "!", so we can rescan it later.
        if (isStringContained(targetContent, "~")) {
            setCircuitCell(targetX, targetY, "!~(" + cellValue + ")");
            markThatStateChanged();
        }

        // If we found a binary logical port with one of the values set and
        // we can set the another value, do it. Use "%" and "&" to know which
        // one was already defined.
        // BTW, do not forget to mark it with "!", so we can rescan it later.
        if ((targetContent.charAt(0) == '%' & sourceY == targetY - 1)
                | (targetContent.charAt(0) == '&' & sourceY == targetY + 1))
        {
            setCircuitCell(targetX, targetY,
                    "!(" + cellValue + ")"
                    + targetContent.charAt(1)
                    + "(" + targetContent.substring(2) + ")");
            markThatStateChanged();
        }

        // Found a binary logical port without any value setted, so set it.
        // Use "%" and "&" to mark which one was setted.
        if (isStringContained(targetContent, "OoAaXx")) {
            setCircuitCell(targetX, targetY, (sourceY == targetY + 1 ? "%" : "&") + targetContent + cellValue);
            markThatStateChanged();
        }

        // If we found an output, store the value there.
        // Mark it with "$", so we will print it in the future.
        if (isStringContained(targetContent, ":")) {
            setCircuitCell(targetX, targetY, "$" + cellValue);
            markThatStateChanged();
        }
    }

    void setCircuitCell(int cellX, int cellY, String cellContents) {
        circuitState.put(cellX * maxLines + cellY, cellContents);
    }

    void markThatStateChanged() {
        finished = false;
    }

    boolean isStringContained(String searchingString, String searchTarget) {
        return searchTarget.indexOf(searchingString) > -1;
    }
}


Julia, 95 93 bytes

g(x)=reduce(vcat,map(p->map(sum,p),partitions([keys(factor(x))...])))
f(a,b)=g(a)∩g(b)!=[]

The primary function is f and it calls a helper function g.

Ungolfed:

function g(x::Integer)
    # Find the sum of each combination of prime factors of the input
    return reduce(vcat, map(p -> map(sum, p), partitions([keys(factor(x))...])))
end

function f(a::Integer, b::Integer)
    # Determine whether there's a nonzero intersection of the factor
    # sums of a and b
    return !isempty(g(a) ∩ g(b))
end

Saved 2 bytes thanks to Darth Alephalpha


Brachylog, 23 bytes

s:papcb~k~c:{#=l2}al|,0

Try it online!

Explanation

s:papcb~k~c:{#=l2}al|,0
s                         Check subsets of the input (longest first).
 :pa                      Check all permutations inside the input's elements
    p                     and all permutations /of/ the input's elements.
     c                    Flatten the result;
      b                   delete the first element;
       ~k                 find something that can be appended to the end so that
         ~c               the result can be unflattened into
           :{    }a       a list whose elements each have the property:
             #=             all the elements are equal
               l2           and the list has two elements.
                   l      If you can, return that list's length.
                    |,0   If all else fails, return 0.

So in other words, for input like [[1:2]:[1:3]:[5:3]], we try to rearrange it into a valid chain [[2:1]:[1:3]:[3:5]], then flatten/behead/unkknife to produce [1:1:3:3:5:_] (where _ represents an unknown). The combination of ~c and :{…l2}a effectively splits this into groups of 2 elements, and we ensure that all the groups are equal. As we flattened (doubling the length), removed one element from the start and added one at the end (no change), and grouped into pairs (halving the length), this will have the same length as the original chain of dominoes.

The "behead" instruction will fail if there are no dominoes in the input (actually, IIRC the :pa will also fail; a dislikes empty lists), so we need a special case for 0. (One big reason we have the asymmetry between b and ~k is so that we don't also need a special case for 1.)


Python 3.0 and Python 2, score 6

(12 bytes, 2 versions)

print(3/2*2)

Try it Online:

Python 2
Python 3

Relies on the fact that Python 3+ uses float division by default, unlike Python 2, which uses floor division.


Retina, 242

Try it online!

iG`^na( na)*$
iM`na
m`^8$
>Batman Theme,Neal Hefti$n>Na Na Hey Hey Kiss Him Goodbye,Steam
m`^10$
>Katamari Damacy,Yuu Miyake
m`^11$
>Hey Jude,The Beatles
[0-9].+
>Land Of 1000 Dances,Wilson Pickett
m`^[0-9]
>Africa,Toto
>
Song:
,
$nArtist:

How it works:

IgnoreCase flag + Grep mode flag + Regex ^na( na)*$. If the input is valid, print it as is. If not, print nothing.

iG`^na( na)*$

IgnoreCase flag + Match mode flag + Regex na. Count the "na"s and print the number.

iM`na

If the string is exactly "8", replace by the second line.

m`^8$
>Batman Theme,Neal Hefti$n>Na Na Hey Hey Kiss Him Goodbye,Steam

If the string is exactly "10", replace by the second line.

m`^10$
>Katamari Damacy,Yuu Miyake

If the string is exactly "11", replace by the second line.

m`^11$
>Hey Jude,The Beatles

If the string matches [0-9].+, replace by the second line. This is neither true for single digit numbers, 10 and 11 as they already have been repaced nor any of the above replacement strings.

[0-9].+
>Land Of 1000 Dances,Wilson Pickett

If none of the above matched, the string still starts with a number. Default to Toto, Africa.

m`^[0-9]
>Africa,Toto

Replace the placeholders > and , by Song: and Artist:.

>
Song:
,
$nArtist:


Flexible I/O

Golfscript cannot at present be used for interactive programs. I propose some functions for explicit input be added (i.e. readline, getchar and friends). The interpreter should see if the program uses these before running it.

If the program does not call any input functions, the interpreter should act like Golfscript normally does.

I wouldn't expect the interpreter to detect input functions in eval'ed code generated at runtime, but if it somehow can do that, kudos.


Compute the result of an equation, but with selectable operator precedence

JavaScript (ES6), 94 bytes

Not particularly short, but fun. Adding parentheses all over the place...

s=>([e,o]=s.split` `,[...o].map(x=>e=e.split(x).join((a+=')')+x+(b+='(')),a=b=''),eval(b+e+a))

Test cases

let f =

s=>([e,o]=s.split` `,[...o].map(x=>e=e.split(x).join((a+=')')+x+(b+='(')),a=b=''),eval(b+e+a))

console.log(f("6.3*7.8 +-*/"))              // 49.14
console.log(f("2.2*3.3+9.9/8.8-1.1 */+-"))  // 7.285
console.log(f("2.2*3.3+9.9/8.8-1.1 +*/-"))  // 2.2
console.log(f("10/2+5-1 +-/*"))             // 1.6666
console.log(f("2147480/90+10*5 +/-*"))      // 107374
console.log(f("3*55-5/8/4+1 -/+*"))         // 7.6875

Historical note

A similar method was used in early FORTRAN compilers. Here is a link from archive.org to a relevant article written by Donald E. Knuth in a 1962 book called Computers and automation.

Examples

Let's consider the expression 2.2*3.3+9.9/8.8-1.1.

With operator precedence */+-, it will expand to:

((((2.2)*(3.3)))+(((9.9))/((8.8))))-((((1.1))))

With operator precedence +*/-, it will now expand to:

((((2.2))*((3.3)+(9.9)))/(((8.8))))-((((1.1))))

Removing all redundant parentheses, we get:

((2.2*3.3)+(9.9/8.8))-1.1 = 7.285

and:

((2.2*(3.3+9.9))/8.8)-1.1 = 2.2


Death By Shock Probe: That's a lot of dice

Pyth - 9 8 bytes
Uses obvious simple method of summation of randint. Took me minute to realize 1048576 was 2^20, now I feel really stupid. Thanks to @Jakube for saving me a byte by pointing out 2^20 = 4^10.
smhO4^4T

The runtime is horrible, it has yet to finish on my computer, so there is no point running it online so here is the 2^10 one: Try it online here.
s        Summation
 m       Map
  h      Incr (accounts for 0-indexed randint)
   O4    Randint 4
  ^4T    Four raised to ten


Jelly, 26 23 bytes

Forward

Ñ¶p9¶7ÆR2ĿV€$ÆPÐf$ÐĿFị@

Try it online!

Words

Ñ ¶ p 9 ¶ 7ÆR2ĿV€$ÆPÐf$ÐĿFị@

Backward

7ÆR2ĿV€$ÆPÐf$ÐĿFị@¶9p¶Ñ

Try it online!

Words

7ÆR2ĿV€$ÆPÐf$ÐĿFị@ ¶ 9 p ¶ Ñ

How it works

All Jelly programs consist of links (Jelly's take on functions), which are separated by linefeeds or pilcrows (¶). The last of them is the main link; it is called automatically when the program is run.

The forward program works as follows.

Ñ                   Helper link. Unused.

p9                  Helper link. Take the Cartesian product with [1, ..., 9].

7ÆR2ĿV€$ÆPÐf$ÐĿFị@  Main link. Argument: n

7ÆR                 Yield all primes up to 7.
             ÐĿ
            $ÐĿ     Combine the two quicklinks to the left into a monadic chain,
                    and call it repeatedly until the results are no longer unique.
                    Return the array of all intermediate results.
       $              Combine the two links to the left into a monadic chain.
   2Ŀ               Call the helper link on line 2.
     Ṿ€                 Eval each array in the product. This casts to string
                        before evaluating, thus concatenating both numbers.
        ÆPÐf        Filter by primality; keep only primes.
               F    Flatten the resulting array.
                ị@  Retrieve the element at index n.

The backward program does almost exactly the same; there are only two differences.

The main link is now Ñ, which simply calls the link below it (wrapping around), i.e., the main link of the forward program.
9p instead of p9 return the reversed Cartesian product.


Pyth, 6 bytes

h-U21Q

Example run

$ pyth -c h-U21Q <<< '[5, 4, 1, 5, 4, 8, 2, 1, 5, 4, 0, 7, 7]'
3

How it works

  U21   range(21)
     Q  eval(input())
 -U21Q  setwisedifference(range(21), eval(input))          # Pyth function. Preserves order.
h-U21Q  setwisedifference(range(21), eval(input))[0]


JavaScript (ES6), 44 bytes

Takes input as an array of ASCII characters.

a=>a.map(c=>k+=c<1?k*59:c<'?'?10:c<{},k=0)|k

Try it online!

How?

The Babylonian Numeral System can be seen as a 4-instruction language working with a single register -- let's call it the accumulator.

Starting with \$k=0\$, each character \$c\$ in the input array \$a\$ modifies the accumulator \$k\$ as follows:

space: multiply \$k\$ by \$60\$ (implemented as: add \$59k\$ to \$k\$)
<: add \$10\$ to \$k\$
T: increment \$k\$
\: do nothing; this is the NOP instruction of this language (implemented as: add \$0\$ to \$k\$)


Kolmogorov Flexibility. A.K.A. Sale! \$38\%\$ Off All Codegolf While Stocks Last!

Python 2, 321 203 bytes

print map(lambda(i,x):(x>'0'and i-8-8-8-8)+8+8+8+8,enumerate(bin(int(reduce(lambda x,y:x+repr('abcdefijkl'.find(y)),'cfjdbljcibkeajjejiljjlcbjddlafklebajjlceljdeadficijflealkeklkljadfbbckjebclkf','')))))

Try it online!

Explanation:

from the inside out:

cfjdbljcibkeajjejiljjlcbjddlafklebajjlceljdeadficijflealkeklkljadfbbckjebclk is the number 25731972618407747697792173390589410779249734035626759409848989703511287412985 encoded with allowed characters. (No 123456's allowed)

reduce(lambda x,y:x+repr('abcdefijkl'.find(y)),'cfjdbl..bclkf','')
maps the string to its decimal string:

reduce(lambda x,y:x+y,'..','') is the same as ''.join('..') (No o's allowed)
repr('..') instead of str('..') (No s's allowed)
'abcdefijkl'.find(y) maps a char to a digit.

enumerate(bin(int(...))) converts the number string to a binary string, and enumerates. This gives the pairs [(0,0), (1,b), (2,1), (3,1), ...]

map(lambda(i,x):(x>'0'and i-8-8-8-8)+8+8+8+8, ... ) converts the enumerated list to the final result.

map(lambda(i,x):.. , .. ) instead of [... for(i,x)in ...] (No o]'s allowed)
lambda(i,x): .. converts each (index,value) pair to either the index or 32.
(x>'0'and i-8-8-8-8)+8+8+8+8 is the same as:

x>'0'and i or 8+8+8+8, (No o's allowed)
[8+8+8+8,i][x>'0'] or [8<<9-7,i][x>'0'], (No ]'s allowed)

8+8+8+8 = 32 (No 23's allowed)

This means that the program is essentially the same as:

print[[32,i][x>'0']for i,x in enumerate(bin(25731972618407747697792173390589410779249734035626759409848989703511287412985))]


My "keybore" is key-boring me! Help me find a minimal keystrokes

MATL, 43 29 bytes
E:"@TFEqZ^!"@Y'tQ**s]vGE=a?@.

This is memory- and time-inefficient. The online compiler can handle up to input 45 only.
Try it online!
Here's a modified version with all test cases up to 40 (it takes almost a minute in the online compiler).
Explanation
This tests all possible key-press sequences of each length, in order of increasing length, until a valid sequence is found.
E:       % Range [1 2 ... 2*N] where N is implicit input. The required sequence length is
         % less than 2*N, so this is enough
"        % For each
  @      %   Push current value: length of sequence
  TFEq   %   Push array [1 -1]
  Z^     %   Cartesian power. Gives all possible sequences of 1, -1 of that length
  !      %   Transpose. Each sequence is now a row
  "      %   For each sequence
    @    %     Push current sequence
    Y'   %     Run-length decoding: Pushes an array of values 1 and -1, and then an
         %     array of run-lengths
    tQ*  %     Duplicate, add 1, multiply. Gives twice the triangular number for each run
    *    %     Multiply element-wise by 1 or -1 to produce correct sign
    s    %     Sum of array. This is the number produced by the current sequence
  ]      %   End for
  v      %   Concatenate all numbers into an array
  GE=a   %   True if any of those numbers equals twice the input
  ?      %   If so
    @    %     Push current sequence length. This is the final result
    .    %     Break loop
         %   End if
         % End for
         % Implicit display


Create an N-Dimensional Simplex (Tetrahedron)

Python 78 66 Bytes
lambda n:[i*[0]+[n]+(n+~i)*[0]for i in range(n)]+[n*[1+(n+1)**.5]]

Surely can be improved, especially at handling n=1```. (How is that even a simplex?) Just realized that's not necessary. Can probably be improved still ^^
Try it online!
[i*[0]+[1]+(n+~i)*[0]for i in range(n)] creates identity matrix. All points have distance sqrt(2) from each other. (thanks to Rod for improving)
Now we need a n+1-th point with the same distance to all other points. We have to choose (x, x, ... x).
Distance from (1, 0, ...  ) to (x, x, ... x) is sqrt((x-1)²+x²+...+x²). If we want an n dimensional simplex this turns out to be sqrt((x-1)²+(n-1)x²), as we have one 1 and n-1 0s in the first point. Simplify a bit: sqrt(x²-2x+1+(n-1)x²) = sqrt(nx²-2x+1)
We want this distance to be sqrt(2).
sqrt(2) = sqrt(nx²-2x+1)
2 = nx²-2x+1
0 = nx²-2x-1
0 = x²-2/n*x+1/n
Solving this quadratic equation (one solution, other one works fine, too):
x = 1/n+sqrt(1/n²+1/n) = 1/n+sqrt((n+1)/n²) = 1/n+sqrt(n+1)/n = (1+sqrt(n+1))/n
Put that in a list n times, put that list in a list and join with identity matrix.

-4 Bytes thanks to Alex Varga:
Multiply each vector by n. This changes the creation of the identity matrix to lambda n:[i*[0]+[n]+(n+~i)*[0] (same length) and gets rid of the division by n in the additional point, so it becomes n*[1+(n+1)**.5], saving two brackets and the /n.


CJam, 9 8 bytes

ea9fbAf%

Reads the digit pairs as command-line arguments. To try the code online, change ea to lS/ to read from simulated STDIN.

Example run

$ cjam <(echo ea9fbAf%) 57 23 99 45; echo
2101
$ cjam <(echo ea9fbAf%) 25 78 63 15; echo
3174

How it works

The character code of the digit d is 48 + d. Thus, considering the two-digit string xy a base 9 number yields 9 * (48 + x) + (48 + y) = 10 * (48 + x) + y - x ≡ y - x (mod 10).

ea       " Push the array of command-line arguments.                                      ";
  9fb    " Mapped base 9 conversion; replace each string 'xy' with (9 * ord(x) + ord(y)). ";
     Af% " Take the results modulo 10.                                                    ";


Given an input, move it along the keyboard by N characters

C, 217 bytes

char*t=" @A$%^*a)_(~.=/z-234567890\"'>`?Z#SNVFRGHJOKL:<MP{WTDYIBECUX]q\\&=1snvfrghjokl;,mp[wtdyibecux}Q|!";l,d,k;f(char*s){for(l=strlen(s);s[--l]-32;);d=atoi(s+l);for(s[l]=0;d--;)for(k=l;k--;s[k]=t[s[k]-32]);puts(s);}

Readable version with whitespace, includes, etc:

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

char* t = " @A$%^*a)_(~.=/z-234567890\"'>`?Z#SNVFRGHJOKL:<MP{WTDYIBECUX]q\\&=1snvfrghjokl;,mp[wtdyibecux}Q|!";
int l, d, k;

void f(char* s) {
    l = strlen(s);
    for( ; s[--l] - 32; );
    d = atoi(s + l);
    s[l] = 0;
    for ( ; d--; ) {
        for (k = l; k--; s[k] = t[s[k] - 32]);
    }
    puts(s);
}

The code pretty much speaks for itself. Just a lookup table that maps from each character to the next character, which is applied the given number of times. Much of the code is actually for parsing the number out of the input.


Husk, 21 20 19 bytes
-2 bytes thanks to Zgarb
Idea taken from A055228
ṠṀöṁ(⌈√Π-3▼8L)fε`#Σ

Try it online!
Explanation (Of older version)
            ṠṀ-oṠ-uΣ   Remove duplicated words
                   Σ   Concatenate
                  u    Remove duplicates
               oṠ-     Remove those unique elements from the list (give list of elements that appear more than once)
            ṠṀ-        Remove those words from each list in the input
m                      For each list
 ṁ(                    Map then sum
          L)           Length
        ▼8             Min(8,x)
      -3               Minus 3
     Π                 Factorial
    √                  Square root
   ⌈                   Ceiling


Generate regular expressions for matching natural numbers between `m` and `n`

Perl, score 455

191 chars, 132 regex length

sub b{my$a=shift;$_=(@_>0&&$a.b(@_).($a-->0&&'|')).($a>=0&&($a>1
?"[0-$a]":$a));/\|/?"($_)":$_}sub a{b(@a=split//,<>-1+$x++).(@a>
1&&"|.{1,$#a}")}print'(?!0|('.a.')$)(?=('.a.'$))^\d{1,'.@a.'}$'

Input: 123456, 7654321

(?!0|((1(2(3(4(5[0-5]|[0-4])|[0-3])|[0-2])|1)|0)|.{1,5})$)(?=((7(6(5(4(3(21|1)|[0-2])|[0-3])|[0-4])|[0-5])|[0-6])|.{1,6}$))^\d{1,7}$

Update: I was able to further simplify this when I realized that most of the patterns ended with things like \d{3}.  These were doing nothing more than enforcing a string length--and doing so very repetitively, since they occurred on every term.  I eliminated this by using another lookahead to enforce the "less than" condition, only checking that either: 1) the first part of the number does not exceed the input or 2) the number is fewer digits than the input.  Then the main regex just verifies that it is not too many digits.

I also incorporated Peter Taylor's idea of negative look-ahead for checking the "greater than" condition.

The key to simplifying this problem (at least for me) was to break the regex in two: a look-ahead makes sure the number is not less than the minimum, then the main part of the regex checks that it is not greater than the maximum.  It is a little bit silly for small input, but it is not so bad for large input.

Note: the 0| at the beginning is to exclude anything that starts with a zero from matching.  This is required because of the recursive nature of the regex function: inner parts of the match can start with zero, but the entire number cannot.  The regex function can't tell the difference, so I excluded any number starting with zero as a special case.

Input: 1, 4

(?!0|(0)$)(?=([0-4]$))^\d{1,1}$

Unreasonably Long Regex Version, 29 chars:

print'^',join('|',<>..<>),'$'


Haskell, 8 bytes

scanl(*)

Try it online!


Retina 0.8.2, 60 59 bytes
i`^(0[0-7]*|0x[\da-f]+|[1-9]\d*)(u)?(l)?(?-i:\3?)(?(2)|u?)$

Try it online! Link includes test cases. Edit: Saved 1 byte thanks to @FryAmTheEggMan. Explanation:
i`

Match case-insensitively.
^(0[0-7]*|0x[\da-f]+|[1-9]\d*)

Start with either octal, hex or decimal.
(u)?

Optional unsigned specifier.
(l)?

Optional length specifier.
(?-i:\3?)

Optionally repeat the length specifier case sensitively.
(?(2)|u?)$

If no unsigned specifier yet, then another chance for an optional specifier, before the end of the literal.


Show the Top Five Comment Scores on a SE Post

Jelly, 6 bytes

NỤḣ5Ṣị

Try it online! or verify all test cases at once.

How it works

NỤḣ5Ṣị    Main link. Input: A (list)

N         Negate (multiply by -1) all elements of A.
 Ụ        Grade the result up.
          This consists in sorting the indices of A by their negated values.
          The first n indices will correspond to the n highest vote counts,
          tie-broken by order of appearance.
  ḣ5      Discard all but the first five items.
    Ṣ     Sort those indices.
          This is to preserve the comments' natural order.
     ị    Retrieve the elements of A at those indices.


APL, 5

⌽⍞⍝⍞⊖

This reverses (⌽, along the last axis) the input (⍞), and is followed by a comment (⍝ marks a line comment). Reversed, the program reverses (⊖, along the first axis) the input, and is followed by a comment. Because the input is always going to be one dimensional, in this case ⌽ and ⊖ are functionally equivalent. It is perhaps even sneakier than the GolfScript solution, so here's a cleaner solution (no comments), which scores 9.

⍬,⌽,⍞,⊖,⍬

This first grabs an empty vector (⍬), flattens it (monadic ,), and reverses it (⊖, along the first axis). This still leaves an empty vector. Then it concatenates (dyadic ,) to the input (⍞), leaving the input untouched. It then flattens (monadic ,) the already-flat input and reverses it (⌽, along the last axis). Then it concatenates (dyadic ,) another empty vector (⍬) to the reversed input. This does nothing, and leaves the reversed input behind. Reversed, this program does the same thing, based again on the fact that ⌽ and ⊖ are functionally equivalent with one-dimesional arguments.

You really couldn't say I'm adding useless characters to break the palindrome (the two different reverse functions are different with two-or-more-dimensional input; I'm just taking advantage of the fact they act the same with one-dimensional input)


Python 2, 226 bytes

g=input()+2
f=lambda n,x=1,y=1:n and f(n-1,y,x+y)or x
k={1:1,2:2,3:3}
s=set(k)
x=4
y=6
while g/x:
	while g/x|g/y:k[y]=f(x);k[x]=y;s|={x};x,y=y,f(x)
	x,y=sorted(set(range(1,max(s)+3))-s)[:2];s|={y}
print map(k.get,range(1,g-1))

Try it online!
-33 bytes thanks to ovs


Find the smallest positive integer which ends in n, is divisible by n and whose digits sum to n

Befunge, 81 bytes
&>00p0v<!%g0<
v%"d":_>1+:0^
>00g->#^_:0v
0g10g-#^_.@1>
>0p:55+/\:v>
^1+g01%+55_$^

Try it online!
Can handle up to n = 70 at least, after which some values will start overflowing the stack cell size on most implementations, and on those that don't, it'll take so long that it's not worth waiting to find out.
Given those constraints, we don't even bother trying to handle values of n greater than 99, which means we can more easily test if the value ends in n with by simply comparing the value modulo 100 with n.
Below is more detailed breakdown of the code.

 Read n from stdin and save in memory.
 Initialize the test value v to 0 and start the main loop, incrementing v up front.
 Test if v%n == 0, and if not return to the start of the main loop.
 Test if v%100 == n, and if not return to the start of the main loop.
 Sum the digits in v by repeatedly adding v modulo 10 and dividing v by 10.
 Test if the sum is equal to n, and if not return to the start of the main loop.
 Otherwise output v and exit.


Jelly, 5 4 bytes, George V. Williams
RÆḊḞ

Try it here.
A hidden feature!
If I remembered correctly, ÆḊ(A) = sqrt(det(AAT)) is n! times the n dimensional Lebesgue measure of a simplex formed by n input point and the origin in m dimensional space. When n=1 it degenerate to the Euclidean distance. Not that weird after all...


Define infix operators instead of binary functions

This saves usually one or two spaces per definition or call.

0!(y:_)=y
x!(y:z)=(x-1)!z

vs.

f 0(y:_)=y
f x(y:z)=f(x-1)z

The available symbols for 1-byte operators are !, #, %, &, and ?. All other ASCII punctuation is either already defined as an operator by the Prelude (such as $) or has a special meaning in Haskell's syntax (such as @).

If you need more than five operators, you could use combinations of the above, such as !#, or certain Unicode punctuation characters, such as these (all 2 bytes in UTF-8):

¡ ¢ £ ¤ ¥ ¦ § ¨ © ¬ ® ¯ ° ± ´ ¶ · ¸ ¿ × ÷


Mathematica, 935 bytes

Inp={5,4};L=Length;T=Table;ST[t_,k_,n_]:=Binomial[n-1,t-1]/Binomial[k-1,t-1];H=ToExpression@Alphabet[];Lo=Inp[[1]]*Inp[[2]];H=H[[;;Lo]];Final={};ST[2,3,12]=4;ST[2,4,20]=5;If[Inp[[2]]==1,Column[Partition[H,{1}]],CA=Lo*Floor@ST[2,Inp[[2]],Lo];While[L@Flatten@Final!=CA,Final={};uu=0;S=Normal[Association[T[ToRules[H[[Z]]==Prime[Z]],{Z,L@H}]]];PA=Union[Sort/@Permutations[H,{Inp[[2]]}]];PT=Partition[H,Inp[[2]]];While[L@PA!=0,AppendTo[Final,PT];Test=Flatten@T[Times@@@Subsets[PT[[X]],{2}]/.S,{X, L@PT}];POK=T[Times@@@Subsets[PA[[Y]],{2}]/.S,{Y,L@PA}];Fin=Select[POK,L@Intersection[Test,#]==0&];Facfin=T[FactorInteger[Fin[[V]]],{V,L@Fin}];end=T[Union@Flatten@T[First/@#[[W]],{W,L@#}]&[Facfin[[F]]],{F,L@Facfin}]/.Map[Reverse,S];PA=end;PT=DeleteDuplicates[RandomSample@end,Intersection@##=!={}&];If[L@Flatten@PT<L@H,While[uu<1000,PT=DeleteDuplicates[RandomSample@end,Intersection@##=!={}&];If[L@Flatten@PT==L@H,Break[],uu++]]]]];Grid@Final]

this is for 26 ladies max

EDIT
I made some changes and I think it works!
The code right now is set to solve [5,4] (which is the "social golfers problem") and gets the result in a few seconds.
However [5,3] problem is tougher and you will have to wait 10-20 minutes but you will get a right combination for all days.
For easier cases it is very quick.

anyway you can try it and see the results
Try it online here
copy and paste using ctrl-v
press shift+enter to run the code
you can change the input at the begining of the code -> Inp={5,4}
run the code multiple times to get different permutations