text:
Sort band names
Challenge description
You have a music library with many tracks recorded by many bands, each of which has a name, like Queen, Aerosmith, Sunny Day Real Estate, The Strokes . When an audio player displays your library alphabetically by band name, it usually skips the The part, as many band names start with The, making it easier to navigate through your media collection. In this challenge, given a list (array) of strings, you need to sort it that way (that is, omitting the The word at the beginning of the name). You can either write a method or a full working program.
Sample inputs / outputs
[Queen, Aerosmith, Sunny Day Real Estate, The Strokes] -> [Aerosmith, Queen, The Strokes, Sunny Day Real Estate]
[The Ramones, The Cure, The Pixies, The Roots, The Animals, Enrique Iglesias] -> [The Animals, The Cure, Enrique Iglesias, The Pixies, The Ramones, The Roots]
[The The, The They, Thermodynamics] -> [The The, Thermodynamics, The They]

Notes / Edge cases

Sorting lexicographically is case insensitive, so The Police, The police and the police are all equivalent,
Your algorithm should only omit the first the word, so bands named The The or The The Band are sorted normally by the second the,
A band named The (a three letter word) is sorted normally (no skipping),
Order of two bands having the same name, one of which starts with the (like The Police and Police) is undefined,
You can assume that if a band's name consists of more than one word, they are separated by a single space character. You don't need to handle leading or trailing whitespaces,
All input strings match [A-Za-z0-9 ]*, that is they will consist only of lower- and uppercase letters of English alphabet, digits and space characters,
Remember that this is a code-golf challenge, so make your code as short as possible!

Do numeral-only names come before or after alphabetical?

Numeral-only strings come first

What is the sort order of The and The The? ( Most answers would probably need to change if it is anything other than undefined )

how about Los Lobos?

The The is a real band by the way. (along with The Who, The What, The Where, The When, The Why, and The How)

If the input had a lowercase the but output an uppercase The, would this be acceptable?

Similar to the "the" / "the the" case, What is the sorting order of "red blues" and "the red blues"?

@BradGilbertb2gills: They are the same in this case, so the order is undefined

@njzk2: It's sorted by "Los", since it doesn't start with "the"

@DrGreenEggsandIronMan: Sure

@JanDvorak: Same as "The" and "The The" case, they are treated the same way lexicographically, so the order is undefined.

the pAper chAse is a good edge test case

Probably want an example that actually uses lowercase letters.

Python, 56 62 64 bytes
lambda b:sorted(b,key=lambda x:(x,x[4:])[x.lower()[:4]=='the '])

Try it
Thanks to @Chris H for pointing out that lstrip() was not handling The The correctly, since the strip was blasting all matching characters and sorting it as a blank string, and @manatwork for finding the flaw in using replace(). The new version should work.
Old version:
lambda b:sorted(b,key=lambda x:x.lower().lstrip('the '))

I'm not convinced.  Adding "The animals" to the last list gives ['The The', 'The', 'The Animals', 'Thermodynamics', 'The They'].  The 2nd edge case suggest sit should be ['The Animals', 'The The', 'The', 'Thermodynamics', 'The They'] (or swap the 2nd and 3rd items).  A little fiddling suggests the space inside strip('the ') is being ignored - try for x in ['The The', 'The They', 'Thermodynamics', 'The', 'The Animals']: print (x.lower().strip('the '))

That replace() is not much better: 'what the snake'.replace('the ','',1) results 'what snake'.

V, 32 28 bytes
ç^The /dwA_
:sort
ç_/$xIThe

Try it online!
Note to self: Make an abbreviation for :sort so that I don't need 6 whole bytes for a single command!
Explanation:
ç^The /     "On every line starting with 'The ',
       dw   "Delete a word
         A_ "And (A)ppend an underscore '_'

:sort       "Sort all lines alphabetically

ç_/         "On every line containing an underscore,
   $x       "Delete the last character
     IThe   "And prepened 'The '

Not familiar with V, but it seems this one works fine without the asterisks. Is this coincidence with the input, or actually unneeded?

@kirkpatt Good idea! That almost works, but not quite. For example, with this input it incorrectly puts "Radiohead" after "The Ramones" and "The Roots". However, that gives me an idea...

What happens if the is in all lowercase, like the pAper chAse?

Retina, 34 bytes
The trailing linefeed is significant.
%`^
$';
T`L`l`.+;
m`^the

O`
.+;

I/O is one band per line.
Try it online!
Explanation
%`^
$';

Duplicate each line, using ; as a separator.
T`L`l`.+;

Turn everything in front of a ; to lower case.
m`^the

Remove any thes that appear at the beginning of a line.
O`

Sort the lines.
.+;

Remove the beginnings of the lines which we used for sorting.

Couldn't you pack the first 3 Steps into a single step? Like in PCRE: s/(?i:the )?(.*)/\L$1\E;$0/

@Falco .NET doesn't support case changes in substitution strings and I haven't yet added them to Retina's custom replacer either.

Pyke, 16 bytes
.#l1D"the ".^4*>

Try it here!
.#                - sort_by(V, input)
  l1              -  i = i.lower()
      "the ".^    -   i.startswith("the ")
              I   -  if ^:
               4> -   i[4:]

