text:
Remove duplicate words from a sentence
In this challenge, you will remove duplicate words from each sentence.
Examples
Hello Hello, World!
Hello, World!

Code Code! Golf Code
Code! Golf Code

Hello  hello   World
Hello   World

Programming Golf Programming!
Programming Golf!

Specification

Input will be a string of ASCII characters.
A sentence is defined as anything until the end of the string, a linefeed (\n), or punctuation (.!?).
A word is defined as a sequence of A-Za-z.
Words are case insensitive (Hello == heLlO).

Only the first occurrence of a word in a sentence is kept.
If a word is removed, the spaces before the removed word should be removed. (e.g. A   A B -> A B).

As always standard loopholes are disallowed.

This is code-golf so shortest code in bytes wins!

a b a. goes to what?

@ThomasKwa a b. because the  a is removed.

For a__b_b_a, do you get a_b_a (first b removed) or a__b_a (second b removed)?

@CamilStaps you would get a__b__ because the repeated b is removed and the repeated a is removed

So you always leave the first occurrence and remove the later ones?

@CamilStaps Yes, the first occurrence is the one that is kept

Hang on, you edited that. Why a__b__ and not a__b if the spaces before the last a and b are removed?

@CamilStaps If _s are supposed to represent whitespace then it would be a__b. Only whitespace before the removed word are removed

Ah, okay, yes, that's what I meant. Inline markdown code removes double spaces. Thanks for the clarification.

Is this an acceptable input format? Each sentence is a separate input, and end of input is marked with a blank line

@LuisMendo no. The whole input will be in one string.