Perl, 52 bytes
-13 byte thanks to @manatwork
-1  byte thanks to @msh210
sub f{lc pop=~s/^the //ri}print sort{f($a)cmp f$b}<>

One band per line as input, and so is the output.
The implementation is quite straight forward : the program prints the list of bands, sorted with the help of a custom function (f) which returns the lower case band name without the eventual leading the .

Is shorter with substitution instead of matching: sub f{lc$_[0]=~s/^the //ir}.

1 byte shorter indeed, thanks.

Actually I counted either 2 or 3 bytes shorter: no need for both the parenthesis around lc's parameter and the i flag in substitution. Or have you met a test case where that not works?

Thinking again, the amount of command line options could also be reduced if you take each band name on separate line: perl -e 'sub f{lc$_[0]=~s/^the //ri}print sort{f($a)cmp f$b}<>' <<< $'Queen\nAerosmith\nSunny Day Real Estate\nThe Strokes'.

Oh right, I added the parenthesis because =~ as a higher precedence than lc. But the lc is done after the regex so it's ok. But then the i flag is needed if I'm not mistaken. Great idea taking the bands name on separated lines.

Save three bytes: lc pop instead of lc$_[0], and say instead of print. (The latter requires -M5.01, which is free.) Tested in Strawberry 5.20.2 with only the first test case from the question.

Right about the pop, thanks. About the say I thought of it, but it adds a trailing empty line, so I didn't want to use it...

Python, 66 72 69 bytes
lambda x:sorted(x,key=lambda a:a[4*(a.lower()[:4]=='the '):].lower())

Uses Python's sorted method with the key keyword argument to sort by the name minus "The". This is a lambda; to call it, give it a name by putting f= in front.
Now with extra case insensitivity!

It doesn't meet the case insensitivity requirement, though... A band name can start with the , in which case this method won't work properly.

@shooqie Oh, I didn't see that requirement. I'll fix it.

PowerShell v2+, 33 32 29 bytes
$args|sort{$_-replace'^the '}

Saved 3 bytes thanks to @MathiasRJessen
Input is via command-line arguments. Sorts the original names based on the results of the script block {...} that performs a regex -replace to strip out the leading (case-insensitive) "the ".
Examples
PS C:\Tools\Scripts\golfing> .\sort-band-names.ps1 'the Ramones' 'The cure' 'The Pixies' 'The Roots' 'the Animals' 'Enrique Iglesias'
the Animals
The cure
Enrique Iglesias
The Pixies
the Ramones
The Roots

PS C:\Tools\Scripts\golfing> .\sort-band-names.ps1 'The The' 'The They' 'Thermodynamics'
The The
Thermodynamics
The They

PS C:\Tools\Scripts\golfing> .\sort-band-names.ps1 'THE STOOGES' 'The Strokes' 'The The' 'the they' 'the band' 'STP'
the band
THE STOOGES
STP
The Strokes
The The
the they

-replace is case-insensitive by default, '^the ' will suffice for the pattern

@MathiasR.Jessen Yes, thanks for the reminder.

@ValueInk See Mathias' comment about case insensitivity and the final example I added.

JavaScript/ECMAScript 6 93 70 bytes
70 Thanks to Neil and Downgoat for advice
B=>B.sort((a,b)=>R(a).localeCompare(R(b)),R=s=>s.replace(/^the /i,''))

Readable Version for the 70-byte variant
let sortBandNames = (bandNames) => {
    let stripThe = (name) => name.replace(/^the /i, '');
    let compareFunc = (a, b) => stripThe(a).localeCompare(stripThe(b));
    return bandNames.sort(compareFunc)
};

93
f=B=>{R=s=>s.toLowerCase().replace(/the /,'');return B.sort((a,b)=>R(a).localeCompare(R(b)))}

Readable Version for the 93-byte variant
let sortBandNames = (bandNames) => {
    let stripThe = (name) => name.toLowerCase().replace(/the /, '');
    let compareFunc = (a, b) => stripThe(a).localeCompare(stripThe(b));
    return bandNames.sort(compareFunc)
};

Shouldn't that regexp have a ^ in it? Also, localeCompare is case insensitive on my system, so I didn't need the toLowerCase, just an /i flag on the regexp. Finally you can golf this as follows: B=>B.sort((a,b)=>...,R=s=>...) - sort ignores the extra parameter that sets R.

Where in the regex would ^ go? That would be a negation and the the expression is supposed to match and erase "the ". I'll try using locale compare without the lower-case conversion.

@Pandacoder the ^ shuold go at the beginning of the regex

@Downgoat From testing all of the given cases, and a few cases I came up with specifically intending to break the RegEx, with or without the ^ I get no change in behavior, only an extra character that doesn't accomplish anything.

@Pandacoder that doesn't make it valid. the ^ is an anchor which requires the "the" to be at the beginning per the spec

Ah, I see what you mean. Didn't think of sticking "The" in the middle.

Updated to include that caret.

You can remove the f= as it's ok to return an anonymous function. Also you may be able to save some bytes by mapping to lowercase&replacing the the and use .sort() which is lexicographic by default

@Downgoat What do you mean by mapping to lowercase (just to make sure, you're looking at the 72/70-byte variant, not the 93/91-byte one)?

I meant a=>a.map(i=>i.toLowerCase().replace(/^the /,'')).sort(); but just relized why that doesn't work you can still remove f= and make it just B=>B.sort((a,b)=>R(a).localeCompare(R(b)),R=s=>s.replace(/^the /i,'')) to save 2 bytes

I feel like there is a way to use map, just as part of the comparator function, but I don't know how to get the lexicographical difference of a two-string array easily. I'll strip the f= though.

Ruby, 42 bytes
->a{a.sort_by{|s|s.upcase.sub /^THE /,''}}

Try it online!

Perl 6, 26 bytes
*.sort({fc S:i/^'the '//})

Explanation:
# ｢*｣ is the input to this Whatever lambda
*.sort(

  # sort based on the return value of this Block lambda
  {
    fc # foldcase the following

    # string replace but not in-place
    S
      :ignorecase
      /
        # at the start of the string
        ^

        # match ｢the ｣
        'the '

      # replace with nothing
      //
  }
)

Test:
use v6.c;
use Test;

my @tests = (
  « Queen Aerosmith 'Sunny Day Real Estate' 'The Strokes' »
    => « Aerosmith Queen 'The Strokes' 'Sunny Day Real Estate' »,
  « 'The Ramones' 'The Cure' 'The Pixies' 'The Roots' 'The Animals' 'Enrique Iglesias' »
    => « 'The Animals' 'The Cure' 'Enrique Iglesias' 'The Pixies' 'The Ramones' 'The Roots' »,
  « 'The The' 'The They' Thermodynamics »
    => « 'The The' Thermodynamics 'The They' »,
);

# give it a lexical name for clarity
my &band-sort = *.sort({fc S:i/^'the '//});

plan +@tests;

for @tests -> ( :key(@input), :value(@expected) ) {
  is-deeply band-sort(@input), @expected, @expected.perl;
}

1..3
ok 1 - ("Aerosmith", "Queen", "The Strokes", "Sunny Day Real Estate")
ok 2 - ("The Animals", "The Cure", "Enrique Iglesias", "The Pixies", "The Ramones", "The Roots")
ok 3 - ("The The", "Thermodynamics", "The They")

Java 8, 178 bytes
void q(String[]s){java.util.Arrays.sort(s,(a,b)->(a.toLowerCase().startsWith("the ")?a.substring(4):a).compareToIgnoreCase(b.toLowerCase().startsWith("the ")?b.substring(4):b));}

Ungolfed version:
void sort(String[] bands) {
    java.util.Arrays.sort(bands, (a, b) ->
        (a.toLowerCase().startsWith("the ") ? a.substring(4) : a).compareToIgnoreCase(
            b.toLowerCase().startsWith("the ") ? b.substring(4) : b
        )
    );
}

Call as such:
public static void main(String[] args) {
    String[] bands = {"The Strokes", "Queen", "AC/DC", "The Band", "Cage the Elephant", "cage the elephant"};
    sort(bands); // or q(bands) in the golfed version
    System.out.println(java.util.Arrays.toString(bands));
}

I know you've answered this almost a year ago, but you can golf a few things. Since you state you use Java 8, you can change void q(String[]s){...} to s->{...}. And you can change both (x.toLowerCase().startsWith("the ")?x.substring(4):x) with x.replaceFirst("(?i)the ",""). So the total becomes: s->{java.util.Arrays.sort(s,(a,b)->a.replaceFirst("(?i)the ","").compareToIgnoreCase(b.replaceFirst("(?i)the ","")));} - 118 bytes

Neat trick with the replaceFirst. When I answered this I had been told a few times on other answers that s->{ ... } wasn't allowed and I had to have a full method signature with types and whatnot. I don't know if that's changed since then.

Not sure about back then, but these days it's allowed and used by close to everyone golfing in Java or C# .NET.

Bash + coreutils, 44 bytes
sed '/^the /I!s,^,@ ,'|sort -dk2|sed s,@\ ,,

Explanation: the input and output format is one band per line
sed '/^the /I!s,^,@ ,'   # prepend '@ ' to each line not starting with 'the ', case
                         #insensitive. This adds a temporary field needed by sort.
sort -dk2                # sort in ascending dictionary order by 2nd field onward
sed s,@\ ,,              # remove the temporary field

Test run (using a here-document with EOF as the end marker):
./sort_bands.sh << EOF
> Queen
> Aerosmith
> Sunny Day Real Estate
> The Strokes
> EOF

Output:
Aerosmith
Queen
The Strokes
Sunny Day Real Estate

Vim, 18 bytes
Well now that I realized this is possible, I'm kinda embarrassed by my 26 byte V answer, especially since V is supposed to be shorter than vim. But this is pretty much a builtin.
:sor i/\(The \)*/<CR>

Explanation (straight from vim help):
                            *:sor* *:sort*
:[range]sor[t][!] [b][f][i][n][o][r][u][x] [/{pattern}/]
            Sort lines in [range].  When no range is given all
            lines are sorted.

            With [i] case is ignored.

            When /{pattern}/ is specified and there is no [r] flag
            the text matched with {pattern} is skipped, so that
            you sort on what comes after the match.
            Instead of the slash any non-letter can be used.

C, 216 212 135 + 5 (qsort) = 221 217 140 bytes
M(void*a,void*b){char*A,*B;A=*(char**)a;B=*(char**)b;A=strcasestr(A,"The ")?A+4:A;B=strcasestr(B,"The ")?B+4:B;return strcasecmp(A,B);}

Well, I finally got around to finishing this in C. Golfing tips are very much appreciated.
In this submission, M is the comparison function to be supplied to qsort. Therefore, to invoke this, you must use qsort in the format qsort(argv++,argc--,8,M) where argv contains the command-line arguments and argc is the number of arguments provided.
Try It Online!

115 bytes

Nim, 96 bytes
import algorithm,strutils,future
x=>x.sortedByIt toLower it[4*int(it.toLower[0..3]=="the ")..^0]

Those imports take up so many bytes :|
A translation of my Python answer.
This is an anonymous procedure; to use it, it must be passed into a testing procedure. Here's a full program you can use for testing:
import algorithm,strutils,future
proc test(x: seq[string] -> seq[string]) =
 echo x(@["The The", "The They", "Thermodynamics"]) # Substitute your input here
test(x=>x.sortedByIt toLower it[4*int(it.toLower[0..3]=="the ")..^0])

MATL, 16 bytes
tk'^the '[]YX2$S

Input format is (each line corresponds to a test case)
{'Queen', 'Aerosmith', 'Sunny Day Real Estate', 'The Strokes'}
{'The Ramones', 'The Cure', 'The Pixies', 'The Roots', 'The Animals', 'Enrique Iglesias'}
{'The The', 'The They', 'Thermodynamics'}

Try it online!
Explanation
t        % Implicitly input cell array of strings. Push another copy
k        % Convert to lowercase
'^the '  % String to be used as regex pattern: matches initial 'the '
[]       % Empty array
YX       % Regex replacement: replace initial 'the ' in each string by empty array
2$S      % Sort input according to the modified cell array. Implicitly display

Haskell, 84 bytes
import Data.List
p(t:'h':'e':' ':s)|elem t"Tt"=s
p s=s
sortBy(\a b->p a`compare`p b)

Call with
sortBy(\a b->p a`compare`p b)["The The", "The They", "Thermodynamics"]

Testcase:
let s = sortBy(\a b->p a`compare`p b)
and[s["Queen", "Aerosmith", "Sunny Day Real Estate", "The Strokes"]==["Aerosmith", "Queen", "The Strokes", "Sunny Day Real Estate"],s["The Ramones", "The Cure", "The Pixies", "The Roots", "The Animals", "Enrique Iglesias"]==["The Animals", "The Cure", "Enrique Iglesias", "The Pixies", "The Ramones", "The Roots"],s["The The", "The They", "Thermodynamics"]==["The The", "Thermodynamics", "The They"]]

C#, 139 Bytes
using System.Linq;System.Collections.IEnumerable S(string[] l)=> l.OrderBy(b=>(b.ToLower().StartsWith("the ")?b.Substring(4):b).ToLower());

Try online!
Without counting the usings the answer would be 102 bytes.

I believe you can ignore the final ToLower() due to the case-insensitive requirement

Also you can make it an anonymous function which should save some bytes:

l=>l.OrderBy(b=>(b.ToLower().StartsWith("the ")?b.Substring(4):b)); For 67 bytes and then you need to add on the using System.Linq; too

@TheLethalCoder: I need the second ToLower because of the case-insensitive requirement. Otherwise the order would be case-sensitive.

Okay the point about converting it to an anonymous function still stands though

BASH, 64 Bytes
sed 's/^the / /;s/^The /    /'|sort -fb|sed 's/^ /the /;s/^ /The /'

Input: stdin, one band per line.
Output: stdout
Note: The second replacements (s/^The/  / and s/^   /The /) use the tab character, so they don't always copy/paste correctly.

q/kdb+, 36 33 bytes
Solution:
{x(<)@[x;(&)x like"[Tt]he *";4_]}

Example:
q){x(<)@[x;(&)x like"[Tt]he *";4_]}("Queen";"Aerosmith";"Sunny Day Real Estate";"The Strokes";"the Eagles")
"Aerosmith"
"the Eagles"
"Queen"
"The Strokes"
"Sunny Day Real Estate"

Explanation:
Strip out any "[Tt]he " from each input string, sort this list, then sort the original list based on the indexing of the sorted list.
{x iasc @[x;where x like "[Tt]he *";4_]} / ungolfed solution
{                                      } / lambda function
        @[x;                       ;  ]  / apply function to x at indices
                                    4_   / 4 drop, remove first 4 items
            where x like "[Tt]he *"      / where the input matches 'The ...' or 'the ...'
   iasc                                  / returns sorted indices
 x                                       / index into original list at these indices

05AB1E, 27 bytes
vyð¡RD¤…TheQsgα£Rðý})‚øí{ø¤

Try it online!
Explanation
vyð¡RD¤…TheQsgα£Rðý})‚øí{ø¤   Argument l
v                 }           For each y in l, do:
 yð¡                            Split y on space
    RD                          Reverse and duplicate
      ¤…TheQ                    Last element equals "The" (true = 1, false = 0)
            sgα                 Absolute difference with length of array
               £                Get elements from index 0 to calculated difference
                R               Reverse
                 ðý             Join on space
                    )‚øí      Pair each element with original
                        {ø¤   Sort and get the original band name

Groovy, 34 bytes
{it.sort{it.toLowerCase()-'the '}}

41% my answer is .toLowerCase(), kill me now.

Output
When running...
({it.sort{it.toLowerCase()-'the '}})(['The ramones','The Cure','The Pixies','The Roots','The Animals','Enrique Iglesias'])

The result is...
[The Animals, The Cure, Enrique Iglesias, The Pixies, The ramones, The Roots]
With no debug or error output.

Japt, 11 10 bytes
ñ_v r`^e

Try it

Java 176 158 bytes
public String[]sort(String[]names){
  for(int i=-1;++i<names.length;)
    if(names[i].startsWith("(The |the )"))
      names[i]=names[i].substring(4);
  return Arrays.sort(names,String.CASE_INSENSITIVE_ORDER);
  }

Main Function
public static void main(String[]args){
  Scanner s = new Scanner(System.in);
  List<String> list= new ArrayList<>();
  while(!(String h = s.nextLine).equalsIgnoreCase("~")){
    list.add(h);
  }
System.out.println(sort(list.toArray(newString[0]))

);
    }
Golfed sort function:
String[]s(String[]n){for(int i=-1;++i<n.length;)if(n[i].startsWith("(The |the )"))n[i]=n[i].substring(4);return Arrays.sort(n,String.CASE_INSENSITIVE_ORDER);}

Thanks to @raznagul for saving 18 bytes

Doesn't work if a name starts with the . The sort should be case insensitive.

This won't work at all... Strings are immutable. You want to do public String[]sort(String[]names){   for(int i=-1;++i<names.length;)   names[i]=names[i].replaceFirst("(the|The)", "");   return Arrays.sort(names,String.CASE_INSENSITIVE_ORDER);   } Since the and The should work, and strings a immutable

Fixed that, but find me one band that starts with a small "the "

I'm not very good at Java so I might be wrong. But couldn't .replaceFirst... be replaced with .substring(4) ?

Yes that's right. I thought replace will edit the String but doesn't. So i missed that while editing last time.

Arrays.sort returns type void

@RomanGräf the pAper chAse


text:
Smallest sum (and largest difference) of two 3-digit integers
Given six unique non-negative integers, print the two 3-digit integers comprised of those numbers that sum to the smallest amount.
Additionally,

If there is more than one set of numbers that meets the smallest-sum requirement, print the two that have the greatest difference. For example, 269 + 157 = 267 + 159 = 426; however, 269 - 157 > 267 - 159, so the first set should be printed.
Print the numbers on the same line largest -> smallest, separated by a single space.
Zero (0) cannot be used as a leading number.
Inputs will always be digits.

Testcases
input        | output
2 6 5 1 9 7  | 269 157
1 9 5 0 8 3  | 359 108
1 2 3 4 5 6  | 246 135

Scoring
As this is code golf, shortest entry wins.

Are the inputs always going to be digits? If so, please specify that.

Welcome to Programming Puzzles and Code Golf! This is a nice first challenge, but the output format is a little restrictive. Can that be relaxed to our standards for input/output?

Feel free to edit as necessary. I was basing the question and input/output format on this post but am not married to it (https://codegolf.stackexchange.com/questions/49854/largest-and-smallest-values-from-concatenated-integers?rq=1)

Jelly, 12 bytes
Ṣs3¬Þ€Fs2ZḌṚ

Try it online! or verify all test cases.
Background
Consider six digits a < b < c < d < e < f.
If a ≠ 0, a number pair of three-digit integers with minimal sum must clearly use a and b for the leftmost digits, c and d for the middle digits, and e and f for the rightmost digits.
That gives eight possible arrangements with identical sums (100(a + b) + 10(c + d) + (e + f)).
Since the difference should be as large as possible, all digits of the first integer should be larger than the corresponding digits of the second integer, leaving bdf10, ace10 as the optimal arrangement (difference 100(b - a) + 10(d - c)+ (f - e)).
Finally, if a = 0, a should still occur as early as possible (as middle digit), and a similar process reveals that the pair cdf10, bae10 is the correct solution.
How it works
Ṣs3¬Þ€Fs2ZḌṚ  Main link. Argument: <a, b, c, d, e, f> (in any order)

Ṣ             Sort; yield [a, b, c, d, e, f].
 s3           Split into triplets; yield [[a, b, c], [d, e, f]].
   ¬Þ€        Sort each triplet by logical NOT.
              If a ≠ 0, all digits have logical NOT 0, so this leaves the triplets
              unaltered. If a = 0, its logical NOT is 1, so the first triplet is
              sorted as [b, c, a], leaving [[b, c, a], [d, e, f]].
      F       Flatten; yield [a, b, c, d, e, f] or [b, c, a, d, e, f].
       s2     Split into pairs; yield [[a, b], [c, d], [e, f]] or
              [[b, c], [a, d], [e, f]].
         Z    Zip; yield [[a, c, e], [b, d, f]] or [[b, a, e], [c, d, f]].
          Ḍ   Undecimal; convert each triplet from base 10 to integer.
           Ṛ  Reverse the order of the generated integers.

Pyth, 17 bytes
_iRTChf*FhTcR2.pS

Try it online
How it works
_iRTChf*FhTcR2.pS

                S   sort input
              .p    permutations in lexicographic order
           cR2      chop each permutation into groups of 2
      f             filter for results T such that:
         hT           the first group
       *F             has a truthy (nonzero) product
     h              first result
    C               transpose
 iRT                convert both rows to base 10
_                   reverse

Perl, 88 66 64 66 64 Bytes
@a[0..2]=@a[1,2,0]if!(@a=sort@ARGV)[0];say@a[1,3,5],$",@a[0,2,4]

Prints the two numbers with no space between them :/
Needs -M5.01 flag
Thanks to @msh210 and @Dada for helping to reduce byte count!

Nice. But say@a[1,3,5],@a[0,2,4] is shorter. (It requires -M5.01, which is free according to site rules.)

Thanks! I realized using the indexes was was shorter right after I posted and have corrected now.

You're welcome! And welcome to PPCG.SE. Note also that it's pretty much customary here to express your appreciation, if any, for those who saved you bytes by mentioning them in the post. And note that you can another byte by using 0..2 instead of 0,1,2.

It's -M5.10, and it is only free because you can use the -E flag instead of the -e flag on the command line. (afaik)

@BradGilbertb2gills, no, it's -M5.01 (short for -M5.010).

@msh210 Yeah I usually use -Mv5.10 because leaving off the trailing 0 is confusing, and should never be done

@BradGilbertb2gills, for production, I agree. But this is a golf site. :-D

To add the space between the numbers (as I guess is required by the challenge), you may try say@a[1,3,5],$",@a[0,2,4] for three bytes more. I don't see a shorter way at the moment. And if you're not including the space then you may as well say@a[1,3,5,0,2,4].

Nice answer. You can save 1 byte by replacing @a=sort@ARGV;!$a[0]? with !(@a=sort@ARGV)[0]?

And 1 more by using a statement modifier if instead of your ternary ?: : @a[0..2]=@a[1,2,0]if!(@a=sort@ARGV)[0]

An alternative way to save 1 byte might be to remove the ! and swap the two parts of the ternary?

@Dada Sorry, I didn't know that. (In JavaScript they have the same precedence and are right-associative so that a=b?c=d?e=f either assigns d to c and a or f to e and a depending on the truthiness of b.)

@Neil Sorry I was wrong in my previous message. The reason why this is not possible is easy to understand with the error message : Assignment to both a list and a scalar. The reason is a ? b : c = d is parsed as ( a ? b : c) = d, meaning d will be assign to b or c depending on the thruthiness of a. In that case, b is a scalar 0 and c is an array slice (@a[0..2]), and perl doesn't like that

JavaScript (ES6), 59 bytes
a=>a[b=!!+a.sort()[0],2-b]+a[3]+a[5]+' '+a[1-b]+a[b+b]+a[4]

Takes input as a character array (e.g. [..."195083"]) and returns two space-separated numbers in a string. 57 bytes if I can return the smaller number first:
a=>a[b=+!+a.sort()[0]]+a[2-b-b]+a[4]+' '+a[1+b]+a[3]+a[5]

Batch, 232 bytes
@if %1 gtr %2 %0 %2 %1 %3 %4 %5 %6
@if %2 gtr %3 %0 %1 %3 %2 %4 %5 %6
@if %3 gtr %4 %0 %1 %2 %4 %3 %5 %6
@if %4 gtr %5 %0 %1 %2 %3 %5 %4 %6
@if %5 gtr %6 %0 %1 %2 %3 %4 %6 %5
@if %1==0 (echo %3%4%6 %20%5)else echo %2%4%6 %1%3%5

Mostly bubble sort.

PowerShell v2+, 90 68 bytes
$a,$b=(($n=$args|sort)-ne0)[0,1];"$b{1}{3} $a{0}{2}"-f($n-ne$a-ne$b)

Not quite as short as others, but showcases some nifty tricks.
Takes input as command-line arguments $args, sorts them, saves that into $n. That's encapsulated in parens and used as the left-hand argument to -ne0, which pulls out all elements not equal to zero (in PowerShell, array -comparator scalar functions as a filter). That resultant array is re-captured in parens, and the 0th(Hi Dennis) and 1st elements plucked out, and uses multiple-assignment to store them into $a and $b. This ensures that the smallest non-zero element is in $a and the next smallest non-zero element is in $b, and those form the basis for our output string.
The next portion is a string "..." using the -format operator. We specify locations in the string {0} for where that particular item goes. We feed to the -f operator the original (sorted) array $n, except without elements $a and $b, so four elements, which correspond to the 1,3,0,2 of the brackets. That string is left on the pipeline and output is implicit.

For a worked out example, let's assume that the OP meant non-negative input numbers, to match the test case of 1 9 5 0 8 3. This starts by sorting the input array, so we have 0 1 3 5 8 9 and re-saving that into $n. We pluck out the non-zero elements, so 1 3 5 8 9, and choose the [0,1] indices thereof. That means that $a=1 and $b=3, and thus we'll always know a < b and neither a nor b are 0.
Those are replaced in the string, so we have "3{1}{3} 1{0}{2}" to start. The -f operator takes the result of our array operation. Since $n is already still sorted, the pair of -ne operators result in 0 5 8 9 being fed to -f. As we're wanting the smallest sum, we obviously want the smaller elements to be used first. But, as we're wanting the largest difference, we want the larger elements to be associated to b. Hence, the {1}{3}{0}{2} arrangement for the indexing. This results in the string "359 108", the proper answer.

Perl 6, 82 bytes
*.permutations.map({my@a=.join.comb(3);@a if @a.all>100}).min({.sum,[R-] |$_}).put

Usage:
my &small = *.permutations.map({my@a=.join.comb(3);@a if @a.all>100}).min({.sum,[R-] |$_}).put;

small [2,6,5,1,9,7]; # 269 157
small [1,9,5,0,8,3]; # 359 108
small [1,2,3,4,5,6]; # 246 135

Explanation:
# Whatever lambda with input ｢*｣
*.permutations

  .map({

    # join and split into 3 character chunks
    my @a = $_.join.comb(3);

    # return the values if neither start with ｢0｣
    @a if @a.all > 100

  })

  # find the minimum
  .min({

    # by sum first
    $_.sum,

    # and reversed subtraction second
    # ( biggest difference in reversed order )
    [R-] |$_

  })

  # print it on a line, space separated
  .put

Ruby, 113 bytes
Try it online!
->a{(a.permutation(6).map{|c|c[0]*c[3]>0?[eval(c[0,3]*''),eval(c[3,3]*'')]:p}-[p]).min_by{|x,y|[x+y,-(x-y).abs]}}

Python3 97 bytes
def x(*s):d=sorted(s);i=(0,1)[not d[0]];print(d[1+i],d[3],d[5],' ',d[0+i],d[(2+i)%3],d[4],sep='')

The approach is based on the narrative of @Dennis answer.
First try on Ideone with the code (I hope I did save it): Try it!

d=sorted(input())[-6:];i=d[0]=='0';print(d[1+i]+d[3]+d[5],d[i]+d[2-2*i]+d[4]) - simple improvement of your code (now only 77 bytes required)

source: Stack Exchange

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

sort: votes


text:
Unsorted majorization of two lists
Definition
A vector a containing n elements is said to
majorize or
dominate a vector b with n
elements iff for all values k such that 1 ≤ k ≤ n, the sum of the first
element of a↓ through the kth element of a↓ is
greater than or equal to the sum of the first through kth elements of
b↓, where v↓ represents the vector v sorted in
descending order.
That is,
                          a_1 >= b_1
                    a_1 + a_2 >= b_1 + b_2
              a_1 + a_2 + a_3 >= b_1 + b_2 + b_3
                              ...
      a_1 + a_2 + ... + a_n-1 >= b_1 + b_2 + ... + b_n-1
a_1 + a_2 + ... + a_n-1 + a_n >= b_1 + b_2 + ... + b_n-1 + b_n

where a and b are sorted in descending order.
For the purpose of this challenge, we will be using a slight generalization of
majorization: we will say a list is an unsorted majorization of another if
all of the above inequalities are true without sorting a and b. (This is,
of course, mathematically useless, but makes the challenge more interesting.)
Challenge
Given an input of two distinct lists a and b of integers in the range 0
through 255 (inclusive), both lists of length n ≥ 1, output whether the first
list unsorted-majorizes the second (a > b), the second unsorted-majorizes
the first (b > a), or neither.
You may optionally require the length of the two lists to be provided as input.
The output must always be one of three distinct values, but the values
themselves may be whatever you want (please specify which values represent a
> b, b > a, and neither in your answer).
Test cases for a > b:
[255] [254]
[3,2,1] [3,1,2]
[6,1,5,2,7] [2,5,4,3,7]

Test cases for b > a:
[9,1] [10,0]
[6,5,4] [7,6,5]
[0,1,1,2,1,2] [0,1,2,1,2,1]

Test cases for no majorization:
[200,100] [150,250]
[3,1,4] [2,3,3]
[9,9,9,9,9,0] [8,8,8,8,8,9]

Can we take a 2-column array as input?

@LuisMendo Yes, the input may be in any format that does not encode extra information.

Would an array of pairs be acceptable?

Jelly, 10 8 6 bytes
2 bytes thanks to @orlp.
2 bytes thanks to @Dennis.
_+\ṠQS

Try it online!
1 for a>b, -1 for a<b, 0 for no majorization.
_+\ṠQS

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

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

ngn/apl, 11 bytes
{+/∪×+\⍺-⍵}

Based on the method in @Leaky Nun's answer.
Given two lists A and B, find the difference between each value elementwise, or let C = A - B. Then, find the cumulative sums of C and take the sign of each. The sum of the unique sign values will be the result. If A > B, the result is 1, if A < B the result is -1, and if there is no majority the result is 0.
Try it online.

Julia, 30 bytes
a^b=sum(sign(cumsum(a-b))∪0)

Saved 4 bytes thanks to @Dennis!

In which version of Julia did you test this?

Oops :P I think this should work.

Indeed. a^b=sum(sign(cumsum(a-b))∪0) saves a few bytes.

Python 3.5, 85 bytes:
lambda*e:[all(sum(g[:k])>=sum(h[:k])for k in range(1,-~len(h)))for g,h in[e,e[::-1]]]

An anonymous lambda function. Returns [True,False] if a>b, [False,True] if b>a, or [False,False] if neither of those are true. I hope this is okay.
Try It Online! (Ideone)

Cheddar, 118 114 bytes
n->[n.map(i->i[0]-i[1]).map((j,k,l)->l.slice(0,k+1).sum).map(i->i>0?1:i<0?-1:0)].map(j->j has 1?j has-1?0:1:-1)[0]

Basically a port of my Jelly answer.
The fact that scope inside function is broken causing inability to define variable inside function means that I would need to do [xxx].map(i->yyy)[0] instead of var a=xxx;yyy.
Takes transposed array as input.
n->[n
.map(i->i[0]-i[1])                     Difference (vectorized)
.map((j,k,l)->l.slice(0,k+1).sum)      Cumulative sum.
.map(i->i>0?1:i<0?-1:0)]               Sign of every difference
.map(j->j has 1?j has-1?0:1:-1)[0]     Deduplicate and Sum

Ruby, 72 59 bytes
Returns 1 for a>b, -1 for a<b, 0 for neither.
-13 bytes from cribbing the sum trick off of @Dennis in their Python answer
Try it online!
->a,b{x=y=0;a.zip(b).map{|i,j|(x+=i)<=>y+=j}.uniq.inject:+}

Python 2, 73 bytes
a,=b,=r={0}
for x,y in zip(*input()):a+=x;b+=y;r|={cmp(a,b)}
print sum(r)

Test it on Ideone.

Python 2, 59 bytes
t=r=0
for x,y in zip(*input()):t+=x-y;r|=cmp(t,0)%3
print r

Outputs:

1 for a>b
2 for b>a
3 for neither

Iterates through the list, tracking the running sum t of differences. The number s tracks what signs have been seen as a two-bit number r: positives in the right bit and negatives in the left bit. This happens via cmp(t,0)%3, which gives

t>0  → +1 → 1
t==0 → 0  → 0
t<0  → -1 → 2

Taking the or of this and the current value of r updates the 2 bits with or, with zero values having no effect.

Javascript (using external library-Enumerable) (123 bytes)
(a,b)=>(z=(c,d)=>_.Range(1,c.length).All(x=>_.From(c).Take(x).Sum()>=_.From(d).Take(x).Sum()))(a,b)==z(b,a)?0:(z(a,b)?1:-1)

Link to lib: https://github.com/mvegh1/Enumerable
Code explanation: Pass in vector a and b, create global function z. z will begin by creating an array of integers from 1, for a count of a.length. .All will verify that the predicate is true for every member belonging to a. That predicate says to load a as an enumerable, take a count of that enumerable equivalent to the current iteration value of that range we made, and sum that up. Check if that >= the same logic from array "b". So, we call z in the order of (a,b), and compare that to the order of (b,a)...if equal we return 0 to signify there is no major. Otherwise, we return 1 if (a,b) is true, else -1

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


text:
Turtles All the Way Down
Write a program or function that takes in a positive integer and prints or returns a stack of that many ASCII-art turtles, where each turtle is larger than the one above it.
Specifically, if the input is 1, the output should be:
 __
/,,\o

If the input is 2:
  __
o/,,\
 ____
/,__,\o

If the input is 3:
   __
  /,,\o
  ____
o/,__,\
 ______
/,____,\o

If the input is 4:
    __
  o/,,\
   ____
  /,__,\o
  ______
o/,____,\
 ________
/,______,\o

If the input is 5:
     __
    /,,\o
    ____
  o/,__,\
   ______
  /,____,\o
  ________
o/,______,\
 __________
/,________,\o

And so on in the same pattern for larger inputs.
Note that:

The head (the o) of the bottom turtle is always on the right. The heads of the turtles above then alternate back and forth.
No lines may have trailing spaces.
Superfluous leading spaces are not allowed. (i.e. the back of the bottom turtle should be at the start of the line.)
A single optional trailing newline is allowed.

The shortest code in bytes wins.

trichoplax, I'm expecting an answer that uses recursion.

,________, When someone says something that makes no sense.

Flipping sides to make sure that every turtle looking up or down sees an ass?

I'm glad you specified ASCII turtles.   Otherwise, I was going to finally submit a Logo answer where I didn't have to waste 3 bytes to hide the turtle.

That's not all the way down, that's only a finite distance down.

I like turtles!

I would have tried posting  but that is always heading the same way...

@TobiasKienzler I'm sure there are languages which can mirror characters, be creative :-)

Stacked turtles look like Christmas trees.

Mostly looks like Christmas fir-tree :3

Batch, 256 bytes
@set i=echo
@%i%off
set u=
for /l %%j in (2,2,%1)do call set i=%%i%%
set/af=%1^&1
if %f%==1 %i% __&%i%/,,\o&set u=__
for /l %%j in (2,2,%1)do call:l
exit/b
:l
set i=%i:~0,-2%
%i%  _%u%_
%i%o/,%u%,\
%i% __%u%__
%i%/,_%u%_,\o
set u=__%u%__

Note that line 1 has a trailing space and line 4 has two trailing spaces. i therefore contains an echo command with the appropriate amount of indentation for each turtle. Meanwhile u contains the number of underscores in alternate turtles. A leading odd turtle is special-cased and then the rest of the turtles are output in pairs.

+1 for being exactly 256 bytes. Do not golf it unless u can exactly half its length!

Originally I missed the note about trailing spaces, most of my editors are set to chop those off and I couldn't figure out why it wasn't working! Always happy to see Batch on PPCG. :)

@RohanJhunjhunwala That's a shame because I've just noticed that the 0 is unnecessary.

C, 131 bytes
i,j;f(n){char _[3*n];memset(_,95,3*n);for(i=n;i--;printf("%*.*s\n%*s/,%.*s,\\%s\n",j+n+1,j+j,_,i,"o"+1-i%2,j+j-2,_,"o"+i%2))j=n-i;}

Try it online.
Defines a function that prints the turtles.
Heavily abuses printf's width and precision specifiers to get the spacing and repeating the underscores. Each turtle is printed using a single printf call:
printf("%*.*s\n%*s/,%.*s,\\%s\n",j+n+1,j+j,_,i,"o"+1-i%2,j+j-2,_,"o"+i%2)

I also have a different version that's 144 bytes with whitespace removed:
c,i;f(n){for(i=n;i--;){
    char*p=" _\n o/,_,\\o\n";
    int C[]={i+1,c=n+n-i-i,1,i&~1,i%2,1,1,c-2,1,1,1-i%2,1};
    for(c=0;p[c];)C[c]--?putchar(p[c]):++c;
}}

Damn, I was about to add a C++ one

+1 for having ,_, in your code.

Ruby, 100 bytes
Recursive solution. Try it online!
f=->n,i=1{f[n-1,i+1]if n>1;puts' '*i+?_*n*2,"%#{i-1}s/,#{?_*2*~-n},\\"%(i<2?'':'o '[i%2])+' o'[i%2]}

V, 57, 53 49 bytes
i ³_
/,_,\oÀñHyjí_/___
ëPhjI ñdjí___
òkk$x^PXkk

Since this contains unprintable characters, here is a hexdump:
00000000: 6920 b35f 0a2f 2c5f 2c5c 6f1b c0f1 4879  i ._./,_,\o...Hy
00000010: 6aed 5f2f 5f5f 5f0a eb50 1668 6a49 20f1  j._/___..P.hjI .
00000020: 646a ed5f 5f5f 0af2 6b6b 2478 5e50 586b  dj.___..kk$x^PXk
00000030: 6b                                       k

Try it online!
Explanation:
i ³_\n/,_,\o<esc>       "Insert the original turtle with one extra underscore

Àñ                      "Arg1 times:
  Hyj                   "  Go the the beginning of the file, and yank a turtle
     í_/___             "  Extend the lenght of every turtle by two
ëP                      "  Move to the beginning of the file again, and paste the turtle we yanked
  <C-v>hjI              "  Move this turtle one to the right
           ñ            "Stop looping.

dj                      "Delete a turtle (since we have one too many)
  í___                  "Make every turtle shorter (since they are all too long)

ò                       "Recursively:
 kk                     "  Move up two lines
   $x                   "  Delete the last character on this line (an 'o')
     ^P                 "  And paste this 'o' at the beginning of the line
       X                "  Remove one space
        kk              "  Move up two lines again

Interesting outputs for inputs 0 and below.

This code also doesn't work for input > 10. On a side note, I accidentally broke it completely with the input 0 41c14. Not sure if I broke the code, or the runner.

@R.Kap Yeah, I think I know why it does that. V is barely able to comprehend integers, so it just sees -1 as a string that it can't pretend is a number. Thankfully, I don't have to handle those.

@BrandonAnzaldi Ah, I see why that doesn't work. I'll fix that in a minute. Also, doing anything other than decimal number is bound to cause some weird problems.

Yup! Cool solution. Figured it'd probably be somewhat simple to fix. I was just very, very fascinated with the output of the aforementioned accidental keyboard mash. Leading spaces also produce some fun output. Seems like you wrangled V quite nicely!

05AB1E, 45 bytes
Lvð¹y-©>×„__y×UXJ,„/,X¨¨„,\J'o®ÉiìëJ}ð®®É-×ì,

Try it online

Gets my vote for being so short.

Not sure if the G-loop was already in the August 2016 version, but if it was, Lv can be G and both y can be N for -1 byte.

Perl, 92 bytes
91 bytes code +1 for -n.
Requires -E at no extra cost.
for$i(1..$_){say$"x$_._,$v=_ x(--$i*2),_.$/.$"x(--$_-1),$_%2?o:$"x!!$_,"/,$v,\\",$_%2?"":o}

Usage
perl -nE 'for$i(1..$_){say$"x$_._,$v=_ x(--$i*2),_.$/.$"x(--$_-1),$_%2?o:$"x!!$_,"/,$v,\\",$_%2?"":o}' <<< 3
   __
  /,,\o
  ____
o/,__,\
 ______
/,____,\o

Thanks to @Dada for -9 bytes with his re-work!

Nice one. Another version, same bytecount : perl -nE 'for$i(1..$_){say$"x$_._.($v=_ x(($i-1)*2))._.$/.$"x(--$_-1).($_%2?o:$_?$":"")."/,$v,\\".($_%2?"":o)}'. I tried to get under 100 too but coudln't...

@Dada Thanks! Updated, much appreciated!

Cheddar, 105 bytes
n->(|>n).map(i->(1-i%2)*"o"+"\\,"+(n-i-1)*"__"+",/"+i%2*"o"+i/2*"  "+"\n"+(n-i)*"__"+(i+1)*" ").vfuse.rev

+1 for using cheese. You can use literal newline to save bytes

Retina, 97 91 88 bytes
Byte count assumes ISO 8859-1 encoding.
.+
  $&$*_$&$*_o
+`^( *?)(.)__(_+)(.)
$1 $4$3$2¶$&
 (.)__(_*) ?
  __$2¶$%`$1/,$2,\
Rm`^

Try it online!

C, 328 238 234 215 bytes:
B;M(w,j,R){j=w;if(j<=B){char b[j*2-1],k[j*2+1];b[j*2-2]=k[j*2]=0;memset(b,95,j*2-2);memset(k,95,j*2);R=(B+1-j)%2;printf("%*s\n%*s/,%s,\\%s\n",j*2+B+1-j,k,B-j,R?"":"o",b,R?"o":"");j++;M(j);}}main(){scanf("%d",&B);M(1);}

A recursive implementation using a lot of string formatting and the builtin memset function. Will try and golf this more over time as much as I can.
C It Online! (Ideone)

Strangely enough, the third and fourth turtles appear broken on Ideone...

@Quentin Actually, that is not Ideone. That is my program's fault. For some reason, the minute input approaches 17 and beyond, the logic breaks for some reason, and therefore, so do the turtles. I'm currently trying to figure out what is wrong.

Nice ! Note that you can replace most character literals ('c') by their ASCII code to spare one character each :)

@Quentin Nice?... It doesn't work very well. How is that nice?

Oh! I checked back on Ideone and it looked fixed, but that's because there are less turtles of course... Hazy morning.

@Quentin Well, it's finally fixed!

I swear you took some perfectly good C and threw it in a blender to write this

@βετѧΛєҫαγ Well, it is code golf, so...

@βετѧΛєҫαγ Well, when you have a limitation of how many characters you can use in your code, you have to exploit every inch of your given language. Also, this was my original code, which was nice and ordered, which I finally turned it into the answer you see now.

Python 2, 116 Bytes
m=input()
for i in range(m):r=m-i;b=r%2;h='o';a='__';u=i*a;s=' '*r;print s+u+a+'\n'+s[:b-2]+h*-~-b+"/,"+u+",\\"+b*h

I get your count at 115 bytes and you can save one byte by using lambda m:for i in r... instead of input()

TSQL, 189 bytes
Now with input acceptance - thanks to @PatrickRoberts
DECLARE @i INT=##i##,@ INT=0a:PRINT SPACE(@i-@)+REPLICATE('__',@+1)+'
'+SPACE((@i-@-1)/2*2)+IIF((@i-@-1)%2=1,'o/,','/,')+REPLICATE('__',@)+IIF((@i-@-1)%2=0,',\o',',\')SET
@+=1IF @i>@ GOTO a

Fiddle

Here's a version that lets you specify i at the cost of 4 bytes

@PatrickRoberts thanks, didn't know that one, is that sql server 2016 ?

@t-clausen.dk That input mechanism is specific to the data.SE site, it's not a standard feature of any version of SQL.

@BradC you are absolutely right, it is some sort of programming language, and very nice to finally be able to add a parameter input. I forgot all about this, and I will consider using it in the future paying the extra bytes

R, 150 bytes
a=function(x,y=1){d=x-y;t=d%%2;cat(rep(" ",d+1),rep("_",2*y),"\n",rep(" ",d-t),"o"[t],"/,",rep("_",2*y-2),",\\","o"[!t],"\n",sep="");if(y<x)a(x,y+1)}

more cleanly (adds a byte)
a=function(x,y=1){
     d=x-y
     t=d%%2
     cat(rep(" ",d+1),rep("_",2*y),"\n",rep(" ",d-t),"o"[t],"/,",rep("_",2*y-2),",\\","o"[!t],"\n",sep="")
     if(y<x)a(x,y+1)
}

Basic structure recursively calls itself --telling itself both the final number to be called and the current level. Starts with a default for y=1, so it only needs one variable for initial call. Quickly defines two values that are frequently used. Then it just repeats everything the necessary number of times.
"o"[t],"o"[!t]

Each of these implicitly test whether to add the head to right or left and place it appropriately.

Use # before the title in the markdown editor to format it like the other answers.

apologies -- so edited

Python, 137 120 113 110 bytes
m=input()
for i in range(m):p=m-i;b=p%2;print' '*p+'__'*-~i+'\n'+' '*(p-2+b)+'o'*-~-b+'/,'+'__'*i+',\\'+'o'*b

Ungolfed:
m=input()
for i in range(m):
  p=m-i                              // Abstract m-i for a few bytes
  b=p%2                              // Determines every other turtle from bottom

  print' '*p + '__'*-~i + '\n' +    // The top of the turtle
       ' '*(p-2+b) +                // Leading spaces (-1 for every other turtle)
       '0'*-~-b +                   // Add a leading head to every other turtle
       '/,'+'__'*i +                // Body of the turtle
       ',\\'+'0'*b                  // Add a trailing head to every other turtle

The heads were hard.

Instead of ('o','')[b], you can do 'o'*(1-b) (and 'o'*b for ('o','')[1-b]).

@mego oh right, i changed that to an empty char, that works.  thanks!

'0'*-~-1 is shorter than '0'*(1-b)

and -~i is shorter than (i+1)

Java 1.7, 238 bytes
A set of two functions: first iterates over input (# of turtles), second facilitates in constructing a sequence of repeated characters recursively (i.e. the leading spaces, the back and belly of the turtles).
String f(int n){String s="";for(int i=-1,x=-2;++i<n;){int m=(i+n)%2;s+=r(' ',n-i)+r('_',i*2+2)+"\n"+r(' ',n-i-(m==1?1:2))+(m==0?"o":"")+"/,"+r('_',x+=2)+",\\"+(m==1?"o":"")+"\n";}return s;}String r(char c,int n){return n>0?c+r(c,--n):"";}

Ungolfed:
class C {
    public static void main(String[] a) {
        System.out.println(new T().f(1));
        System.out.println(new T().f(2));
        System.out.println(new T().f(3));
        System.out.println(new T().f(4));
        System.out.println(new T().f(5));
    }

    static class T {

        String f(int n) {
            String s = "";
            for (int i = -1, x = 0; ++i < n; x+=2) {
                int m = (i + n) % 2;
                s += r(' ', n - i) + r('_', i * 2 + 2) + "\n" + r(' ', n - i - (m == 1 ? 1 : 2)) + (m == 0 ? "o" : "") + "/," + r('_', x) + ",\\" + (m == 1 ? "o" : "") + "\n";
            }
            return s;
        }

        String r(char c, int n) {
            return n > 0 ? c + r(c, --n) : "";
        }

    }

}

Run it! (Ideone)
I've assumed it's okay to exclude the class definition from the byte count.
I may be able to golf this a little further by reversing the iteration order of the loop (build from bottom turtle up) and/or by going fully recursive like some of the other answers.
Note to self: Java really lacks a built-in shorthand to repeat n characters...

"Write a program or function..." When do I have to include things like Java's public static void main

F#, 218 207 202 196 187 bytes.
Shaved most of these bytes by inlining variables
let R=String.replicate
let t n=let rec L i r k=if i<n then L(i+1)(R(k+i%2+1)" "+R((n-i)*2)"_"+"\n"+R k" "+R(i%2)"o"+"/,"+R(n*2-i*2-2)"_"+",\\"+R(1-i%2)"o"+"\n"+r)(k+i%2*2)else r in L 0""0

The logic is shamelessly stolen from this Python answer
Try it online.

CJam, 88 bytes
ri_[S\_'_*_+N+\O\"/,"\('_*_++','\+'o]\({_[(S+\(2>\(S\+)'O^c+\(-2<\(\('o\{;O}&\;]}*]-1%N*

Makes the biggest turtle first (because otherwise what would every other turtle stand on?), then gradually reduces the size until the smallest one is made. Works for any integer larger than 0.
Try it online!

Python 2, 147 bytes
n=input()
s=' ';r=[];i=k=0
while i<n:a=i%2;r=[s*k+s*a+s+'_'*(n-i)*2+s,s*k+'o'*a+'/,'+'_'*(n-i-1)*2+',\\'+'o'*(1-a)]+r;k+=a*2;i+=1
print'\n'.join(r)

Try it online

Python 2.7, 255 238 236 bytes
Even though this loses to both of the other Python 2 solutions, I liked my recursive approach:
def r(s,p):
 for(a,b)in p:s=a.join(s.split(b))
 return s
def t(w):
 i='_'*2*w;s='\n __%s\n/,%s,\o'%(i,i)
 if w:s=r(t(w-1),[('\n ','\n'),('Z/',' /'),('\\Z\n','\\\n'),(' /','o/'),('\\','\\o'),('o','Z')])+s
 return s
print t(input()-1)[1:]

edit1: dropped a few bytes by eliminating some replacements
edit2: shaved 2 bytes by saving the underscores as a variable

Python 2.7, 139 114 113 130 bytes
I also liked Iguanodon's recursive approach so here's a slightly shorter attempt.
def t(n):
 if n>1:t(n-1)
 a=i-n;b=(a+1)%2;print' '*(a+1)+'__'*n+'\n'+' '*(a-1+b)+'o'*(not b)+'/,'+'__'*(n-1)+',\\'+'o'*b
i=input()
t(i)

EDIT
A mighty 25 26 9 bytes golfed due to some fantastic tips from  Destructible Watermelon. Many thanks! Think it may be the shortest Python answer now :-)
def t(n):
 if n>1:t(n-1)
 a=i-n;b=-~a%2;print' '*-~a+'__'*n+'\n'+' '*(a-1+b)+'o'*-~-b+'/,'+'__'*~-n+',\\'+'o'*b
i=input()
t(i)

(a+1) can be shortened to -~a, and n-1 can be shortened to ~-n, and b is always 0 or 1, so not b can be shortened to -~-b, and you can eliminate the i=input();t(i) part, because you are allowed to just have a function.

Man thanks for some great hints @Destructible .  Also spotted that as b is always 1 or 0 then 1-b works and loses 1 more byte.

except that that would require parens, because * has higher priority than binary -, but unary - and ~ have higher priority than *

Now that i think about it, if n is always >0, then if n>1 can be shortened to ~-n (n-1), which chops off the leading space. Also, again, (1-b) can be shortened to -~-b with no parens

This just gets better and better! I'm pretty new to this and more used to writing readable code so your hints are greatly appreciated :)

just realised you are going to need to set i actually... currently doesn't work :(

Good point. As a function it is relying on the i variable outside of the function scope so I guess the i=input and t(i) are needed :(

I fixed it a bit :)
t(n,i=0) should be declaration|
if i<1:i=n, add this right under declaration|
if n>1:t(n-1,i) this is function call

also if you add +1 to the setting of a, you can remove the unary +1s and change -1 in the spaces to -2, to save 2 bytes

PowerShell, 105 100 97 87 85 84 bytes
-21 bytes thanks to mazzy, the mad man
"$args"..1|%{' '*$_--+($m='__'*$i++)+'__'
' '*($_-$_%2)+("/,$m,\o","o/,$m,\")[$_%2]}

Try it online!
Cleverly shifts variables using $_-- to avoid using repeated ($_+1) blocks to save several bytes. It also converts the single argument to a string which is then cast to an int when used in a range to iterate over through the number of turtles. Biggest trick is now having the 2nd level of a turtle's spacing only increase every other row by subtracting $_%2 (i.e. 0 if even, 1 if odd) from the current row_count.
Otherwise, it's a lot of index math to get proper _ and  counts, including a lag counter in the form of $i++, and now only a single list index to put the head on the correct side.

@mazzy Can't have trailing spaces but I did modify it for 5 bytes, thanks

I'm sorry :) 85 bytes

@mazzy Double dang, putting in even more work. Good stuff

That's all :) 84 bytes

ES6 (JavaScript), 140 bytes
Code
T=(i,h=0,p=1,R="repeat")=>(i>1?T(i-1,~h,p+1)+"\n":"")+" "[R](p)+'--'[R](i)+"\n"+" "[R](p-1+h)+(h?"o":"")+"/,"+'__'[R](i-1)+",\\"+(!h?"o":"")

Test
console.log(T(5));

     --
    /,,\o
    ----
  o/,__,\
   ------
  /,____,\o
  --------
o/,______,\
 ----------
/,________,\o

Canvas, 26 bytes
╷_×,×ｌ_×∔/×║o×⇵↔⁸¹－［  ×↔｝］

Try it here!

Vyxal, 62 bytes
(⁰nεð*nd⇧\_*+,⁰nε⇩ð*⁰nε₂[\o|⁰‹n=[¤|ð]]‛/,nd\_*‛,\⁰nε₂[|\o+]Wṅ,

Try it Online!
Many turtles.

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


text:
A queen's walk across a spiral
In a far-off kingdom, a chess queen takes a daily walk across a spiral path, numbered from 1 to n, not caring to follow the spiral itself, but simply making queen's moves as she would on a chessboard. The queen is beloved by her subjects, and they make a note of every square she visits on her path. Given that the queen can start her walk on any square and ends it on any square, what is the shortest queen's walk that she can take?
The challenge
Given a spiral of integers on a rectangular grid, write a function that returns one of the shortest possible paths (counted by number of cells travelled) between two numbers on this spiral grid using a chess queen's moves.
For example, from 16 to 25:
25 10 11 12 13
24  9  2  3 14
23  8  1  4 15
22  7  6  5 16
21 20 19 18 17

Some possible paths include 16, 4, 2, 10, 25 and 16, 5, 1, 9, 25.
Rules

The input will be any two positive integers.
The output will be a path of integers (including both endpoints) across the spiral using only orthogonal and diagonal moves.
The length of a path is counted by the number of cells travelled.
Your answer may be a program or a function.
This is code golf, so the smallest number of bytes wins.

As always, if the problem is unclear, please let me know. Good luck and good golfing!
Test cases
>>> queen_spiral(4, 5)
4, 5
>>> queen_spiral(13, 20)
13, 3, 1, 7, 20
>>> queen_spiral(14, 14)
14
>>> queen_spiral(10, 3)
10, 11, 3
>>> queen_spiral(16, 25)
16, 4, 2, 10, 25
>>> queen_spiral(80, 1)
80, 48, 24, 8, 1

Related.

You might want to mention that you're looking for the shortest path by number of cells travelled (as opposed to Euclidian distance, say).

Wouldn't this make more sense as a "king's walk"?

@JoKing Ah, now that you mention it, it should be a king's walk. It might be a little late to change the title, however.

APL (Dyalog Unicode), 59 57 bytesSBCS
{v⍳+\v[⍺],↓⍉↑(|⍴¨×)⊃⍵⍺-.⊃⊂v←9 11∘○¨+\0,0j1*{⍵/⍨⌈⍵÷2}⍳⍺⌈⍵}

Try it online!
-2 bytes thanks to @ngn.
Anonymous function that accepts two endpoints as left and right arguments.
Ungolfed & how it works
The queen moves diagonally first, so it is sufficient to pre-compute the coordinates of each number up to max(start,end).
The coordinate-generating algorithm is inspired from several answers on the related challenge, but is slightly different from any of the existing answers:

Given the necessary bound of 10
Generate the 1-based range r=1 2 3 4 5 6 7 8 9 10
Take the ceiling of half of each number n=1 1 2 2 3 3 4 4 5 5
Replicate each item of r by n. 1 2 3 3 4 4 5 5 5 6 6 6 7 7 7 7 8 8 8 8 9 9 9 9 9 10 10 10 10 10
Take the cumulative sum of power of imaginary unit, with starting point of 0. (this part is common to various Python solutions to the linked challenge)

Then, once the vector of coordinates v is ready, we can easily convert between the spiral index and coordinates using v[i] and v⍳coord (finding the first index of coord in v).
⍝ Define a function; ⍺=start, ⍵=end
f←{
  ⍝ Construct a vector of spiral coordinates v
  v←9 11∘○¨+\0,0j1*{⍵/⍨⌈⍵÷2}⍳⍺⌈⍵
                             ⍺⌈⍵  ⍝ max of start, end
                            ⍳     ⍝ range of 1 to that number
                   {⍵/⍨⌈⍵÷2}  ⍝ for each number n of above, copy itself ceil(n/2) times
               0j1*  ⍝ raise imaginary unit to the power of above
           +\0,      ⍝ prepend 0 and cumulative sum
                     ⍝ (gives vector of coordinates as complex numbers)
    9 11∘○¨  ⍝ convert each complex number into (real, imag) pair
  v←         ⍝ assign it to v

  ⍝ Extract start and end coordinates
  a w←(⍺⊃v)(⍵⊃v)

  ⍝ Compute the path the Queen will take
  v⍳+\(⊂a),↓⍉↑(|⍴¨×)w-a
                    w-a  ⍝ coordinate difference (end-start)
              (|⍴¨×)     ⍝ generate abs(x) copies of signum(x) for both x- and y-coords
                         ⍝ e.g. 4 -> (1 1 1 1), ¯3 -> (¯1 ¯1 ¯1)
           ↓⍉↑  ⍝ promote to matrix (with 0 padding), transpose and split again
                ⍝ (gives list of steps the Queen will take)
    +\(⊂a),     ⍝ prepend the starting point and cumulative sum
                ⍝ (gives the path as coordinates)
  v⍳  ⍝ index into the spiral vector (gives the spiral numbers at those coordinates)
}

(⍵⊃v)-⍺⊃v -> ⊃⍵⍺-.⊃⊂

(⍺⌷v) -> v[⍺]

Mathematica 615 530 bytes
This constructs a number grid, converts it into a graph, and then finds a shortest path between the two numbers that were input.

UnGolfed
numberSpiral is from Mathworld Prime Spiral.  It creates an n by n  Ulam Spiral (without highlighting the primes).
findPath converts the number grid into a graph. Edges are valid queen moves on the number grid.

numberSpiral[n_Integer?OddQ]:=
  Module[{a,i=(n+1)/2,j=(n+1)/2,cnt=1,dir=0,len,parity,vec={{1,0},{0,-1},{-1,0},{0,1}}},a=Table[j+n(i-1),{i,n},{j,n}];Do[Do[Do[a[[j,i]]=cnt++;{i,j}+=vec[[dir+1]],{k,len}];dir=Mod[dir+1,4],{parity,0,1}],{len,n-1}];a];

findPath[v1_, v2_] :=
  Module[{f, z, k},
    (*f  creates edges between each number and its neighboring squares *)
    f[sp_,n_]:=n<->#&/@(sp[[Sequence@@#]]&/@(Position[sp,n][[1]]/.{r_,c_}:>Cases[{{r-1,c},{r+1,c},{r,c-1},{r,c+1},{r-1,c-1},{r-1,c+1},{r+1,c+1}, {r+1,c-1}},{x_,y_}/; 0<x<k&&0<y<k]));k=If[EvenQ[
     z=\[LeftCeiling]Sqrt[Sort[{v1, v2}][[-1]]]\[RightCeiling]],z+1,z];
    FindShortestPath[Graph[Sort/@Flatten[f[ns=numberSpiral[k],#]&/@Range[k^2]] //Union],v1,v2]]

Examples
findPath[4,5]
findPath[13,22]
findPath[16,25]
numberSpiral[5]//Grid

{4,5}
{13,3,1,7,22}
{16,4,1,9,25}

The shortest path from 80 to 1 contains 5, not 6, vertices.
findPath[80,1]
numberSpiral[9]//Grid

{80, 48, 24, 8, 1}

Golfed
u=Module;
w@n_:=u[{a,i=(n+1)/2,j=(n+1)/2,c=1,d=0,l,p,v={{1,0},{0,-1},{-1,0},{0,1}}},
a=Table[j+n(i-1),{i,n},{j,n}];
Do[Do[Do[a[[j,i]]=c++;{i,j}+=v[[d+1]],{k,l}];d=Mod[d+1,4],{p,0,1}],{l,n-1}];a];
h[v1_,v2_]:=u[{f,z},
s_~f~n_:=n<->#&/@(s[[Sequence@@#]]&/@(Position[s,n][[1]]/.{r_,c_}:>
Cases[{{r-1,c},{r+1,c},{r,c-1},{r,c+1},{r-1,c-1},{r-1,c+1},{r+1,c+1},{r+1,c-1}},{x_,y_}/;0<x<k&&0<y<k]));
k=If[EvenQ[z=\[LeftCeiling]Sqrt[Sort[{v1,v2}][[-1]]]\[RightCeiling]],z+1,z];
FindShortestPath[g=Graph[Sort/@Flatten[f[ns=w@k,#]&/@Union@Range[k^2]]],v1,v2]]

Scala (830 bytes)
Builds the spiral in a square 2D array using four mutually recursive functions. Another recursive search to build the path list.
def P(s:Int,e:Int):List[Int]={
import scala.math._
type G=Array[Array[Int]]
type I=Int
type T=(I,I)
def S(z:I)={def U(g:G,x:I,y:I,c:I,r:I):Unit={for(i<-0 to r.min(y)){g(y-i)(x)=c+i}
if(r<=y)R(g,x,y-r,c+r,r)}
def R(g:G,x:I,y:I,c:I,r:I)={for(i<-0 to r){g(y)(x+i)=c+i}
D(g,x+r,y,c+r,r+1)}
def D(g:G,x:I,y:I,c:I,r:I)={for(i<-0 to r){g(y+i)(x)=c+i}
L(g,x,y+r,c+r,r)}
def L(g:G,x:I,y:I,c:I,r:I)={for(i<-0 to r){g(y)(x-i)=c+i}
U(g,x-r,y,c+r,r+1)}
val g=Array.ofDim[I](z,z)
U(g,z/2,z/2,1,1)
g}
def C(n:I,g:G):T={var(x,y)=(0,0)
for(i<-g.indices){val j=g(i).indexOf(n)
if(j>=0){x=j
y=i}}
(x,y)}
def N(n:Int)=if(n==0)0 else if(n<0)-1 else 1
def Q(a:T,b:T):List[T]={val u=N(b._1-a._1)
val v=N(b._2-a._2)
if(u==0&&v==0)b::Nil else a::Q((a._1+u,a._2+v),b)}
val z=ceil(sqrt(max(s,e))).toInt|1
val p=S(z)
Q(C(s,p),C(e,p)).map{case(x,y)=>p(y)(x)}}

Ungolfed
  import scala.math._
  type Grid=Array[Array[Int]]
  def spiral(size: Int) = {
    def up(grid:Grid, x: Int, y: Int, c: Int, r: Int): Unit = {
      for (i <- 0 to r.min(y)) {
        grid(y-i)(x) = c + i
      }
      if (r <= y)
        right(grid,x,y-r,c+r,r)
    }
    def right(grid:Grid, x: Int, y: Int, c: Int, r: Int) = {
      for (i <- 0 to r) {
        grid(y)(x+i) = c + i
      }
      down(grid,x+r,y,c+r,r+1)
    }
    def down(grid:Grid, x: Int, y: Int, c: Int, r: Int) = {
      for (i <- 0 to r) {
        grid(y+i)(x) = c + i
      }
      left(grid,x,y+r,c+r,r)
    }
    def left(grid:Grid, x: Int, y: Int, c: Int, r: Int) = {
      for (i <- 0 to r) {
        grid(y)(x-i) = c + i
      }
      up(grid,x-r,y,c+r,r+1)
    }
    val grid = Array.ofDim[Int](size,size)
    up(grid,size/2,size/2,1,1)
    grid
  }
  def findPath(start: Int, end: Int): List[Int] = {
    def findCoords(n: Int, grid: Grid): (Int, Int) = {
      var (x,y)=(0,0)
      for (i <- grid.indices) {
        val j = grid(i).indexOf(n)
        if (j >= 0) {
          x = j
          y = i
        }
      }
      (x,y)
    }
    def sign(n: Int) = if (n == 0) 0 else if (n < 0) -1 else 1
    def path(stc: (Int, Int), enc: (Int, Int)) : List[(Int, Int)] = {
      val dx = sign(enc._1 - stc._1)
      val dy = sign(enc._2 - stc._2)
      if (dx == 0 && dy == 0) {
        enc :: Nil
      } else {
        stc :: path((stc._1 + dx, stc._2 + dy), enc)
      }
    }
    val size = ceil(sqrt(max(start, end))).toInt | 1
    val spir = spiral(size)
    path(findCoords(start, spir),findCoords(end, spir)).
      map { case (x, y) => spir(y)(x) }
  }

Ruby, 262 218 216 bytes
This is a port of my Python answer. Golfing suggestions welcome.
Edit: 45 bytes thanks to Jordan and their suggestions of d=[0]*n=m*m;*e=c=0;*t=a, .rect, 0<=>x and x,y=(e[a]-g=e[b]).rect; t<<d[(g.real+x)*m+g.imag+y]. Another byte from (x+y*1i) to (x+y.i).
->a,b{m=([a,b].max**0.5).to_i+1;d=[0]*n=m*m;*e=c=0;*t=a
n.times{|k|d[c.real*m+c.imag]=k+1;e<<c;c+=1i**((4*k+1)**0.5-1).to_i}
x,y=(e[a]-g=e[b]).rect
(x+=0<=>x;y+=0<=>y;t<<d[(g.real+x)*m+g.imag+y])while(x+y.i).abs>0
t}

Ungolfed:
def q(a,b)
  m = ([a,b].max**0.5).to_i+1
  n = m*m
  d = [0]*n
  c = 0
  *e = c   # same as e=[0]
  *t = a   # same as t=[a]

  (1..n).each do |k|
    d[c.real * m + c.imag] = k+1
    e << c
    c += 1i**((4*k+1)**0.5-1).to_i
  end

  x, y = (e[a] - g=e[b]).rect

  while (x+y.i).abs > 0 do
    if x<0
      x += 1
    elsif x>0
      x += -1
    end

    if y<0
      y += 1
    elsif y>0
      y -= 1
    end

    t << d[(g.real+x)*m+g.imag+y]
  end

  return t
end

You should remove the q= from your answer since you're not counting its bytes. c=0;e=[c];t=[a] can be shortened to *e=c=0;*t=a. You can replace z=e[a]-e[b];x,y=z.real,z.imag with x,y=(e[a]-e[b]).rect and x+=x<0?1:x>0?-1:0 with x+=0<=>x (same for y). I think that gets it down to 229 bytes.

If you switch to a 1-dimensional array you can save 6 more bytes. Replace the initialization of d with d=[0]*m*m, then replace d[c.real][c.imag] with d[c.real*m+c.imag] and d[e[b].real+x][e[b].imag+y] with d[(e[b].real+x)*m+e[b].imag+y].

A 2-byte improvement over my previous comment: t<<d[(e[b].real+x)*m+e[b].imag+y] can be shortened to u,v=e[b].rect;t<<d[(u+x)*m+v+y].

Two more bytes by changing d=[0]*m*m to d=[0]*n=m*m and (m*m).times to n.times. That's 219.

You can save two additional bytes by changing x,y=(e[a]-e[b]).rect to x,y=(e[a]-g=e[b]).rect, deleting u,v=e[b].rect and changing t<<d[(u+x)*m+v+y] to t<<d[(g.real+x)*g.imag+v+y] (basically reverting my second-to-last comment).

Python 3, 316 bytes
This answer looks at the coordinates of a and b on the spiral (using complex numbers) and adds the diagonal moves first, then the orthogonal moves.
def q(a,b):
 m=int(max(a,b)**.5)+1;d=[];c=0;e=[c];t=[a]
 for i in range(m):d+=[[0]*m]
 for k in range(m*m):d[int(c.real)][int(c.imag)]=k+1;e+=[c];c+=1j**int((4*k+1)**.5-1)
 z=e[a]-e[b];x,y=int(z.real),int(z.imag)
 while abs(x+y*1j):x+=(x<0)^-(x>0);y+=(y<0)^-(y>0);t+=[d[int(e[b].real)+x][int(e[b].imag)+y]]
 return t

Ungolfed:
def queen_spiral(a,b):
    square_size = int(max(a,b)**.5)+1
    complex_to_spiral = []
    complex = 0
    spiral_to_complex = [c] # add 0 first, so that it's 1-indexed later
    result = [a]

    for i in range(square_size):
        complex_to_spiral.append([0]*square_size) # the rows of the spiral

    for k in range(square_size**2):
        row = int(complex.real)
        column = int(complex.imag)
        complex_to_spiral[row][column] = k+1 # 1-indexing

        spiral_to_complex.append(complex)

        quarter_turns = int((4*k+1)**.5-1)
        complex += 1j**quarter_turns

    z = spiral_to_complex[a] - spiral_to_complex[b]
    v = spiral_to_complex[b]
    x, y = int(z.real), int(z.imag)
    r, s = int(v.real), int(v.imag)

    while abs(x+y*1j):
        if x < 0:
            x += 1
        elif x > 0:
            x += -1
        # else x == 0, do nothing
        if y < 0:
            y += 1
        elif y > 0:
            y += -1

        vertex = complex_to_spiral[r+x][s+y]
        result.append(vertex)
    return result


text:
Collatz Paths: Forwards and Backwards along the Collatz Conjecture
The Collatz conjecture is a very well-known conjecture. Take a positive integer; if it's even, divide by 2, else, multiply by 3 and add 1. Repeat until you reach 1 or something else happens. The conjecture is that this process always reaches 1.
You can also reverse the process. Start at 1, multiply by 2, and to branch to multiply by 3 and add 1 numbers, when you reach an even number that is 1 (mod 3), subtract 1 and divide by 3.
A Collatz path combines the two, trying to get from one number to another with those four operations.
For example, to get to 20 from 1:
1     *2
2     *2
4     *2
8     *2
16    *2
5     (-1)/3
10    *2
20    *2

You can also get to 3 from 10 by subtracting 1 and dividing by 3.
With these tools, you can traverse a Collatz path from one number to another. For example, the path from 20 to 3 is (divide by 2), (subtract 1, divide by 3).
In short, the available operations are:
n * 2       always
n // 2      if n % 2 == 0
n * 3 + 1   if n % 2 == 1
(n-1) // 3  if n % 6 == 4

Note: not all Collatz paths are short. a(7,3) could run
7, 22, 11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1, 2, 4, 8, 16, 5, 10, 3

but a shorter path is
7, 22, 11, 34, 17, 52, 26, 13, 40, 20, 10, 3

The Challenge
Find the length of the shortest Collatz path between any two positive integers, p and q.

Input is any two positive integers less than 2^20 to avoid integer overflow. The input method is left to the discretion of the golfer. The integers may be the same, in which case, the length of the Collatz path is 0.
Output should be one integer, denoting the length of the shortest Collatz path between p and q.

Test Cases
a(2,1)
1

a(4,1)
1         # 4 -> 1

a(3,1)
6         # 3 -> 10 -> 5 -> 16 -> 8 -> 4 -> 1

a(11,12)
11        # 11 -> 34 -> 17 -> 52 -> 26 -> 13
          # -> 40 -> 20 -> 10 -> 3 -> 6 -> 12

a(15,9)
20        # 46 -> 23 -> 70 -> 35 -> 106 -> 53 -> 160 -> 80 -> 40 -> 13
          # -> 26 -> 52 -> 17 -> 34 -> 11 -> 22 ->  7 -> 14 -> 28 -> 9

Many thanks to orlp for their help in clarifying this challenge.
As always, if the problem is unclear, please let me know. Good luck and good golfing!

Our computers wouldn't endure an array of at least 2^31 elements.

@MatthewRoh Challenge has since been edited.

This is pretty much a [tag:graph-theory] [tag:path-finding] challenge. And I'm pretty sure we had a almost identical one before.

Possible duplicate of Shortest paths in a divisor graph

@flawr I don't agree with the duplicate. Yes, both challenges want to find a path in a graph, but the graphs are different, and encoding the graph structure in your answer is the unique part, IMO. See for example my answer, and compare it to the answers in your 'duplicate' question.

I see, so you'd consider it different problems as soon as you change the definition of the graph? I just thought it is another infinite graph on the integers, the edges are again defined by a property the corresponding numbers.

@flawr You're right. Applies to a(4,1), too.

Haskell, 170 158 157 146 143 137 135 112 109 108 106 100 99 bytes
a!b=length$fst$break(elem b)$iterate(>>= \n->2*n:cycle[div n 2,n*3+1]!!n:[div(n-1)3|mod n 6==4])[a]

I did not expect that my original version was so much more golfable, this is also the work of @nimi @Lynn and @Laikoni!
Thanks @Laikoni for a byte, @Lynn for 11 14 20 21 bytes, @nimi for 8 bytes!
This expands the the tree of visited numbers (beginning by a) step by step, and checks in each step whether we arrived at the given number b.

You missed one space: iterate s [a] -> iterate s[a]

Sweet~ Inlining s saves three more bytes! iterate(nub.concat.map f)[a] Also, do you really need the nub?

Tell me when you're finished golfing:D Thank you very much. Unfortunately I'm still have trouble understanding monads.

@nimi Again, thank you very much, I never expected that it is so much more golfable! I didn't know about break and span, really useful!

Replacing [div n 2,n*3+1]!!mod n 2 with cycle[div n 2,n*3+1]!!n saves one more byte :)

@Lynn That is a very clever idea! Nice!

Python 2, 110 bytes
a=lambda p,q,s={0}:1+a(p,q,s.union(*({p,n*2,[n/2,n*3+1][n%2]}|set([~-n/3]*(n%6==4))for n in s)))if{q}-s else-1

Python 2, 156 179 191 209 181 172 177 171 bytes
Since a Collatz path can be imagined as a(1,p) and a(1,q) conjoined at the first number that is common to both sequences and a(1,n) is the original Collatz conjecture, this function calculates the Collatz sequence of p and q, and calculates the length from there. This isn't a pretty golf, so golfing suggestions are very much welcome. The only exception is when p or q == 1. Then, since we can skip directly from 4 to 1 as opposed to a regular Collatz sequence, we need to subtract a step from the result.
Edit: Lots of bug fixing.
Edit: Lots and lots of bug fixing
f=lambda p:[p]if p<3else f([p//2,p*3+1][p%2])+[p]
def a(p,q):
 i=1;c=f(p);d=f(q)
 if sorted((p,q))==(1,2):return 1
 while c[:i]==d[:i]!=d[:i-1]:i+=1
 return len(c+d)-2*i+2

Try it online!

Your approach does not work, e.g. a(3,1) returns 7 while it should return 6, as the shortest path is 3 -> 10 -> 5 -> 16 -> 8 -> 4 -> 1

@flawr Edited. Hopefully it works now

Why do you assume that the algorithm you described works? Couldn't a shortest path consist of multiple times going "back and forth"?

@flawr That's a good point. Deleting until I can prove/disprove my idea.

Let f denote a step forward, b a step backward in the collatz sequence. The pattern b->f cannot be in a shortest path, as it is the identity (f is undoing b in any case.) So the shortest path can only consist of patterns f->f, f->b and b->b. That means again that the shortest path is always of the form f->f->...->f or b->b->...->b or f->...->f->b->...->b

PS: I have the impression your byte count is going in the wrong direction. :D

@flawr So I have noticed XD Bug fixes before golfing, I say

Pyth, 30 bytes
|q*FQ2ls-M.pm.u&n2N?%N2h*3N/N2

Try it online
How it works
Take the length of the symmetric difference of the two forward Collatz sequences starting at the two input numbers and ending at 2. The only exception is if the input is [1, 2] or [2, 1], which we special-case.
  *FQ                        product of the input
|q   2                       if that equals 2, return 1 (True), else:
            m                  map for d in input:
             .u                  cumulative fixed-point: starting at N=d, iterate N ↦
               &n2N?%N2h*3N/N2     N != 2 and (N*3 + 1 if N % 2 else N/2)
                                 until a duplicate is found, and return the sequence
          .p                   permutations
        -M                     map difference
       s                       concatenate
      l                        length

JavaScript (ES6), 135 bytes
f=(x,y,a=[(s=[],s[0]=s[x]=1,x)],z=a.shift())=>z-y?[z*2,z/2,z%2?z*3+1:~-z/3].map(e=>e%1||s[e]?0:s[a.push(e),e]=-~s[z])&&f(x,y,a):~-s[y]

Performs a breadth-first search. x is the starting number, y the destination, a an array of trial values, s an array of the number of inclusive steps on the chain from x, z the current value. If z and y are not equal, compute z*2, z/2 and either z*3+1 or (z-1)/3, depending on whether z is odd or even, then filter out fractions and previously seen values and add them to the search list.

Python 2, 80 bytes
p=lambda n:n-2and{n}|p([n/2,n*3+1][n%2])or{n}
lambda m,n:m*n==2or len(p(m)^p(n))

Take the length of the symmetric difference of the two forward Collatz sequences starting at the two input numbers and ending at 2. The only exception is if the input is 1, 2 or 2, 1, which we special-case.