There are languages in which \n marks the end of the (or one) input :-(

Are any other ASCII characters allowed? (other than letters)

@BradGilbertb2gills All ASCII characters are allowed in the input. Only letters are considered words though

So _ is a non-word ( which means I have to do some fixing )

Should we only remove spaces in front of a removed word, or other whitespace as well? (Like tabs, vertical tabs, form feeds...)

@MartinBüttner I've specified "whitespace" but I guess it doesn't matter. You can remove other whitespace as long as you remove spaces.

@Doᴡɴɢᴏᴀᴛ you actually specified "spaces" which is why I asked to make sure that's intentional. ;)

Vim, 27 bytes
:s/\v\c(<\a+>).{-}\zs\s+\1

Note that the 27 bytes is including a trailing carriage return at the end.
Try it online! Side note: This is a link to a different language I'm writing called "V". V is mostly backwards compatible with vim, so for all intents and purposes, it can count as a vim interpreter. I also added one byte % so that you can verify all test cases at once.
Explanation:
:s/\v                       "Substitute with the 'Magic flag' on. This magic flag allows us
                            "to shorten the regex by removing a lot of \ characters.
     \c(<\a+>)              "A case-insensitive word
              .{-}          "Any character (non-greedy)
                  \zs       "Start the selection. This means everything after this atom
                            "will be removed
                     \s+    "One or more whitespace characters,
                        \1  "Followed by the first word

JavaScript (ES6), 98
Note while I found it myself, it's annoyingly similar to @Neil's, just with the additional logic to split the whole input string in sentences.
s=>s.replace(/[^\n.!?]+/g,s=>s.replace(/ *([a-z]+)/ig,(r,w)=>k[w=w.toUpperCase()]?'':k[w]=r,k=[]))

Test

f=s=>s.replace(/[^\n.!?]+/g,s=>s.replace(/ *([a-z]+)/ig,(r,w)=>k[w=w.toUpperCase()]?'':k[w]=r,k=[]))

console.log=x=>O.textContent+=x+'\n'

;[['Hello Hello, World!','Hello, World!']
,['Code Code! Golf Code','Code! Golf Code']
,['Hello  hello   World','Hello   World']
,['Programming Golf Programming!','Programming Golf!']]
.forEach(t=>{
  var i=t[0],k=t[1],r=f(i)
  console.log((r==k?'OK ':'KO ')+i+' -> '+r)
})

Retina, 66 46 bytes
Byte count assumes ISO 8859-1 encoding.
i`[a-z]+
·$0·
i` *(·[a-z]+·)(?<=\1[^.!?¶]+)|·

Try it online!
Explanation
Since only letters should be considered word characters (but regex treats digits and underscores as word characters, too), we need to make our own word boundaries. Since the input is guaranteed to contain only ASCII characters, I'm inserting · (outside of ASCII, but inside ISO 8859-1) around all words and remove them again with the duplicates. That saves 20 bytes over using lookarounds to implement generic word boundaries.
i`[a-z]+
·$0·

This matches every word and surrounds it in ·.
i` *(·[a-z]+·)(?<=\1[^.!?¶]+)|·

This is two steps compressed into one. <sp>*(·[a-z]+·)(?<=\1[^.!?¶]+) matches a full word (ensured by including the · in the match), along with any spaces preceding it, provided that (as ensured by the lookbehind) we can find the same word somewhere earlier in the sentence. (The ¶ matches a linefeed.)
The other part is simply the ·, which matches all artificial word boundaries that weren't matched as part of the first half. In either case, the match is simply removed from the string.

C, 326 bytes
Who needs regular expressions?
#include <ctype.h>
#define a isalpha
#define c(x)*x&&!strchr(".?!\n",*x)
#define f(x)for(n=e;*x&&!a(*x);++x);
main(p,v,n,e,o,t)char**v,*p,*n,*e,*o,*t;{for(p=v[1];*p;p=e){f(p)for(e=p;c(e);){for(;a(*++e););f(n)if(c(n)){for(o=p,t=n;a(*o)&&(*o-65)%32==(*t-65)%32;o++,t++);if(a(*t))e=n;else memmove(e,t,strlen(t)+1);}}}puts(v[1]);}

Perl 6, 104 bytes
{[~] .split(/<[.!?\n]>+/,:v).map(->$_,$s?{.comb(/.*?<:L>+/).unique(as=>{/<:L>+/;lc $/}).join~($s//'')})} # 104

Usage:
# give it a lexical name
my &code = {...}

say code "Hello Hello, World!
Code Code! Golf Code
Hello  hello   World
Programming Golf Programming!";

Hello, World!
Code! Golf Code
Hello   World
Programming Golf!

Explanation
{
  [~]                         # join everything that follows:

  .split(/<[.!?\n]>+/,:v)     # split on boundaries, keeping them
  .map(                       # loop over sentence and boundary together
    -> $_, $s? {              # boundary is optional (at the end of the string)
      .comb(/.*?<:L>+/)       # grab the words along with leading non letters
      .unique(                # keep the unique ones by looking at …
        as => {/<:L>+/;lc $/} # only the word chars in lowercase
      )
      .join                   # join the sentence parts
      ~                       # join that with …
      ($s//'')                # the boundary characters or empty string
    }
  )
}

Perl 5 with -p option, 27 + 1 = 28 bytes
s/\A(\w+)[^.!?]*\K\s+\1//gi

Try it online!

Perl 5, 57 bytes
56 bytes code + 1 for -p
s/[^.!?
]+/my%h;$&=~s~\s*([A-z]+)~!$h{lc$1}++&&$&~egr/eg

Usage:
perl -pe 's/[^.!?
]+/my%h;$&=~s~\s*([A-z]+)~!$h{lc$1}++&&$&~egr/eg' <<< 'Hello Hello, World!
Code Code! Golf Code
Hello  hello   World
Programming Golf Programming!
'
Hello, World!
Code! Golf Code
Hello   World
Programming Golf!

Might need to be +1, currently I'm assuming that there will only be spaces in the input, no tabs.

From a comment "All ASCII characters are allowed in the input. Only letters are considered words though" (I'll edit this into the challenge, I think)

@MartinBüttner Damn, ok I'll update to use \s instead... Still nowhere near your retina answer though!

Oh I see why you asked now. If we need to remove whitespace in front of words, then I need another byte as well. The question specifically says "spaces" though. I've asked for clarification.

@MartinBüttner I guess my comment wasn't really clear either! Thanks for your comments though!

JavaScript (Node.js), 50 bytes
x=>x.replace(/(?<=\b(\w+)\b[^.!?\n]*) +\1\b/ig,'')

Try it online!

Stax, 39 bytes
ô┘ⁿ=3⌠↕ê║▌ßa⌡ô½â╖¬╥▓lå3Öîz╝╥'n┐←ûl₧'○0T

Run and debug it
I'm not sure if Stax's JS regex has the features to match up with Vim regex, but nested regex works!
Explanation
'!+".+?[\n!?]"{cV^{c:~\{:}m$"\s*"s+{i!*}Rc}Rd}RNd
'!+                                               append an ! to the string
   ".+?[\n!?]"                                    match anything(non-greedy),
                                                  followed by a sentence terminator
              {                              }R   replace each sentence with:
               c                                  copy it
                V^                                /[a-zA-Z]+/
                  {                       }R      for each regex word match:
                   c                              copy the word
                    :~                            toggle case
                      \                           zip the two
                       {:}m                       embed each pair in square brackets
                           $                      flatten
                            "\s*"s+               prepend \s*
                                                  Example for "wOrd":
                                                  "\s*[wW][Oo][rR][dD]"
                                   {   }R         replace each occurrence of word with:
                                    i!            index negated (1 if first)
                                      *           multiply with word
                                         c        copy
                                             d    delete the faulty replaced string
                                               Nd remove last !

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

sort: votes


text:
Draw and label an ASCII hexagonal grid
In my previous challenge, I
drew the first diagram mostly by hand (with the help of vim's visual block
mode). But surely there must be a better way...

Given an input of two dimensions, a width and a height, output a hexagonal grid
with those dimensions in ASCII art.
Here's the diagram referenced in the intro (with minor edits), which should be
your output for the input width=7, height=3:
         _____         _____         _____
        /     \       /     \       /     \
  _____/ -2,-1 \_____/  0,-1 \_____/  2,-1 \_____
 /     \       /     \       /     \       /     \
/ -3,-1 \_____/ -1,-1 \_____/  1,-1 \_____/  3,-1 \
\       /     \       /     \       /     \       /
 \_____/ -2,0  \_____/  0,0  \_____/  2,0  \_____/
 /     \       /     \       /     \       /     \
/ -3,0  \_____/ -1,0  \_____/  1,0  \_____/  3,0  \
\       /     \       /     \       /     \       /
 \_____/ -2,1  \_____/  0,1  \_____/  2,1  \_____/
 /     \       /     \       /     \       /     \
/ -3,1  \_____/ -1,1  \_____/  1,1  \_____/  3,1  \
\       /     \       /     \       /     \       /
 \_____/       \_____/       \_____/       \_____/

Notice several things:

The width and height are essentially equivalent to how many hexagons there
are for a given y and x coordinate respectively. These will always be odd
numbers.
Each hexagon is represented by the ASCII art
  _____
 /     \
/       \
\       /
 \_____/

but borders are "shared" between neighboring hexagons.
The comma in the coordinates is always exactly two characters below the
center of the top edge. The x-coordinate is then positioned directly before
the comma, and the y-coordinate directly after.
You may assue that the coordinates will never be too large such that they
would overlap the hexagon's borders.

Input may be taken as a whitespace-/comma-separated string, an array of
integers, or two function/commandline arguments. Output must be a single string
(to STDOUT, as a return value, etc.).
Since this is code-golf, the shortest code in bytes will win.
The grid above can be used as a test case. The maximum-sized
width=199, height=199 grid is obviously impractical to include here, but the
first few rows and columns should look like the following:
         _____         ___
        /     \       /
  _____/-98,-99\_____/-96,
 /     \       /     \
/-99,-99\_____/-97,-99\___
\       /     \       /
 \_____/-98,-98\_____/-96,
 /     \       /     \
/-99,-98\_____/-97,-98\___
\       /     \       /
 \_____/-98,-97\_____/-96,
 /     \       /     \
/-99,-97\_____/-97,-97\___
\       /     \       /

Related

Ruby, 221 bytes
->w,h{s=' '
a=(s*9+?_*5)*(w/2)+$/
(2-h*2).upto(h*2+3){|y|c=y<4-h*2
a+=[b=c ?s:?\\,s+b,s,''][y%4]
(0-w/2).upto(w/2){|x|a+=["/#{h<y/2?s*7:"%3d,%-3d"}\\",s*7,?_*5,"/     \\"][(y+x*2+w)%4]%[x,y/4]}
a+='//  '[c ?3:y%4]+$/}
a}

Ungolfed in test program
f=->w,h{
  s=' '                                #set s to space for golfing reasons
  a=(s*9+?_*5)*(w/2)+$/                #start building the output with a row of just _ and space

  (2-h*2).upto(h*2+3){|y|              #iterate 4 times for each row of hexagons, plus an extra 2 at the end to finish last row
    c=y<4-h*2                          #condition for first two rows
    a+=[b=c ?s:?\\,s+b,s,''][y%4]      #string to be output before main set of hexagons (spaces for top row, \ for certain other rows

    (0-w/2).upto(w/2){|x|              #iterate through hexagons on each row, 4 lines for each with the following printf type string
      a+=["/#{h<y/2?s*7:"%3d,%-3d"}\\",#line 1:contains ends / \ and numbers
         s*7,                          #line 2 padding spaces
         ?_*5,                         #line 3 padding ___
         "/     \\"][(y+x*2+w)%4]%     #line 0 top of hexagon / \; formula to select string to be printed
           [x,y/4]                     #numbers to be printed (if format for current line does not require them they are ignored)
    }

    a+='//  '[c ?3:y%4]+$/             #ending alternates between / and space; / are suppressed for first two rows
  }
  a
}

puts g[7,3]
puts g[5,5]

Output
As I was finishing debugging, I noticed an ambiguity in the spec. Where w+1 is divisible by 4, the first and last x coordinates are odd, and there is no ambiguity. But where w-1 is divisible by 4 the first and last x coordinates are even. I assumed that the first and last columns should be offset below the next ones. But then I read the previous question and noted in that case it was the odd columns that should be offset below the even ones (note for w-1 divisible by 4 it is not possible to do both.)
That distinction was not made in this question, however. I will leave this up to OP's judgement and rework if necessary, though I'd prefer not to have to.
         _____         _____         _____
        /     \       /     \       /     \
  _____/ -2,-1 \_____/  0,-1 \_____/  2,-1 \_____
 /     \       /     \       /     \       /     \
/ -3,-1 \_____/ -1,-1 \_____/  1,-1 \_____/  3,-1 \
\       /     \       /     \       /     \       /
 \_____/ -2,0  \_____/  0,0  \_____/  2,0  \_____/
 /     \       /     \       /     \       /     \
/ -3,0  \_____/ -1,0  \_____/  1,0  \_____/  3,0  \
\       /     \       /     \       /     \       /
 \_____/ -2,1  \_____/  0,1  \_____/  2,1  \_____/
 /     \       /     \       /     \       /     \
/ -3,1  \_____/ -1,1  \_____/  1,1  \_____/  3,1  \
\       /     \       /     \       /     \       /
 \_____/       \_____/       \_____/       \_____/
         _____         _____
        /     \       /     \
  _____/ -1,-2 \_____/  1,-2 \_____
 /     \       /     \       /     \
/ -2,-2 \_____/  0,-2 \_____/  2,-2 \
\       /     \       /     \       /
 \_____/ -1,-1 \_____/  1,-1 \_____/
 /     \       /     \       /     \
/ -2,-1 \_____/  0,-1 \_____/  2,-1 \
\       /     \       /     \       /
 \_____/ -1,0  \_____/  1,0  \_____/
 /     \       /     \       /     \
/ -2,0  \_____/  0,0  \_____/  2,0  \
\       /     \       /     \       /
 \_____/ -1,1  \_____/  1,1  \_____/
 /     \       /     \       /     \
/ -2,1  \_____/  0,1  \_____/  2,1  \
\       /     \       /     \       /
 \_____/ -1,2  \_____/  1,2  \_____/
 /     \       /     \       /     \
/ -2,2  \_____/  0,2  \_____/  2,2  \
\       /     \       /     \       /
 \_____/       \_____/       \_____/

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
Strategies for representing a given large integer using arithmetic expression
I have a specific number in mind, but it's part of a challenge I'm doing, and I don't want people to do (all) the work for me.
Here is a number which has the same digits, but shuffled:
5713167915926167134578399473447223554460066674314639815391281352328315313091488448321843
8892917486601064146636679920143691047671721184150386045081532202458651561779976236919751
5521854951599379666116678853267398393892536121049731949764192014193648608210652358947001
6332620900065461061195026191178967128001712341637591690941978871368243245270800684616029
6679555942849366434586090627998161441134473428845367022486230724219981658438108844675033
4461550796750244527407413996606134735852639191026103378962082622204359677030054592798927
4145951979523473408718011778751084514127053772614511042703365596651912104541233491744530
87457854312602843967491787086250478422477028164189

The number has 666 digits (decimal). Because I'm using Python, integers (or technically longs) are automatically bignums.
I have 255 chars to use, and I need to describe the same number. The description is meant to be run through eval() to produce the original number.
What strategies should I be looking into?

base64 (or higher) encoding

Are you sure that the actual number from your challenge doesn't have some property that makes it easier to compress that may be lost due to the reshuffling? I don't think Luis's suggestions is gonna cut it. Even in base 256, this still has 277 digits. Of course you said you've got "255 characters", so I guess in principle you could use a much bigger base like 2^16, and go into Unicode.

This is asking for the shortest code to produce a number, which is absolutely asking for golfing advice. My concern is the source is uncredited -- the challenge should be linked if possible so we have attribution and can check it's OK to give outside help.

I have 255 chars to use, and I need to describe the same number. The description is meant to be run through eval() to produce the original number: is it acceptable for you to read the number from an external resource, such as a web page?

@LuisMendo No, it has to be self contained. Additionally, it can only use chars that are legal in a filename.

I'm with @MartinBüttner on suspecting the original number has some property that makes it easier to represent than an arbitrary integer.

Can you clarify "arithmetic expression"? Your elaboration mentions using eval(). Without further limitation, eval() allows loops and other constructs. If you truly mean to restrict this to only arithmetic, can we get a list of legal operations?

the viability of certain approaches changes in different languages. python wants infix expressions, which means it needs parentheses. the same expressions in prefix or postfix can do without parentheses which makes a big difference to some approaches. you've tagged the question as python, but it would still be a good question without that restriction.

Base Encoding
A standard technique for compressing numbers is to express them in a big base and encode the digits as characters. E.g. if you encode the number in base 256, it would have only 277 digits:
[12 24 156 48 101 149 235 32 96 92 20 203 202 164 144 71 193 127 112 77 141 79 210 183 98 155 16 151 65 198 26 236 83 221 220 129 169 254 43 124 245 25 176 182 167 124 95 191 77 25 233 139 190 7 135 2 149 90 163 163 106 193 220 253 109 129 57 219 91 157 218 18 223 11 171 113 209 173 207 123 110 220 79 139 176 143 171 7 30 35 231 151 172 83 120 114 119 47 217 227 50 105 236 91 161 226 112 16 170 57 162 147 36 89 26 9 122 164 15 15 243 108 30 14 233 139 103 137 82 169 2 57 54 71 154 136 23 203 137 10 219 153 24 168 42 218 165 125 185 183 241 91 193 85 195 71 186 18 98 34 196 78 6 193 252 8 177 94 5 24 137 183 127 129 9 77 149 73 148 193 62 220 146 33 130 21 209 153 229 105 100 188 87 235 203 104 207 161 20 17 102 150 252 120 242 222 233 248 114 217 142 31 196 42 161 173 0 244 9 213 178 152 122 170 136 230 135 132 245 69 9 196 231 147 8 175 48 98 101 23 162 144 190 200 62 226 61 27 200 15 232 12 105 187 184 4 121 252 171 240 230 94 161 151 131 209 205 130 193 9 4 155 92 48 59 130 93]

Or expressed as a string
"0eë `\ËÊ¤GÁpMOÒ·bAÆìSÝÜ©þ+|õ°¶§|_¿Mé¾Z££jÁÜým9Û[Úß«qÑÏ{nÜO°«#ç¬Sxrw/Ùã2iì[¡âpª9¢$Y  z¤ólégR©96GË
Û¨*Ú¥}¹·ñ[ÁUÃGºb\"ÄNÁü±^· MIÁ>Ü!Ñåid¼WëËhÏ¡füxòÞéørÙÄ*¡ô  Õ²zªæõE Äç¯0be¢¾È>â=Èèi»¸yü«ðæ^¡ÑÍÁ  \0;]"

(Plus some unprintable characters which are stripped by SE.)
Of course, that's still too long for your 255 character allowance. If you're actually talking about characters though (as opposed to bytes), you can go into Unicode and use a much bigger base. How about 216? That's only 139 digits:
[12 6300 12389 38379 8288 23572 52170 42128 18369 32624 19853 20434 46946 39696 38721 50714 60499 56796 33193 65067 31989 6576 46759 31839 48973 6633 35774 1927 661 23203 41834 49628 64877 33081 56155 40410 4831 2987 29137 44495 31598 56399 35760 36779 1822 9191 38828 21368 29303 12249 58162 27116 23457 57968 4266 14754 37668 22810 2426 41999 4083 27678 3817 35687 35154 43266 14646 18330 34839 52105 2779 39192 43050 55973 32185 47089 23489 21955 18362 4706 8900 19974 49660 2225 24069 6281 46975 33033 19861 18836 49470 56466 8578 5585 39397 26980 48215 60363 26831 41236 4454 38652 30962 57065 63602 55694 8132 10913 44288 62473 54706 39034 43656 59015 34037 17673 50407 37640 44848 25189 6050 37054 51262 57917 7112 4072 3177 48056 1145 64683 61670 24225 38787 53709 33473 2308 39772 12347 33373]

(I can't include the actual string here, because it contains some CJK characters that are banned by SE.)
Now that seems more doable. You just need to be able to decode it in 116 characters. If you can't, Unicode has a lot more than 216 characters, so you could try using an even larger base.

"CJK characters that are banned by SE" - wtf?

@immibis http://meta.stackexchange.com/a/263725/201409

Base 2²⁰ describes the number in only 145 characters.

Prime Factorization
If the number has no interesting features, base encoding is the best way to do it. The next thing to do is look for interesting features of the number. The first one that comes to mind is that it may have factors of small primes (2,3,5,7, etc) raised to quite large powers. IF you have nothing else to go on, keep trying to divide by small primes and see what happens. If its factors include 2**4, 3**4, and 7**4, you can write big number *42**4 which is a few bytes shorter than big number * 3111696

I'd also try factoring the number plus or minus small integers to see if one of them has a nicer factorization.  Also, if your language has a short way to get the nth prime, you can save a digit or so per prime by storing its index instead of the prime itself.

Recursive removal of largest square
This approach removes the largest square number from N, repeatedly, until there's no value in continuing.
while(n>999*999):
    s = sqrt(n,2)
    print s,"** 2 +"
    n = n - s**2
print n

If you ignore the "**2+" characters, this one comes out to approximately the same number of digits as the original number, on average. Making up for those 4 extra characters per iteration requires a bit of luck. In the case of your number, the result has 670 digits of square numbers, plus 7x"**2+", another failure:
755855006990505232214298076833020140623897728341856142793250050184099570268569900389346192358073922001480310798643405893673501405667458785677166605919485512157948819102093414848159820683798554799982163455753292781944741934237780592730586508786425528910736750640071037094033497266578109597923654387813828207885510302579581252831537751**2+
33300095205899066129442737321270515378501483166974896029394675779096351509514355500527819871697116193238261137790928953798777695127752032484956608505929119246433389165**2+
187763197402063683206154659623192450644818397963460986292088297442441704645626089130**2+
278760215056365252005927060531480627653626**2+
639191600506542558482**2+
25777519523**2+
106673**2+
103405

By almost breaking even on average, this algorithm lends itself well to being used in conjunction with other algorithms (or even itself) to further reduce the numbers in the expression (at the cost of some parentheses). Those other algorithms can be more expensive, as they will be operating on significantly smaller numbers than the original. In the given example, a net gain could be had if a more expensive and effective algorithm could cut out 25% of the characters of 33300095205899066129442737321270515378501483166974896029394675779096351509514355500527819871697116193238261137790928953798777695127752032484956608505929119246433389165 (the second large value in the result)

This approach can be slightly improved by checking for cubes, and very rarely fourth powers, as well.

Nearby large powers
This approach looks for [relatively] small numbers raised to some power that come close to the target number. In most cases restating N as A**B+C will not be an improvement, but in some cases it will be.
def nearest_power(n):
    mindiff = 1
    best = (n,1)
    for a in xrange(2,10000):
        b = math.log(n,a)
        if math.ceil(b)-b<mindiff:
            mindiff = math.ceil(b)-b
            print a,"**",b
            best = (a,b)
        if b-math.floor(b)<mindiff:
            mindiff = b-math.floor(b)
            print a,"**",b
            best = (a,b)
    return best

10000 is an arbitrary constant. The bail-out condition could also be based on some target mindiff.
In the case of your sample number N with 666 digits, this function (with the 10k cap increased a bit) finds that N ~= 165661162**81.0000000025, so N-165661162**81 is a 659 digit number, cutting 7 digits off the number to be handled at a cost of 14 characters of expression, a failure.


text:
Coding Convention Conversion
In that Coding Golf, you should convert one coding convention with TitleCase to lower_case_with_underscores. And... vice versa!
Specification
Change the casing in a following way:

If underscore character is a delimiter, change the casing to Title Case without any of delimiter.
If there are multiple words with no delimiter, change the casing to lower case and add an underscore character as a delimiter.
In case of only one word (or one character): change the casing to Title Case if the word starts with lower case; change the casing to lower case if the word starts with the upper case.

Allowed characters:

A to Z
a to z
underscore (_).

Input with mixed cased words are disallowed. Examples of disallowed cases:

Coding_Convention_Conversion
a_BC

Example Cases
Input                        | Expected Output
===========================================================
CodingConventionConversion   | coding_convention_conversion
coding_convention_conversion | CodingConventionConversion
abc                          | Abc
Abc                          | abc
ABC                          | a_b_c
a_b_c                        | ABC
a                            | A
A                            | a

Rules

It is allowed to use ToUpper, ToLower and ToTitleCase functions.
Using regular expressions is allowed.
code-golf: shortest code in bytes wins!

Is using a ToTitleCase function okay? You didn't specify, so I'd assume it is okay.

@Justin: Good question indeed. Let's make it more fun and disallow the ToTitleCase function :)

Darn... my solution relies on it

@Justin: Okay - I didn't specify it in the beginning, so in that case - let's allow it anyway.

Pyth, 25 bytes 29 33 35 40
Saved 2 bytes thanks to @Dennis
Saved 4 bytes thanks to @FryAmTheEggman
?rIz0smrd4cz\_tsXzrG1*\_G

Try it online

Your link needs to be updated.

When I try put "abc" as an input, it yields "bc" as an output. Bug? :)

To fix what @DariuszWoźniak noticed, you can change your condition from /z\_ to rIz0. I also believe I found a same-length alternative to the adding underscores program: tsXzrG1_Mcj\_G2, maybe someone can golf it more...

Ah, found it: tsXzrG1*\_G

Jolf, 35 bytes
Saves 1 byte thanks to @Cᴏɴᴏʀ O'Bʀɪᴇɴ. This is encoded in ISO 8859-7.
? hI'_ΜGI'_dpyH0pxRGIL0"(?=[A-Z])'_

Woohoo my first Jolf program!
Explanation
   // I = input
? hI'_                              // If input contains _
       GI'_                          // Split on _
      Μ    d                         // Loop, then join
            pyH0                     // Make the first character uppercase
                                    // ELSE...
                  RGIL0"(?=[A-Z])    // Split *after* all uppercase chars
                                 '_  // join with _
                px                   //Make lowercase

Try it online

You can use string separation at the end, so it becomes "(?=[A-Z])'_. The string is closed automatically.

@CᴏɴᴏʀO'Bʀɪᴇɴ oh, cool, thanks!

Retina, 37
Thanks to @ MartinBüttner for saving 4 bytes!
^|[A-Z]
_$0
T`Ll`lL`_.
^_|_(?=[A-Z])

(Note the trailing newline.)
Try it online.  Note this includes extra m`  to configure a couple of lines to treat each input line separately so all testcases may be run in one go.  This is not a requirement of the question, so these are not counted in the score.

Lines 1 and 2 insert _ either at the beginning of input or before uppercase letters.  All words are now _-separated, regardless of case.
Line 3 swaps case of the first letter in each word.
Lines 4 and 5 remove _ either at the start of input, or when followed by an uppercase letter.

This saves four bytes: http://retina.tryitonline.net/#code=bWBefFtBLVpdCl8kMApUYExsYGxMYF8uCm1gXl98Xyg_PVtBLVpdKQo&input=Q29kaW5nQ29udmVudGlvbkNvbnZlcnNpb24KY29kaW5nX2NvbnZlbnRpb25fY29udmVyc2lvbgphYmMKQWJjCkFCQwphX2JfYwphCkE

Also you can avoid the trailing empty line by omitting the last ?= and replacing that stage with $1 (doesn't affect the byte count though).

@Martin Very good - thanks!

GNU Sed, 46
Thanks to @TobySpeight for saving 2 bytes!
Score includes +1 for -E (or -r) option to sed.
s/(^|_)([a-z])/\u\2/g
t
s/[A-Z]/_\l&/g
s/^_//

Try it online.
Fairly straightforward sed:

Line 1 substitutes beginning of line or _, followed by a lowercase letter with the upper case of that letter.  The g flag to s performs this substitution for each instance found
t jumps to the : unnamed label if there were any matches for the above substitution.  This label is implicitly at the end.
Otherwise all uppercase letters are substituted with _ the lower case of that letter
This leaves a leading _ before the first letter.  s/^_// removes that.

@Toby Thanks.  -E works in my GNU sed 4.2.2 (Ubuntu 14.04.3), though its not in the man page.  I read somewhere [citation needed] that -E is newer Posix option that will officially be added to GNU Sed in a newer release, but is already there unofficially.  Regardless, -r does the right thing if -E doesn't work for you.

@Toby lines 280-282 of sed/sed.c are /* Undocumented, for compatibility with BSD sed.  */ case 'E': case 'r':.

@Digital - I was mistaken; my sed does accept -E as a synonym for -r.  I wasn't correctly passing a minimal program e.g. sed -E -e Q

JavaScript (ES6), 87 bytes
s=>s.replace(/[A-Z]|(^|_)(.)/g,(c,_,l,i)=>l?l.toUpperCase():(i?"_":"")+c.toLowerCase())

Explanation
Depending on which part of the regex matched, it replaces the match with the opposite case.
s.replace(
  /[A-Z]|(^|_)(.)/g,
  (c,_,l,i)=>
    l?
      (i?"_":"")+c.toLowerCase()
    :l.toUpperCase()
)

Test

var solution = s=>s.replace(/[A-Z]|(^|_)(.)/g,(c,_,l,i)=>l?l.toUpperCase():(i?"_":"")+c.toLowerCase())
<input type="text" id="input" value="coding_convention_conversion" />
<button onclick="result.textContent=solution(input.value)">Go</button>

PHP 160 bytes
not the shortest but for completeness here my solution in PHP, $s holds the string to convert:
trim(preg_replace_callback('/((^[a-z]|_[a-z])|([A-Z]))/',function($m){return empty($m[2])?'_'.strtolower($m[3]):strtoupper(str_replace('_','',$m[2]));},$s),'_')

Welcome to Programming Puzzles and Code Golf Stack Exchange. Well done for posting something in a language that you knew wasn't going to win. [tag:code-golf] challenges are mostly within languages, so using a non-golfing language is good. +1 d:-D

Ruby, 101 87 75 bytes
->s{s.gsub(/^.|[A-Z]/,'_\0').gsub(/_./,&:swapcase).gsub(/_(?=[A-Z])|^_/,'')}

Unfortunately, this does exactly the same thing as the Retina solution, as that method ended up being shorter than anything else I came up with.

Python 3, 130 bytes
Quick and dirty attempt using regex to split at the caps. Pretty brute force: if anyone can come up with a different approach I'm sure this can be beaten.
import re
lambda s:('_'.join(re.findall('[A-Z][a-z]*',s)).lower(),''.join([a[0].upper()+a[1:]for a in s.split('_')]))[s.islower()]

 3, 15 chars / 32 bytes (noncompetitive)
⟮ѨǱï⟯≠ï?Ⅰ:ѨȎѨƎï

Try it here (Firefox only).
v3 was released after this challenge, with a bunch of bugfixes and library updates.
Explanation
This is just a mashup of builtins.
⟮ѨǱï⟯≠ï?Ⅰ:ѨȎѨƎï // implicit: ï=input
⟮ѨǱï⟯≠ï?        // check if ï is NOT in snake_case
       Ⅰ       // if so, then convert to snake_case
        :ѨȎѨƎï // otherwise, convert to camelCase and make the first letter UPPERCASE

Jelly, 24 bytes
e€ØAḊkŒlj”_$ʋ⁾_ yŒtḲƲ}Ẹ?

Try it online!

Python 3, 86 bytes
lambda s,u='_':''.join([u[i>u:]+i.lower()for i in(s<u)*s]or[u]+s.title().split(u))[1:]

Try it online!
Also works in Python 2.
Making use of the convenient fact that the ascii value for _ (95) is right in between those of the uppercase (65-90) and lowercase (97-122) letters, which allows for easy string comparisons.

Perl 6,  73 72 71  68 bytes
{.comb(/<:Lu><:Ll>*|<:Ll>+/).map({/<:Lu>/??.lc!!.tc}).join('_'x?/<:Lu>/)} # 73
{.comb(/<:Lu><:Ll>*|<:L>+/).map({/<:Lu>/??.lc!!.tc}).join('_'x?/<:Lu>/)}  # 72
{/<:Lu>/??S:g/(^)?(<:Lu>)/{$0||'_'}$1.lc()/!!S:g/[^|_](<:Ll>)/$0.tc()/}   # 71
{.comb(/<:Lu><:Ll>*|<:L>+/).map({/<:Lu>/??.lc!!.tc}).join('_'x!/_/)}      # 68

Usage:
# give it a lexical name
my &code = {...}

for <CodingConventionConversion coding_convention_conversion abc Abc ABC a_b_c a A>
{ say .&code }

coding_convention_conversion
CodingConventionConversion
Abc
abc
a_b_c
ABC
A
a

Explanation:
{
  .comb( / <:Lu><:Ll>* | <:L>+ / ) # grab the "words" only
  .map({
      /<:Lu>/ # if the word has uppercase
    ??
      .lc     # lowercase the whole word
    !!
      .tc     # otherwise titlecase the word
   })
  .join(  # join the words
    '_'   # with '_'
    x     # repeated
    !/_/  # zero times if it had a _, otherwise once
  )
}

You may be wondering why I used the Unicode properties (<:Lu>, <:Ll>) instead of just a character class.
In Perl 6 they are no longer spelled [a-z] they are spelled <[a..z]> which is 1.6 times as big.
The brackets [ … ] are used for non-capturing grouping instead which was spelled as (?: … ) in Perl 5.

Japt, 40 bytes
UfV="%A" ?UrV@'_s!Y +Xv} :Ur"^.|_."_sJ u

Test it online!
How it works
           // Implicit: U = input string
UfV="%A"   // Set variable V to the string "\\A", and get all matches in U.
?          // If the list is not null:
UrV@     } //  Replace each match X and its index Y with this function:
'_s!Y +Xv  //   Return "_".slice(!Y) (1 for Y=0, 0 for anything else) + X.toLowerCase().
:          // Otherwise:
Ur"^.|_."  //  Replace the char at the beginning and each char following an underscore with:
_sJ u      //   The last char of the match (the letter) .toUpperCase().

Why is the U not automatically inserted?

@SamuelWaller, because this solution pre-dates that feature being added.

Perl 5, 42 bytes
40 bytes plus 2 for -p (thanks, dev-null)
s/[A-Z]/_\l$&/g||s/(^|_)(.)/\u$2/g;s/_//

On Windows, using perl and MINGW32, I get no output, what am I missing?

@ChatterOne I don't know what MINGW32 is, but it worked fine for me on Strawberry Perl. Use -E instead of -e.

Forth (gforth), 129 bytes
: f bounds dup c@ 32 xor emit 1+ ?do i c@ '_ < if ." _"i c@ 32 + emit then i c@ '_ > if i 1- c@ '_ = 32 * i c@ + emit then loop ;

Try it online!
Code Explanation
: f              \ start a new word definition
  bounds         \ convert string address and length to beginning and ending address
  dup c@         \ get the first character
  32 xor emit    \ convert to the opposite case and output
  1+             \ add 1 to beginning of string (skip starting char)
  ?do            \ begin counted loop over string character addresses
    i c@ '_ <    \ check if char is uppercase
    if           \ if it is:
      ." _"      \ output underscore
      i c@       \ get current char
      32 + emit  \ convert to lowercase and output
    then         \ end if block
    i c@ '_ >    \ check if lowercase (not '_')
    if           \ if it is:
      i 1- c@    \ get the previous character
      '_ = 32 *  \ if it's an underscore, multiply by 32 (true = -1 in forth)
      i c@ +     \ add result to current char (make uppercase if previous was '_')
      emit       \ output resulting char
    then         \ end if block
  loop           \ end loop
;                \ end word definition

Pip, 37 bytes
'_Na?UC@_.@>_Ma^'_(LC_MRXU.XL.'+a)J'_

Try it online!
Lot of underscores in this one.

Japt, 27 26 bytes
I fear I may have gone in the wrong direction with this; stuck on 27 and can't seem to do any better.
r"^.|_.|%A"ÈÌc^H i'_pY©XÊu

Try it
r"^.|_.|%A"ÈÌc^H i'_pY©XÊu     :Implicit input of string
r                              :Replace
 "^.|_.|%A"                    :RegEx /^.|_.|[A-Z]/g
           È                   :Pass each match X at 0-based index Y through the following function
            Ì                  :  Last character of X
             c                 :  Charcode
              ^H               :  Bitwise XOR with 32
                 i             :  Prepend
                  '_p          :    "_" repeated
                     Y©        :      Logical AND of Y and
                       XÊ      :      Length of X
                         u     :      Mod 2

K (ngn/k), 43 bytes
{("_"/(&x<_x)__x;,/`c$t-32*~<'t:"_"\x)x~_x}

Try it online!

x~_x check if the input x is all lowercase
(...;...) index into this two-item list depending on that value (i.e., return the first item in the list if x contains an uppercase letter, and the second item if it does not)
When x contains an uppercase letter:

(&x<_x) identify indices of uppercase letters
(...)__x split the lowercased input on those indices
"_"/ join the resulting chunks with underscores

When x is all lowercase:

t:"_"\x split input on underscores, storing in variable t
t-32*~<'t capitalize the first letter in each chunk (this converts to integers)
,/`c$ convert back to characters, flattening the list

Japt, 37 bytes
a'_ Ä?Uq'_ ®hZu g} q:Uò@Yc <#a} q'_ v

Try it online!
Explanation:
There are some unicode chars that a shortcuts for common groups of chars,
like Ä is +1. This is the expanded version.

     // U = input string
a'_  // get index of "_" in string, -1 if not found
+1   // add 1 to make -1 falsy
?    // if truthy, ie. if there is an underscore in the input text
Uq'_ // split on underscores
m_   // map
h    // replace character (first char by default)
Zu g // the first letter of the string converted to uppercase (Zug)
} q  // close function and join
:    // else, ie. the string doesn't have any underscores
Uò   // runs func on every pair of chars, splits them if it returns true
@Yc <#a } // returns true if the second char code is less than "a", ie. uppercase
q'_  // join with underscores
v    // make lowercase

implicit print

First Japt program, I beat the creator, and Zu g!


text:
Draw a network of nodes
There is a network of up to 26 nodes (named A to Z or a to z as per your wish). Every pair of nodes may be connected or disconnected. A node may be connected to at most 4 other nodes. Your task is to draw the network in a 2D diagram. Input will be given such that this task is possible (see more constraints in output section).

Format
Input

Pairs of letters (A to Z or a to z as per your wish). They are not sorted in any order.
Optional - number of pairs

Output

An ASCII drawing that shows the actual links between the nodes. Nodes are given by a to z or A to Z. Use - for horizontal links and | for vertical links. Links may be of any (non-zero) length but they should be straight horizontal/vertical lines that do not bend. Spaces can be added provided they don't disfigure the picture.

You may not use built-ins that help in layout of the graph. Other graph-related built-ins may be allowed (though solutions without built-ins would be more appreciated). Shortest code wins.

Sample data
Input
A B
B F
B L
F K
L K
K R
K S
R P
S J
S P
J A
T V
V N

Output
A - B - F   T - V
|   |   |       |
|   L - K - R   N
|       |   |
J ----- S - P

Input
H C
G H
A B
B F
B C
F G
C D
D A

Output
A - B ----- F
|   |       |
D - C - H - G

I consider that my previous questions have been sufficiently answered, but note that the new test case is wrong because the first line is H A and that edge isn't in the given output. Edit: problem identified and fixed.

Maybe change it to "First (working) code wins"? ;-) Seriously, this is challenging on its own, even without golfing...

@Marco13 That would most likely get the challenge closed as off topic.

@ghosts_in_the_code Please don't use flags to ask moderators questions. If you need feedback on something, there's always The Nineteenth Byte.

@Dennis ok, sorry. I've never been on chat before, so I don't know how it works.

Just click the link, click logged in at the bottom of the page, log in as you usual do, and go back to the chat page.

Will there always be at least one edge? Can there be isolated vertices? Can a node be connected to itself with an edge?

@mbomb007 Isolated vertices don't have to be outputted (like in the examples). A node cannot be connected to itself. Your code doesn't need to work for empty input.

"Never mind the golfing requirement for now." Regardless of the difficulty of the answer, answers still need to follow the rules, part of which are that all answers need to make at least an attempt at golfing the code. Please don't encourage people to do otherwise.

@MartinEnder Ok then, if you say so. Btw why are non-golfing coding questions not allowed on this site? And which site would they be better to put on?

They just have a different tag. Like [code-challenge], [king-of-the-hill], [code-bowling], etc

@mbomb007 Ik. But still it isn't as well accepted if I submit it as code-challenge

It depends how you submit it. But for the most part that's because it needs an objective winning criterion, and the easiest one is byte-count. Any other criterion is likely to be seen as inferior.

@mbomb007 Why isn't 'first working solution' an objective criterion?

It is, but only one submission gets to compete. So if you're not first, what's the point in trying?

@ghosts_in_the_code what about crossings/overlaps, e.g. ad,bd,cd,ae,be,ce,af,bf,cf

@Rod Input will be given such that there's always atleast one way to draw it.

CJam, 142
You didn't ask for an optimal, deterministic or fast solution, so here you go:
qN%Sf%::c_s_&:Aff#:E;{A{;[DmrDmr]2f*}%:C;E{Cf=~.-:*}%0m1{E{Cf=$~1$.-_:g:T\:+,1>\ff*\f.+T0="-|"=f+~}%CA.++:L2f<__&=!}?}gS25*a25*L{~2$4$=\tt}/N*

Try it online
This generates random coordinates for each letter and tests if the layout is acceptable (edge letters lining up and no intersections), until it is. It gets mind-numbingly slow as you add more edges.
The two D letters in the code specify the maximum x and y coordinates; I picked D (=13) because I think it should be sufficient for all cases, feel free to prove me wrong. But you can change them to other values to speed up the program, e.g. the 2nd example should finish within a minute or two if you use 3 and 4 instead.

I didn't ask for a fast solution, but maybe I should have asked for a deterministic one. But now that the question has been up for so long, I won't change it.

@ghosts_in_the_code it shouldn't be too hard to make it deterministic - try all combinations of coordinates. But it would probably be longer and much slower, and eat a lot of memory too.

C, 813 bytes
#include<map>
#include<set>
#include<cstdlib>
typedef int I;typedef char*C;I a,t,s,h;struct p{I x,y;}j,k;std::map<I,std::set<I>>l;std::map<I,p>g;C m,M="  |-";I L(I n,C q,C Q){j=g[n],h=1;for(I o:l[n])if(g.find(o)!=g.end())if(!(a=(k=g[o]).y==j.y)&&k.x^j.x)h=0;else for(I x=j.x,y=j.y,e=k.y*s+k.x,b,d=(k.x<j.x||k.y<j.y)?-1:1;a?x+=d:y+=d,(b=y*s+x)^e;m[b]=q[a])if(m[b]^Q[a]){h=0;break;}}I N(){for(auto i:g)for(I n:l[i.first])if(g.find(n)==g.end())return n;for(auto i:l)if(g.find(a=i.first)==g.end())return a;exit(puts(m));}I f(){for(I n=N(),x,y=0,b;y<s;y+=2)for(x=0;x<s;x+=2)m[b=y*s+x]==*M?g[n]={x,y},m[b]=n,L(n,M+2,M),h&&f(),L(n,M,M+2),m[b]=*M,g.erase(n):0;}I main(I c,C*v){for(;--c;l[a].insert(s),l[s].insert(a))a=v[c][0],s=v[c][1];t=l.size(),s=t|1;memset(m=(C)calloc(s,s),*M,s*s-1);for(a=1;a<s;++a)m[a*s-1]=10;f();}

Takes input as commandline arguments, e.g.:
./network AB BF BL FK LK KR KS RP SJ SP JA TV VN

Nowhere near competitive with aditsu's answer by size, but much more efficient!
This will brute-force all possible solutions, but will quickly recognise failure as it goes. For the two test cases, it finishes almost immediately, and it seems to only take a few seconds on more awkward inputs. It also has no limitation to the accepted node names (though you can't name one space, | or -) and has no limit on the number of nodes (as long as all names fit in a byte, so the practical limit is 252 nodes, and it will get slow long before reaching that many).
There's plenty of scope for speeding this up; a lot of short-circuit exiting was lost to the golfing, and there's parts which could be moved out of hot-loops. Also some observations of symmetry can dramatically reduce the positioning of the first 2 nodes, among other things.

Breakdown:
#include<map>
#include<set>
#include<cstdlib>
typedef int I;
typedef char*C;
I a,t,s,h;                // Variables shared between functions
struct p{I x,y;}          // Coord datatype
j,k;                      // Temporary coord references
std::map<I,std::set<I>>l; // Bidirectional multimap of node links
std::map<I,p>g;           // Map of nodes to positions
C m,                      // Rendered grid
M="  |-";                 // Lookup table for output characters

// Line rendering function
// Sets h to 1 if all lines are drawn successfully, or 0 if there is a blocker
I L(I n,C q,C Q){
  j=g[n],h=1;
  for(I o:l[n])                  // For each connection to the current node
    if(g.find(o)!=g.end())       // If the target node has been positioned
      if(!(a=(k=g[o]).y==j.y)&&k.x^j.x)h=0; // Fail if the nodes are not aligned
      else
        for(I x=j.x,y=j.y,             // Loop from node to target
          e=k.y*s+k.x,
          b,d=(k.x<j.x||k.y<j.y)?-1:1;
          a?x+=d:y+=d,(b=y*s+x)^e;
          m[b]=q[a])                   // Render character (| or -)
          if(m[b]^Q[a]){h=0;break;}    // Abort if cell is not blank
}

// Next node selection: finds the next connected node to try,
// or the next unconnected node if the current connected set is complete.
// Displays the result and exits if the entire graph has been rendered.
I N(){
  for(auto i:g)for(I n:l[i.first])  // Search for a connected node...
    if(g.find(n)==g.end())return n; // ...and return the first available
  for(auto i:l)                     // Else search for an unconnected node...
    if(g.find(a=i.first)==g.end())
      return a;                     // ...and return the first available
  exit(puts(m));                    // Else draw the grid to screen and stop
}

// Recursive brute-force implementation
I f(){
  for(I n=N(),x,y=0,b;y<s;y+=2) // Loop through all grid positions
    for(x=0;x<s;x+=2)
      m[b=y*s+x]==*M            // If the current position is available
       ?g[n]={x,y},             // Record the location for this node
        m[b]=n,                 // Render the node
        L(n,M+2,M),             // Render lines to connected nodes
        h&&f(),                 // If line rendering succeeded, recurse
        L(n,M,M+2),             // Un-render lines
        m[b]=*M,g.erase(n)      // Un-render node
       :0;
}

// Input parsing and grid setup
I main(I c,C*v){
  // Parse all inputs into a bidirectional multi-map
  for(;--c;l[a].insert(s),l[s].insert(a))a=v[c][0],s=v[c][1];
  t=l.size(),s=t|1; // Calculate a grid size
  // Allocate memory for the grid and render newlines
  memset(m=(C)calloc(s,s),*M,s*s-1);
  for(a=1;a<s;++a)m[a*s-1]=10;
  f(); // Begin recursive solving
}

Finally! It's been 2 months. I personally am not in favour for golfing such an answer, I was only required to, by the people of this site.

@ghosts_in_the_code if you don't want code golf there are plenty of other objective winning criteria you can use (though obviously, you can't change this challenge now it's been posted). Time-based examples would be: fastest to generate results on specific hardware (e.g. particular EC2 instance / raspberry pi / etc.), most compact output for a battery of tests within a time limit, largest network supported from a battery of tests within a time limit (e.g. a day, allowing flexibility on the specific hardware). Try using the sandbox next time; people can help you pick an objective.

746 bytes


text:
Can my 4-note music box play that song?
I have a crank-operated music box that can play a series of four notes. When I turn the crank, it plucks one of four strings, depending on the position of the crank and the direction of the turn. When the crank is turned due north, the box (with its strings numbered 1 through 4) looks like this:
1  |  2
   |
   O

4     3

From there, I can turn the crank clockwise to pluck the #2 string and point the crank east:
1     2

   O---

4     3

Alternatively, I could have also turned the crank counterclockwise from north to play the #1 string and end with a crank pointing west:
1     2

---O

4     3

At any given time, then, the box can play one of two notes: the next note available in the clockwise direction or the next note in the counterclockwise direction.
Challenge
Your challenge is to write a program or function that accepts a non-empty string of note values (i.e., numerals 1 through 4) and determine if it is ever possible to play that sequence of notes on the music box. Produce a truthy or falsy result to indicate the playability or non-playability of the input.
Some notes:

The input makes no assumptions about initial start position. The inputs 214 (starting east and moving strictly counterclockwise) and 234 (starting north and moving strictly clockwise) and both valid.
The crank may move freely in either direction after each note. A series of the same note is possible (e.g., 33333) by moving back and forth across one string. The series 1221441 is perfectly playable (starting west, moving clockwise two steps, then counterclockwise three steps, then clockwise two steps).

Samples
Some true cases:
1
1234
1221
3333
143332
22234
2234
22214
1221441
41233

Some false cases:
13     (note 3 is never available after note 1)
1224   (after `122`, the crank must be north, so 4 is not playable)
121    (after `12` the crank is east; 1 is not playable)
12221  (as above, after `1222` the crank is east)
43221

Can the input be the string including quotes?

@LuisMendo Sure, I'll allow it -- I'm interested in your algorithm, not making you jump through hoops to get the input. Anyway, there's unofficial community consensus that it's generally okay: String input with or without “”?

I didn't know that. Thanks for the link!

Is there a limit to the maximum number of times a song will make me go all the way around?

@AJMansfield No, solutions should allow for arbitrarily many cycles. Of course, if some input causes your code to exceed a limit in your language's interpreter or your computer's memory, that's fine (since it's merely limited by however much memory you physically have or your interpreter allows), but your solution should not impose extra limitations on how far or how many times the crank moves.

Test case: 234123412341234: True

This problem reminds me of the code I wrote to play the Toyshop Trouble music (https://www.youtube.com/watch?v=miN90xEJh3s) on the Atari 2600.  Each 8-beat measure uses a set of four melody notes, and every 32-beat phrase uses the same four sets; since I budgeted 256 bytes for music code and data (I actually went somewhat over) so the tune had to work with something like your four-note music box.

This challenge has won the Not as simple as it looks category in Best of PPCG 2016. Unfortunately, we can't give bounties to challenges, but Zgarb has written a challenge in your honour. Congratulations!

Pyth, 30 27 bytes
f!-aVJ.u%-ysYN8zTtJ,1 7cR2T

Here's the idea:
 1.5  1  0.5

  2       0

 2.5  3  3.5

The crank is always at a half-integer position c. At each step, we reflect it over an integer position note n by setting c = 2*n-c. If n is valid, c changes by ±1 mod 8. If n is invalid, c changes by ±3 mod 8. We cumulatively reduce over the input to collect all values of c, and then see if all notes were valid. We do this for every starting value of c, because it's shorter than checking just the ones adjacent to the first note.
Formatted:
f
  ! -
      aV J .u
              % -
                  y s Y
                  N
                8
              z
              T
         t J
      ,
        1
        7
  cR2 T

Test suite.

CJam, 34 31 bytes
8,q{~2*f{_@-_zF8b&,@@+8,=*}0-}/

Did this on my phone, so I'll have to put up an explanation later. Output is nonempty iff truthy.
Try it online | Test suite
Explanation
The new code shifts the layout a little:
2    3    4

1    .    5

0/8  7    6

Even numbers correspond to string positions and odd numbers correspond to crank positions.
Here's what happens:
8,           Create the range [0 1 .. 7] of possible starting positions
             We can leave the string positions [0 2 4 6] in since it doesn't matter
q{ ... }/    For each character in the input...
  ~2*          Evaluate as integer and double, mapping "1234" -> [2 4 6 8]
  f{ ... }     Map over our possible current crank positions with the string
               position as an extra parameter
    _@-          Calculate (string - crank), giving some number in [-7 ... 7]
    _z           Duplicate and absolute value
    F8b          Push 15 base 8, or [1 7]
    &,           Setwise intersection and get length. If (string - crank) was in
                 [-7 -1 1 7] then the move was valid and this evaluates to 1, otherwise 0
    @@+          Calculate ((string - crank) + string)
    8,=          Take modulo 8, giving the new crank position. x%y in Java matches the
                 sign of x, so we need to do ,= (range + index) to get a number in [0 .. 7]
    *            Multiply the new crank position by our previous 0 or 1
  0-           Remove all 0s, which correspond to invalid positions

The stack is then automatically printed at the end. Any possible ending positions will be in the output, e.g. for the input 1 the output is 31, which means the crank can end facing either left or up.
If only CJam had filter with extra parameter...

Edit: Temporarily rolling back while I convince myself that this 29-byte works:
8,q{~2*f{_@-_7b1#@@+8,=|}W-}/

Every time someone answers with some difficult language like cjam and says "did this on my phone" I die a little inside

He probably meant the text was outputted using a phone, but it was done in his head.

Haskell, 93 88 87 bytes
any(all(\(a,b:c)->1>mod(a!!1-b)4).(zip=<<tail)).mapM((\a->[[a,a+1],[a+1,a]]).read.pure)

This evaluates to an anonymous function that takes a string and returns a boolean. Test suite here.
Explanation
The idea is that the lambda on the right maps a number a to [[a,a+1],[a+1,a]], the two possible "moves" that take the crank over that number, according to the following diagram:
  1 (2) 2

(1/5)  (3)

  4 (4) 3

In the main anonymous function, we first do mapM((...).read.pure), which converts each character to an integer, applies the above lambda to it, and chooses one of the two moves, returning the list of all resulting move sequences.
Then, we check if any of these sequences has the property that the second number of each move equals the first number of the next modulo 4, which means that it's a physically possible sequence.
To do this, we zip each move sequence with its tail, check the condition for all the pairs, and see if any sequence evaluates to True.

Retina, 50 bytes
A`13|31|24|42|(.)(?!\1)(.)(\2\2)*(\1|\2(?!\1|\2).)

I think this works?
Try it here.

Retina, 127 109 bytes
^((1|2)|(2|3)|(3|4)|(4|1))((?<2-5>1)|(?<5-2>1)|(?<3-2>2)|(?<2-3>2)|(?<4-3>3)|(?<3-4>3)|(?<5-4>4)|(?<4-5>4))*$

This prints 0 or 1, accordingly.
Try it online! (This is a slightly modified version which marks all matches in the input instead of printing 0 or 1.)
I tried coming up with an elegant algorithm, but my first few attempts weren't able to circumvent backtracking... and implementing backtracking is annoying... so I used a language which does the backtracking for me where I just need to encode a valid solution. Unfortunately, the encoding is fairly verbose and fairly redundant... I'm sure this can be shortened.
While I try to figure out something neater, if anyone wants to sort out how this works, here is a somewhat more readable version:
^
(
    (?<a>1|2)
  | (?<b>2|3)
  | (?<c>3|4)
  | (?<d>4|1)
)
(
    (?<a-d>1) | (?<d-a>1)
  | (?<b-a>2) | (?<a-b>2)
  | (?<c-b>3) | (?<b-c>3)
  | (?<d-c>4) | (?<c-d>4)
)*
$

And here is a hint:
1  a  2

d  O  b

4  c  3

MATL, 57 55 bytes
1t_hjnZ^!t1tL3$)2_/wvG1)UGnl2$Ov+Ys.5tv3X53$Y+4X\G!U=Aa

This uses current release (10.2.1), which is earlier than this
challenge.
EDIT (17 January, 2017): due to changes in the language, v needs to be replaced by &v, and tL3$) by Y) (in addition, some other improvements could be done). The following link includes those two modifications
Try it online!
Explanation
This is based on two of my favourite tools for code golf: brute force and convolution.
The code defines the path followed by the crank in terms of coordinates 0.5, 1.5 etc. Each number tells the position of the crank between notes. The code first builds a path array with all possible paths that start with the first note of the input string. Each path is a column in this array. This is the brute force component.
From this path array, a note array is obtained, where each column is a realizable sequence of played notes. For example, movement from position 0.5 to 1.5 produces a note 1. This consists in taking the average between positions and then applying a modulo 4 operation. The running average along each column is done with a 2D convolution.
Finally, the program checks if any column of the note array coincides with the input.
1t_h        % row array [1, -1]
j           % input string
nZ^!        % Cartesian power of [1, -1] raised to N, where "N" is length of string
t           % duplicate
1tL3$)      % extract first row
2_/         % divide by -2
wv          % attach that modified row to the top of Cartesian power array
G1)U        % first character of input string converted to number, "x"
Gnl2$O      % column array of N-1 zeros, where N is length of input
v           % concat vertically into column array [x;0;0...;0]
+           % add with singleton expansion
Ys          % cumulative sum along each column. Each column if this array is a path
.5tv        % column array [.5;.5]
3X5         % predefined string 'same' (for convolution)
3$Y+        % 2D convolution of path array with [.5;.5]
4X\         % modified modulo operation. This gives note array with values 1,2,3,4
G!U         % column array of input string characters converted to numbers
=Aa         % true if any column of the note array equals this

Pyth, 43
Km-R2sMdc`M%R4-VJjQTtJ`0|Fm!s-VKdCm_B^_1dlK

Test Suite
This is probably very golfable, and also not the optimal algorithm for golfing (I expect enumerating all paths will be shorter?)... Anyway, if you find any error with the algorithm please let me know, I think it should work but I've been wrong before!
I'll explain my algorithm using the example input of 1221. This program first maps the digits against their successors, like so: [[1,2],[2,2],[2,1]]. Then it gets their differences mod 4 (Pyth gets the result that matches the sign of the right argument of %, so this is always positive) : [3,0,1]. Then the results are split on 0 and have 2 subtracted from each of them: [[1],[-1]].
Now that the setup is done, we create a list of [-1,1,-1...] and its negation [1,-1,...], both the same length as the resulting array from before. Then, for each of these lists, perform setwise subtraction between the elements of the list and the list generated in the earlier step.  Then, if either of the results contains only empty lists, we output true.

What do you mean by "the results are split on 0"? In particular, what would you get for 1221221 and 1221441?

@Neil 1221221 is false and 1221441 gives true overall, but if I understand you want the result after that step in the algorithm? If that is the case it gives: from [3, 0, 1, 3, 0, 1] to [[3], [1, 3], [1]] and [3, 0, 1, 1, 0, 3] to [[3], [1, 1], [3]]. Let me know if you want something else explained :)

I think I'm more confused than before, so could you please finish those two examples to explain how the (correct) results are achieved?

@Neil Sure, no problem :) From there, we do the subtraction to get: [[1], [-1, 1], [-1]] and [[1], [-1, -1], [1]] from here, you can see that the first one does not have lists that alternate between -1 and 1 while the other list does, giving the final result. The algorithm is a bit obtuse, but it's basically mapping direction changes to 0 and direction as +/-1, then checking that no jumps are made and the directions make sense.

Oh, so the bit I was missing was that each split list must consist of the same value, and those values must alternate. Thanks!

ES6, 104 100 bytes
s=>!/13|24|31|42|3[24]{2}1|4[13]{2}2|1[24]{2}3|2[13]{2}4|(.).\1/.test(s.replace(/(.)(\1\1)+/g,"$1"))

Edit: Saved 4 bytes thanks to @DigitalTrauma.
This is a complete rewrite as my previous approach was flawed.
I start by reducing all runs of digits to 1 or 2 depending on whether there was an odd or even number in the run. I then look for all the illegal combinations:

13|24|31|42 (opposite sides)
3[24]{2}1 as 3221 and 3441 are illegal
similarly for 4xx2, 1xx3 and 2xx4 where x is either of the missing digits
(.).\1 as things like 121 are illegal (111 has been reduced to 1 earlier)

If there are no illegal pairs or "triples" then the whole string is legal (proof by induction is left as an exercise because it's late night here).
I tried to simplify 3[24]{2}1|1[24]{2}3 using a negative lookahead assertion but it turned out to be longer that way.

f("1122") => true @DigitalTrauma

@CᴏɴᴏʀO'Bʀɪᴇɴ I see nothing wrong with that. On the other hand I've realised that f("1221221") outputs the wrong answer, so I'll have to rethink.

It's alway nice to include a test suite, '43221' fails: https://jsbin.com/vafitotequ/1/edit?js,console

@Pavlo Whoops, I'd golfed [24][24] to (2|4)\1 but I hadn't tested adequately. Sorry about that.

Can you golf [24][24] to [24]{2}?

@DigitalTrauma Thanks that looks good!

Almost as short (110 bytes) without using regexes: http://codegolf.stackexchange.com/a/70824/48325

Matlab, 279 180 bytes
o=eye(4);a=input('')-'0';M=[o,o(:,[4,1:3]);o(:,[2:4,1:4,1])];x=2;for p=[a(1),mod(a(1),4)+1];for k=a;i=find(M*[o(:,k);o(:,p)]>1);if i;p=mod(i-1,4)+1;else;x=x-1;break;end;end;end;x>0

Quite a lazy solution, but the shortest I was able to come up with. I created special matrix: When you encode the state of the plucker and the last string that is to be plucked, it returns a vector, that encodes the new position of the plucker, and whether the previous pluck was possible at all. Now we just loop over all notes from the two possible start positions and see if one of them results in a playable melody.  Can probably be golfed a lot more.
Expanded and explained source:
o=eye(4);
a=input('')-'0';

% encoding of plucker/notes
%      1
%   1     2
%4           2
%   4     3
%      3
%

M=[...
%12 3 4 1 2 3 4 <
1,0,0,0,0,1,0,0; %1  k = current note
0,1,0,0,0,0,1,0; %2
0,0,1,0,0,0,0,1; %3
0,0,0,1,1,0,0,0; %4
0,0,0,1,0,0,0,1; %1  p = current position of plucker
1,0,0,0,1,0,0,0; %2
0,1,0,0,0,1,0,0; %3
0,0,1,0,0,0,1,0];%4
% the vector we multiply with this matrix has following structure,
% the k-th and the p+4 th entries are 1, the rest 0
% when we multiply this vecotr with this matrix, we get a vector with an
% entry of value 2 IF this is a valid move ( mod(positionOfThe2 -1,4)+1 is
% the position of the plucker now)
% or only entries less than 2 it is impossible
x=2;  %number of "chances" to get it right
for p=[a(1),mod(a(1),4)+1] %check both starting values;
    for k=a;                %loop throu the notes
        size(M);

        c = M * [o(:,k);o(:,p)];
        i=find(c>1);               %did we find a 2?
        if i;
           p=mod(i-1,4)+1;         %if yes, valid move
        else;
            x=x-1;                 %if no, invalid,
            break;
        end
    end
end
x=x>0 %if we failed more than once, it is not possible

Lua, 146 142 108 162 159 149 144 135 132 118 113 bytes
z,q,s=0,0,io.read()for i in s:gmatch'.'do t=i-z if 2==math.abs(t)or t==q then return''end q=-t z=i end return 2>1

Returns true or false given a string of numbers between 1 and 4. (Doesn't handle no data or out of range numbers.
Simply tracks what the last movement was and checks if this movement is a reversal of the last movement (IE, 121 or 12221) or if the distance moving is more than possible.
EDIT 1:
Saved 6 bytes. I forgot that if (int) then returns true if int is non zero.
Thus:
if t~=0 then

changes to:
if t then

Also saved a few bytes by restructuring.
EDIT 2:
I'm slowly figuring this out. I've been reading the documentation here: http://www.lua.org/pil/ And one of the more useful pages there for golfing is http://www.lua.org/pil/3.3.html
In particular, this is very helpful:

Like control structures, all logical operators consider false and nil as false and anything else as true.

What this means for me is that I can go ahead and remove my declaration for q (which was initially set to 0) as it will be regarded as "false" until it is set. So I save a few more bytes through this.
Another thing worth mentioning, though I don't use it, is if you want to swap values in Lua, you can simply do a,b=b,a without the need for a temporary variable.
EDIT 3
So, through some clever reconstruction as well as a new function, I've got the byte count down by 9 more.
Best Mode for Receiving Input
If you need to read in a list of numbers and do operations on them one at a time, you can use:
for x in string:gmatch('.') do
    print(x) --This is our number
end

When compared to your alternative using string:sub, you can see the value for golf (or general use):
for x=1,string:len() do
    print(string:sub(x,x)) --This is our number
end

Restructure Functions or Strings
Second thing, if you have multiple declarations on one line and one of the values is a function or you have a condition in which you compare a number to the result of a function like these:
x,y,z=io.read(),0,0 print('test')

if math.abs(x)==2 then

by restructuring it so the closing parenthesis are the last character in the condition or declaration, you can cut out a character like so:
y,z,x=0,0,io.read()print('test') --Notice no space

if 2==math.abs(x)then --If we put the '2' first in the conditional statement, we can now remove a space character

Return Conditions that Equate to True or False instead of 'True' or 'False'
I found a semi amusing way to cut my byte count down yet further. If you need to return true or false, you can return a statement that equates to true or false that has less characters than "true" or "false" themselves.
For instance, compare:
return true
return false

To:
return 2>1
return 1>2

121 should output false.

Ah, nevermind. I see. Will fix shortly

You might be interested in adding some of those Lua tips to Tips for golfing in Lua if you don't see them listed there already.

JavaScript (ES6), 80 bytes
s=>[r=0,1,2,3].map(i=>[...s].map(n=>n-1-i%4?n%4-i%4?v=0:i+=3:i++,v=1)|v?r=1:0)|r

Explanation
i%4 is the current crank position:
    1 (i%4 == 1) 2

(i%4 == 0) (i%4 == 2)

    4 (i%4 == 3) 3

Indented and Commented
s=>
  [r=0,1,2,3].map(i=> // i = crank position, test for i starting at 0 to 3, r = result
    [...s].map(n=>    // for each note n
      n-1-i%4?        // if n is not at the position after i
        n%4-i%4?      // if n is not at the position before i
          v=0         // set the result of this test to invalid
        :i+=3         // else i-- (+3 used because i%4 would break for negative values)
      :i++,           // else i++
      v=1             // v = result of test, initialise to 1 (valid)
    )
    |v?r=1:0          // if the test returned true, set the result to true
  )
  |r                  // return the result

Test

var solution = s=>[r=0,1,2,3].map(i=>[...s].map(n=>n-1-i%4?n%4-i%4?v=0:i+=3:i++,v=1)|v?r=1:0)|r
<input type="text" value="1221441" oninput="result.textContent=solution(this.value)" />
<pre id="result"></pre>

Nicely done. Would you explain how | works in this case?

@pavlo Thanks. It's a shorter way of writing (x.map(...),v). It works because the array that the map returns casts to 0 and 0|v == v.

Python (3.5) 160 151 150 bytes
A recursive solution
def f(s):g=lambda s,c:s==''or g(s[1:],(c[:4]*2)[(s[0]==c[0])*2+1:])if s==''or s[0]in c[:2]else 0;return any([g(s,"1234123"[i:])for i in range(4)])

Ungolfed without lambda
def f(s):
    def g(s,c):
        if s=='' or s[0] in c[:2] :
            return s=='' or g(s[1:],(c[:4]*2)[(s[0]==c[0])*2+1:])
        else:
            return False
    return any([g(s,"1234123"[i:]) for i in range(4)])

I rotate all the box instead of the crank. The crank position is between first and second character of the c string. I need to test all beginning position of the crank.
Trick use to rotate the string
The usual way to rotate a string in python (s[i:]+s[:i]) need too repeat both index and string.
In this case i duplicate the string and crop first characters.
(c*2)                        # duplicate the string
     [(s[0]==c[0])*2+1       # test that return 1 if firsts characters match 3 instead
                      :]
                        [:4] # crop again to have a 4 characters string

Test cases
[f(i) for i in ["1", "1234", "1221", "3333", "143332", "22234", "2234", "22214", "1221441", "41233", "13", "1224", "121", "12221", "43221"]]
[True, True, True, True, True, True, True, True, True, True, False, False, False, False, False]

You can remove the space at 3"[i:]) for.

@EriktheOutgolfer thanks I remove it.

MATL, 49 bytes (non-competing1)
1. The answer (ab)uses the less strict indexing of newer versions of MATL, and would not have worked at the time this challenge was posted.
dt~aX`tt~f1)q:)w3MQJh)_ht~a]tT-3hX|n2=wT_3hX|n2=+

Try it online!.
I saw this challenge at the Best of PPCG 2016, and figured that this could use my favourite operator:
d

Or, diff in MATLAB/Octave (I will freely use MATLAB/Octave terminology in my explanation, since it is easier to read for humans). This command calculates the element-wise difference in a vector or, in this case, in a character array.
For this problem, the differences exhibit an interesting pattern. Note that

An change in direction must mean that a note is played twice.

For the difference pattern (ignoring the 1-4 transition for now), this means that

A change in sign in diff(input) must have an odd number of zeroes in between. Conversely, the sign is not allowed to change after an even number of zeroes.

I implemented this by, for each array, finding the first zero. I trim the zero out, and multiply all elements after it by -1. For the end result, this means that all elements must have the same sign. Of course, there is the small issue of the -3 equalling +1, and 2 being disallowed in general. I solved this by taking the set union of the result with [1 -3], and checking whether this is of size 2 (i.e., no disallowed elements 'entered' the set through the union). Repeat for [-1 3], and check whether either (or both, in the case of a 1-length input) is true.
d                                % Difference of input
 t~a                             % Check if any element equals 0
    X`                     t~a]  % Start while loop, ending in the same check
       t~                           % Get a new vector, logical negated to find zeroes.
          f1)                       % Find the position of the first zero.
      t         q:)                 % Decrement by 1, to index all elements before that zero.
                   w3MQJh)          % Push the result of 'find', but increment to get all elements after.
                         _h         % Multiply the second half by -1, and concatenate horizontally.

  T-3hX|n2=                      % Check if set union with [1 -3] is size 2
 t        wT_3hX|n2=             % Check if set union with [-1 3] is size 2
                    +            % Logical OR.

@LuisMendo Thanks. I really need to read up on M, last time I tried it, it worked differently than expected so I just ignored it for the time being. Is it correct to say that it needs to be 3M because then I get the input of not ), not :but of q (skipping w as it's not a normal function)?

Yes, exactly. w is skipped because it's not a normal function. Normal functions that take no inputs would be skipped too

Python 2, 65 bytes
n=15
for c in input():k=2**int(c);n=n*17/k%4*5/2%4*k%15
print n>0

Try it online!

JavaScript (ES2015), 110 95
p=(s,d)=>(h=s[0],t=s.slice(1),g=t[0],!g||(d?g==h?p(t,-d):g%4==(h-d)%4&&p(t,d):p(s,1)||p(s,-1)))

15 bytes saved by Neil! Original version ungolfed:
p = (s, d) => {
  h = s[0]
  t = s.substr(1)

  if (!t[0]) return true
  if (!d) return p(s, 1) || p(s, -1)
  if (t[0] == h) return p(t, d*-1)
  if (t[0] == (h-d > 4 ? 1 : h-d || 4)) return p(t, d)

  return false
}

Tests: https://jsbin.com/cuqicajuko/1/edit?js,console

Saved you 17 bytes: (s,d)=>(h=s[0],t=s.slice(1),g=t[0],!g||(d?g==h?p(t,-d):g%4==(h-d)%4&&p(t,d):p(s,1)||p(s,-1)))

Still not as short as @user81655's answer though.

Turing machine code, 395 bytes
0 1 _ r a
0 2 _ r b
0 3 _ r c
0 4 _ r d
a 1 _ r a
a 2 _ r E
a 3 _ r h
a 4 _ r S
b 1 _ r W
b 2 _ r b
b 3 _ r S
b 4 _ r h
c 1 _ r h
c 2 _ r N
c 3 _ r c
c 4 _ r W
d 1 _ r N
d 2 _ r h
d 3 _ r E
d 4 _ r d
N 1 _ r W
N 2 _ r E
N _ _ r r
N * _ r h
E 2 _ r N
E 3 _ r S
E _ _ r r
E * _ r h
S 3 _ r E
S 4 _ r W
S _ _ r r
S * _ r h
W 4 _ r S
W 1 _ r N
W _ _ r r
W * _ r h
h _ 0 r halt
h * _ r h
r _ 1 r halt

Try it online!
This is basically a state-based approach:

The initial state is 0.
a, b, c, and d are "undecided states" that only occur at the beginning
N, E, S, and W are the "decided states", obviously standing for North, East, South, and West.

Thue, 203 bytes
I can't think of how to golf this farther.
0::=:::
>11::=>1
>22::=>2
>33::=>3
>44::=>4
>12::=b
>21::=d
>14::=c
>41::=a
>23::=c
>32::=a
>34::=d
>43::=b
a1::=d
a2::=b
b2::=a
b3::=c
c3::=b
c4::=d
d4::=c
d1::=a
a<::=~n
b<::=~e
c<::=~s
d<::=~w
::=
>0<

If the note sequence is possible, will output ending direction, otherwise the output will be empty.

Prolog (SWI), 117 bytes
a(N,P):-P=N;N=1,P=4,!;P is N-1.
m([A,B|C],[X,Y|Z]):-a(A,X),a(B,X),a(B,Y),X\=Y,m([B|C],[Y|Z]).
m([_],_).
p(N):-m(N,_).

Defines a predicate p that succeeds on playable inputs (given as a list of integers) and fails on unplayable ones. Try it online!
Explanation
a defines an adjacency relation between note N and crank position P. We define position p to be between notes p and p+1. Thus, a position is adjacent to note N iff

it equals N (P=N); or
the note is 1 and the position is 4 (N=1,P=4); or
the above case is not true (!) and the position equals N-1 (P is N-1).

m takes a list of notes and tries to generate a list of positions that will play those notes. A is the note just played, B is the note about to be played; X is the current crank position, Y is the next crank position. A move is valid iff

the note just played is adjacent to the current crank position (a(A,X));
the note about to be played is also adjacent to the current crank position (a(B,X));
the note about to be played is adjacent to the next crank position (a(B,Y)); and
the two crank positions are not equal (X\=Y).

If all of these hold, recurse. If we successfully get down to any one note (m([_],_)), the sequence of notes is playable.
For this question, we only care whether a sequence of moves exists, so we define p to call m and discard the generated list of crank positions.
See an ungolfed version and verify all test cases here.


text:
Next public holiday
Australians love public holidays, and drinking. Yesterday, the 26th January, was Australia day, which is a public holiday. I was glad to not be at work yesterday, and eager to know the next time I get a public holiday! Unfortunately, I had a bit too much to drink, and I'm not able to work it out for myself.
Write a program that will take a date in Australian date/time notation (dd/mm) as input, and output the amount of days until the next public holiday. Because I'm a Queensland (QLD) resident, I'm only interested in public holidays that affect Queenslanders:

25/03 | Good Friday
  26/03 | Easter Saturday
  28/03 | Easter Monday
  25/04 | Anzac Day
  02/05 | Labour Day
  03/10 | Queen's Birthday
  25/12 | Christmas Day
  26/12 | Boxing Day
  27/12 | Christmas Day holiday

Note the following from the site:

Christmas Day holiday
An additional public holiday to be added when New Year's Day, Christmas Day or Boxing Day falls on a weekend.

Because Christmas day is on Sunday, there is an extra public holiday. Christmas day is still a public holiday.
Because I'm a morning person, you should include the current date as a day (as that's the most likely time I will check your program for the next public holiday). That is, if a public holiday's date is entered, your output should be 0; if the day before a public holiday is entered, your output will be 1.
I'm only interested in dates between now (the 27/01) until the end of the year. The final date you will need to account for is 31/12 where your output will be 1 (for New Year's day).
Standard loopholes are forbidden.
Input

Input will always be 5 characters: 4 letters, separated with a hyphen - or slash /
Input will only be a date between 27/01 and 31/12

Output

The number of days until the next public holiday in Queensland Australia, inclusive of the input date: should be a number between 0 and 153 (the longest gap)
No new lines or errors

Examples
01-05 = 1
02-05 = 0
03-05 = 153
25/12 = 0
26-12 = 0
27/12 = 0
30/12 = 2
31-12 = 1

Hopefully this is clear and nothing is missed; however, this is my second question so I will appreciate any feedback and do my best to fix problems ASAP.

@insertusernamehere Thanks for the great suggestion! I've added the dates in to the question

@Tas are you sure those dates are correct? The ones in the examples don't match the quote and both of them don't match the website.

@AdamMartin Thanks for pointing that out. I had incorrectly put in the December dates. The ones in the example are just any dates, not specific to public holidays. They are just examples of dates that could be entered, and what the output should be. The quoted ones should (and hopefully do) match the ones from the website.

You celebrate the Queen's birthday in October in Queensland? That is so weird, but seems correct from the link.

Wow, you guys don't have any holidays from June straight through September? That's rough.

@Tas Based on the chat in the comments in [this answer] (http://codegolf.stackexchange.com/a/70294/49110) you probably should clarify the seperator-topic in your question. It is not clear if we have to deal with both possible seperators or just one.

Pyth, 98 84 62 67 Bytes
Update: Saved 14 Bytes by shortening the list of the day count for all 12 months for the day number calculation. Haven't found a good way to compress the other list tho, still trying!
Update2: Saved another 22 bytes by endcoding the list of the day-numbers as a base256 string.
J30KhJ=Yc:z"\W"dd=N+s<[KtJKJKJKKJKJK)tseYshY-hfgTNCMc"UVXt{ĕŨũŪů"1N

Try it online!
Same algorithm as in my Python answer. And no builtin to get the day of the year, so I had to do it myself. Creating those 2 lists for the day-of-the-year calculation and for the days of the holidays is quite costly...gonna have a look at it again and try to generate them in fewer bytes.

It doesn't seem to like input separated with a hyphen, but otherwise is great

@Tas Thanks for the hint, completly overread that part...Fixed it at the cost of 5 more bytes. Maybe you should add some hyphens to the testcases, since you want them to cover every possible input variation.

JavaScript (ES6), 131 128 bytes
d=>[56,57,59,87,94,248,331,332,333,338].map(n=>r=r||(q=1454e9+n*864e5-new Date(d[3]+d[4]+`/${d[0]+d[1]}/16`))>=0&&q/864e5,r=0)|r

Explanation
Uses the JavaScript built-in Date constructor to convert the input string into a number of milliseconds since epoch, then compares this with the number of milliseconds for each public holiday.
It does this by storing the public holidays in an array as the number of days since a reference date. I chose 2016-01-29 for the reference date because the number of milliseconds since epoch can be condensed the shortest for this date. Any number of milliseconds between this day and the next works because the result is rounded down, and keeping the number in the middle avoids daylight saving effects (although the OP's timezone does not have daylight savings). The number of this day is 1453986000000 and rounding it up to 1454000000000 (adding a couple of hours) means it can be written as 1454e9.
d=>
  [56,57,59,87,94,248,331,332,333,338]             // list of day offsets from 01/29
  .map(n=>                                         // for each public holiday offset n
    r=r||                                          // if r is already set, do nothing
      (q=                                          // q = approximate difference in ms
        1454e9+n*864e5                             // time of public holiday
        -new Date(d[3]+d[4]+`/${d[0]+d[1]}/16`)    // time of input date
      )
      >=0&&                                        // if q >= 0
        q/864e5,                                   // r = q in days
    r=0                                            // r = result
  )
  |r                                               // floor and return r

Test
This solution is dependent on the user's timezone. This works in the OP's (and my) time zone (GMT +1000). If you want to test it in a different time zone, adding numberOfHoursDifferentFromGMT1000 * 60 * 60 * 1000 to the reference date number should work. (eg. GMT +0430 would be -5.5 * 60 * 60 * 1000 + 1454e9+n*864e5)

var solution = d=>[56,57,59,87,94,248,331,332,333,338].map(n=>r=r||(q=1454e9+n*864e5-new Date(d[3]+d[4]+`/${d[0]+d[1]}/16`))>=0&&q/864e5,r=0)|r
<input type="text" id="input" value="03/05" />
<button onclick="result.textContent=solution(input.value)">Go</button>

This gives always 0 when the date is seperated by a hyphen. I already asked the OP to adjust his testcases, since they are all with a slash as seperator.

@DenkerAffe Oh, I thought he meant we were free to choose a separator. Incidentally, making it separator-ambivalent saved me 3 bytes, so thanks!

Seems like the rule separated with a hyphen - or slash / is a bit ambigious. For me it means that we have to deal with both, but I can definetly see your side. Guess the OP should clarify this.

Visual Basic for Applications, 155 or 118 bytes
Version 1 - locale-independent, 155 bytes
Function h(d)
For i=0To 9
h=Array(0,1,3,31,38,192,275,276,277,282)(i)+42454-DateSerial(16,Val(Right(d,2)),Val(Left(d,2)))
If h>=0Goto 9
Next
9 End Function

Version 2 - locale-dependent, 118 bytes
Function h(d)
For i=0To 9
h=Array(0,1,3,31,38,192,275,276,277,282)(i)+42454-CDate(d)
If h>=0Goto 9
Next
9 End Function

Byte count is for final .BAS file, including linefeed characters. Edited outside standard VBA editor (as it imposes additional spaces and verbose forms of some keywords) - but imports and runs smoothly on any Office Application (to test type e.g. ? h("10/08") in immediate window, or in Excel use directly in a cell formula).
(EDITED) Initially I chose to use DateSerial to make the function locale-safe (version 1). As I live in Brazil and thus my system is configured to use "dd/mm/yy" format for dates (just like Australia) I could write a even smaller version by using CDate instead (version 2). CDate uses system locale information to convert text into date. I also assumed in this version that the code would only be run during 2016 (if year is omitted (-6 bytes) CDate assumes current year as per system clock).
The number 42454 on third line is  the sum of 42450 that is the numeric representation of 01/01/2016 on VBA, and 84 that is the day-of-the-year for the first holiday. The Array contains day-of-the-year for each holiday (including 01/01/2017) offset by -84 as this takes some digits away. Using 16 instead of 2016 on DateSerial takes away two more bytes.
Creating an identical array nine times inside the iteration is "bad" code, but works and saves 3 more bytes (one for array name and one for equal sign outside loop, and one more to reference the array inside the loop).
The "missing" spaces between 0 and the following keyword on second and fourth lines are not necessary as they are reintroduced automatically by VBE when the module is imported. Used outdated but byte-cheap If <...> Goto <linenumber> to break from loop (both If <...> Then Exit For and If <...> Then Exit Function use more characters).
Also took advantage of the fact that the function name in VBA behaves as a local variable, and its value is automaticaly returned by the function in the end of execution.

Welcome to PPCG! Here we define a programming language by the interpreter, so it's perfectly acceptable to require a certain locale.

Thanks! Edited to add a smaller locale-dependent version.

T-SQL, 210, 206, 194 Bytes
(First post here, Hope this is ok, but please be nice :)
Input goes into @i, caters for both / and - as the separator. I'm in Australia, so my date format is the same as @Tas
DECLARE @i CHAR(5)='23-09';DECLARE @c INT=DATEPART(dy,CAST(REPLACE(@i,'-','/')+'/2016' AS DATE))-1;SELECT MIN(b)-@c FROM(VALUES(84),(85),(87),(115),(122),(276),(359),(360),(361))a(b)WHERE b>=@c;

Update varchar to char saves 3 bytes plus removed a space :)
Update 2 declare @c and assign without a select

T-SQL, 296 bytes
Created as a table valued function
create function d(@ char(5))returns table return select min(o)o from(select datediff(day,cast('2016'+right(@,2)+left(@,2)as date),cast(right('2016'+right('0'+cast(d as varchar(4)),4),8)as datetime)+1)o from(values(324),(325),(327),(424),(501),(1002),(1224),(1225),(1226),(1231))d(d))d where 0<=o

Used in the following manner
SELECT *
FROM (
    VALUES
        ('01/05') --= 1
        ,('02/05') --= 0
        ,('03/05') --= 153
        ,('25/12') --= 0
        ,('26/12') --= 0
        ,('27/12') --= 0
        ,('30/12') --= 2
        ,('31/12') --= 1
    )testData(i)
    CROSS APPLY (
        SELECT * FROM d(t)
    ) out

i     o
----- -----------
01/05 1
02/05 0
03/05 153
25/12 0
26/12 0
27/12 0
30/12 2
31/12 1

(8 row(s) affected)

A brief explanation
create function d(@ char(5)) returns table  -- function definition
return
select min(o)o -- minimum set value
from(
    select datediff( -- date difference
        day, -- day units
        cast('2016'+right(@,2)+left(@,2)as date), -- convert input parameter to date
        cast(right('2016'+right('0'+cast(d as varchar(4)),4),8)as datetime)+1 -- convert int values into datetimes and add a day
        )o
    from(
        values(324),(325),(327),(424),(501),(1002),(1224),(1225),(1226),(1231) -- integers representing the day before public holidays
        )d(d)
    )d
where 0<=o -- only for values >= 0

Python 2, 204 185 165 166 Bytes
Update: Golfed it down by ~20 Bytes by calculating the day of the year by myself. No need for the long imports anymore :)
Update 2: Another 20 Bytes down by realizing that I can treat new years just as day 367 and making some other small adjustments.
def f(d):d=[d[:2],d[3:]];y=sum([31,29,31,30,31,30,31,31,30,31,30,31][:int(d[1])-1])+int(d[0]);return filter(lambda n:n>=y,[85,86,88,116,123,277,360,361,362,367])[0]-y

Try it online!
Ungolfed:
def f(d):
    l=[85,86,88,116,123,277,360,361,362,367]
    d=[d[:2],d[3:]]
    y=sum([31,29,31,30,31,30,31,31,30,31,30,31][:int(d[1])-1])+int(d[0])
    f=filter(lambda n:n>=y,l)
    return f[0]-y

Works by storing the day-of-the-year number of the holidays in a list, filtering out the ones which are before the given date, taking the first element in that filtered list and subtracting the day-of-the-year, which got calculated from the input.

JavaScript (ES6), 134 bytes
x=>[0,1,3,31,38,192,275,276,277,282].find(z=>z>=(q=x[0]+x[1]- -[...'20212122121'].slice(0,x[3]+x[4]-1).reduce((a,b)=>+b+a+29,0)-85))-q

user81655 still has me beat by 3 bytes, but I can't find anywhere else to squeeze anything out of here. Works by calculating the number of days gone by instead of using Date, then comparing it to an array of holiday offsets.

ruby 1.9.3, 155 153 bytes
After Christmas Day holiday, we need our super-special-day 366! Similar case as @DenkerAffe.
require'date'
c=(Date.strptime(ARGV[0],'%d/%m')-Date.parse('01/01')).to_i
print [84,85,87,115,122,276,359,360,361,366].map{|i|(i-c)}.select{|i|i>=0}.min

Usage:
$ ruby i_want_to_break_free.rb "03/05"

I don't know much about Ruby, but I think you can save 3 Bytes by removing whitespaces in line 1 and 3. Also you should specify which input method you are using, since it is not that obvious in your code. You might save some Bytes by defining a function, so you can take the input as argumen and use the return value as output.

@DenkerAffe Thank you very much! I've saved 2 bytes, but I think a function will increase the number. I've updated the answer with a usage example.

PHP, 116 bytes
Pretty straight forward approach. It stores the days of the year for the holidays and pops them as long as they are in the past. Finally the requested day of the year is subtracted.
for($x=[366,361,360,359,276,122,115,87,85,84];($a=date(z,strtotime($argv[1].'-2016')))>$t=array_pop($x););echo$t-$a;

Past all test cases. Runs from command line and accepts the input using a hyphen, like:
$ php holidays.php "12-05"

05AB1E, 45 bytes
•9JRt€ª´Q®Ië•368вDI„-/S¡`•Σ₁t•ºS₂+s<£O+©@Ïн®-

It may not be 2016 anymore, but whatever.. ;) Still assumes the year is 2016 for the sake of being a leap year with 29 for February.
Try it online or verify all test cases.
Explanation:
•9JRt€ª´Q®Ië•  # Push compressed integer 10549819042671399072072399
  368в         # Converted to base-368 as list: [85,86,88,116,123,277,360,361,362,367]
      D        # Duplicate this list
I              # Take the input
 „-/S¡         # Split it on ["-","/"]
      `        # Push both integer separated to the stack
•Σ₁t•          # Push compressed integer 5354545
     º         # Mirror it without overlap: 53545455454535
      S        # Converted to a list of digits: [5,3,5,4,5,4,5,5,4,5,4,5,3,5]
       ₂+      # Add 26 to each: [31,29,31,30,31,30,31,31,30,31,30,31,29,31]
         s     # Swap to get the month-integer
          <    # Decrease it by 1
           £   # Only leave the first month-1 values from the integer-list
            O  # Sum that sublist
             + # And add it to the day-integer (so we now have the N'th day of the year)
©              # Save this in the register (without popping)
 @             # Do a >= check with each integer in the first (duplicated) list we created
  Ï            # Only leave the truthy values from the list
   н           # Then pop this sublist and only leave its first value
    ®-         # And subtract the integer we saved in the register (N'th day of the year)
               # (after which the result is output implicitly)

See this 05AB1E tip of mine (sections How to compress large integers? and How to compress integer lists?) to understand why •9JRt€ª´Q®Ië• is 10549819042671399072072399; •9JRt€ª´Q®Ië•368в is [85,86,88,116,123,277,360,361,362,367]; and •Σ₁t• is 5354545.


text:
Print The Formula
Introduction
In chemistry there is a type of extension, .xyz extension,(https://en.wikipedia.org/wiki/XYZ_file_format), that prints in each line
a chemical element, and the coordinates in the plane of the element. This is very useful for chemists to understand chemical compounds and to visualize the compounds in 3D. I thought it would be fun to, given a .xyz file, print the chemical formula.
Challenge
Given an .xyz file, print the chemical formula of the compound in any programming language in the smallest possible number of bytes. Note:

Originally, the input was to be given as a file. As I have been pointed out, this constraints the challenge. Therefore you may assume the input is a list/array of strings, each representing a line of the .xyz file.
There are no restrictions in the ordering of the elements.
Each element should be printed with an underscore "_" delimiting the element and the number of times it appears
The first two lines of any .xyz file is the number of elements, and a comment line (keep that in mind).

Example Input and Output
Suppose you have a file p.xyz which contains the following (where the first line is the number of elements, and the second a comment), input:
5
A mystery chemical formula...
Ba      0.000   0.000  0.000
Hf      0.5     0.5    0.5
O       0.5     0.5    0.000
O       0.5     0.000  0.5
O       0.000   0.5    0.5

Output:
  Ba_1Hf_1O_3

Testing
A quick test is with the example mentioned. A more thorough test is the following:
since the test file is thousands of lines, I'll share the .xyz file:
https://gist.github.com/nachonavarro/1e95cb8bbbc644af3c44

Requiring input to be read from a file unnecessarily and unfairly prohibits a very significant portion of programming languages from participating in your challenge. See: http://meta.codegolf.stackexchange.com/a/8077/3808, http://meta.codegolf.stackexchange.com/q/2447/3808

@Doorknob Good point. I've changed that.

Code golf, code challenge, and fastest code are mutually-exclusive tags. The score should be in bytes, not characters. The file format should be completely described in the question, instead of requiring outside resources. Use a GitHub Gist instead of an untrusted file hosting service. Because of these issues, I'm voting to close as unclear. Please use the Sandbox in the future.

@Mego how about now? :)

@nacho There are still many issues with it. You should probably delete this question, post it in the Sandbox, and then post it to main after getting feedback and fixing issues that others point out.

what is the answer for the large test case?

Does ordering matter in the output?

Pyth - 18 bytes
sjL\__MrShMcR;ttQ8

Try it online here.

Japt, 21 bytes
U=¢m¸mg)â £X+'_+Uè_¥X

Test it online! Input is given as an array of strings (which can be formatted as in the link).
Ungolfed and explanation
U=¢   m¸  mg)â £    X+'_+Uè_  ¥ X
U=Us2 mqS mg)â mXYZ{X+'_+UèZ{Z==X

          // Implicit: U = input array of strings
Us2       // Slice off the first two items of U.
mqS mg    // Map each item by splitting at spaces, then taking the first item.
U=    )   // Set U to the result.
â mXYZ{   // Uniquify, then map each item X to:
UèZ{Z==X  //  Count the number of items Z in U where Z == X.
X+'_+     //  Prepend X and an underscore.
          // Implicit output

AWK, 44
NR>2{a[$1]++}END{for(i in a)printf i"_"a[i]}

Try it online.

Shell + GNU Utilities, 67
sed '1d;2d;s/ .*//'|sort|uniq -c|sed -Ez 's/\s*(\S+) (\S+)/\2_\1/g'

Try it online.

1d;2d → 1,2d

Just because trailing spaces in the output are not forbidden: tail -n+3|cut -c-3|sort|uniq -c|sed -rz 's/\s*(\S+) (\S+)/\2_\1/g'

Mathematica, 79 53 bytes
StringRiffle[Tally@StringExtract[#[[3;;]],1],"","_"]&

Quite simple.