text:
The Lonely Islands
Input:
A 2D array containing two distinct (optional) values.
I'll use 0 and 1 when explaining the rules. The input format is of course flexible.

Challenge:
Zeros are water, and ones are islands. In order to ensure loneliness, your task is to surround all islands with water by inserting rows and columns of zeros. You don't want to waste water, so you must minimize the amount of water added. In case there are more than one solution that requires the same amount of water added, then you should add columns of water, not rows. I'll show this in the test cases.

Output:
The new, modified 2D array. The output format is of course flexible.

Test cases:
Input and output are separated by dashes. Added zeros are shown in bold font. Use one of the answers here if you want to convert the test cases to more convenient formats.
1
---
1

1 1
---
1 0 1

1 1
1 1
---
1 0 1
0 0 0
1 0 1

1 0
0 1
---
1 0 0
0 0 1
Note that we added a column of zeros, not a row of zeros. This is because the number of necessary zeros is equal, and columns should be preferred.

1 0 0 0 1
0 1 0 1 0
0 0 1 0 0
0 1 0 1 0
---
1 0 0 0 1
0 0 0 0 0
0 1 0 1 0
0 0 0 0 0
0 0 1 0 0
0 0 0 0 0
0 1 0 1 0
Note that we added rows, not columns, since that requires the least amount of extra zeros.

0 0 1 0 0
0 1 1 1 0
---
0 0 0 1 0 0 0
0 0 0 0 0 0 0
0 1 0 1 0 1 0
This required both columns and a row.

0 0 1 0 0
0 1 0 1 0
---
0 0 0 1 0 0 0
0 1 0 0 0 1 0
Better to add two columns than one row, since it requires less water.

0 0
1 0
0 1
1 0
0 0
---
0 0
1 0
0 0
0 1
0 0
1 0
0 0
Better to add two rows than one column, since it requires less water.

Related.

Damnit, Stewie, now I've got "Jack Sparrow" stuck in my head again!

This problem is equivalent to the vertex cover problem on bipartite graph, and according to Wikipedia it can be solved in polynomial time.

I changed my mind... it may be weighted. Anyway for sufficiently large square matrix it's (hopefully) equivalent. So if your algorithm is "too simple", be careful.

I think I have a polynomial time algorithm.

Jelly, 37 bytes
ṫƤ-S€ZƊ⁺FỊẠ
Z_,,WƲ€ŒpẎ€Ʋ⁺€ẎLÞFL$ÞṚÇÞṪ

Try it online!
Function returning a 2D array of integers. Note that naturally in Jelly singleton list displays as its value so G is used to format the output.

Link 1: Return (validity).
Link 2: Main program.

The program runs in exponential time, but so-far I could not think of any polynomial time algorithm.
Uses Ƥ on dyadic function, that feature postdates the challenge.

Python 2, 374 346 340 339 323 317 bytes
R=range;L=len
def f(a):
 w,h=L(a[0]),L(a);W=[]
 for i in R(2**w):
	A=zip(*a)
	for c in R(w):A[-c:-c]=[[0]*h]*(i&1<<c>0)
	for j in R(2**h):
	 B=zip(*A);x=L(B[0])
	 for r in R(h):B[-r:-r]=[(0,)*x]*(j&1<<r>0)
	 y=L(B);W+=[(w*h-x*y,x,B)]*all(sum(B[i][j:j+2]+B[i+1][j:j+2])<2for i in R(y-1)for j in R(x))
 return max(W)[2]

Try it online!

I think the first [:] can be removed without affecting the output.

@user202729, Thanks, I think it can. I'd changed it in the meantime though :)

source: Stack Exchange

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

sort: votes


text:
Paths & Wasting Time
Premise
So recently I was about half an hour early to an appointment, and decided to wait outside. I also determined that it would look strange if I just stood motionlessly in front of the house. Therefore, I decided to go on a quick walk, within a limited area. I also concluded that if I started walking in circles that would make it obvious that I was loitering. So I was inspired to create my first Code Golf challenge.
Specification
You will be given a list, a map of the area, which will contain either " " or "#", which represent free spaces and obstacles of some sort. Free spaces can only be crossed once, and it takes 1 minute to cross it. Your initial position will be signified with a "@" per roguelike tradition, and the target will be represented with a "$" because that's what you're going to lose there. You will also be given an integer which will represent how many minutes you have to waste before not seeming as if you were intruding. When you land on the "$", it will have to have been the exact amount minutes (so if you were counting down, it will have to be 1 on an adjacent tile, and be 0 on the tile). It will always be possible to reach the destination. Your program or function will have to return a list showing the shortest path with <, >, ^, and v to represent the four possible directions.
Examples
Input:
[[" ", " ", " ", " "],
 ["@", " ", " ", "$"],
 [" ", " ", " ", " "],
 [" ", " ", " ", " "]]

and
5

Ouput:
[[">", ">", ">", "v"],
 ["^", " ", " ", "$"],
 [" ", " ", " ", " "],
 [" ", " ", " ", " "]]

Input:
[[" ", "#", " ", " ", " "],
 [" ", "#", " ", " ", " "],
 ["@", "#", " ", "$", " "],
 [" ", " ", " ", " ", " "],
 [" ", "#", " ", " ", " "],
 [" ", "#", " ", " ", " "]]

and
7

Output:
[[" ", "#", " ", " ", " "],
 [" ", "#", ">", "v", " "],
 ["v", "#", "^", "$", " "],
 [">", ">", "^", " ", " "],
 [" ", "#", " ", " ", " "],
 [" ", "#", " ", " ", " "]]

Input:
[[" ", "#", " ", " ", " "],
 [" ", "#", " ", " ", " "],
 ["@", "#", " ", "$", " "],
 [" ", " ", " ", " ", " "],
 [" ", "#", " ", " ", " "],
 [" ", "#", " ", " ", " "]]

and
17

Output:
[[" ", "#", " ", "v", "<"],
 [" ", "#", " ", "v", "^"],
 ["v", "#", " ", "$", "^"],
 [">", ">", "v", ">", "^"],
 [" ", "#", "v", "^", "<"],
 [" ", "#", ">", ">", "^"]]

Rules

Standard loopholes apply
Each tile must only be moved over once
The exact amount of time must be spent on the board
Only one path needs to be displayed in the case of multiple paths
This is a code golfing question so shortest answer wins
As per user202729's question in the comments, you may assume valid input.

Add a comment if any further clarification is required

Is it guaranteed that "It will always be possible to reach the destination in the time specified"?

Yes, it will, there will always be a way, even if convoluted

Welcome to PPCG! :) Nice first challenge.

What happened to the half minute at each end?! (no need to change anything if it's not obvious)

JavaScript (ES6), 171 bytes
Takes input in currying syntax (a)(n). Outputs by modifying the input matrix.
a=>g=(n,y=a[F='findIndex'](r=>~(i=r[F](v=>v>'?'))),x=i,R=a[y])=>!n--|[-1,0,1,2].every(d=>(R[x]='<^>v'[d+1],(c=(a[Y=y+~-d%2]||0)[X=x+d%2])<1?g(n,Y,X):n|c!='$')&&(R[x]=' '))

Try it online!
Commented
a =>                           // a[] = input matrix
g = (                          // g = recursive function taking:
  n,                           //   n = number of remaining moves
                               //   (x, y) = current coordinates, initialized as follows:
  y = a[F = 'findIndex'](r =>  //     y = index of the row containing the starting point,
    ~(i = r[F](v => v > '?'))  //         found by iterating over all rows r until we
  ),                           //         find some i such that r[i] > '?'
  x = i,                       //     x = index of the column of the starting point
  R = a[y]                     //   R[] = current row
) =>                           //
  !n-- |                       // decrement n; force failure if we're out of moves
  [-1, 0, 1, 2].every(d =>     // for each direction d, where -1 = left, 0 = up,
    (                          // 1 = right and 2 = down:
      R[x] = '<^>v'[d + 1], (  //   update the current cell with the direction symbol
        c = (                  //   c = content of the new cell at (X, Y) with:
          a[Y = y + ~-d % 2]   //     Y = y + dy
          || 0                 //     (use a dummy value if this row does not exist)
        )[X = x + d % 2]       //     X = x + dx
      ) < 1 ?                  //   if c is a space:
        g(n, Y, X)             //     we can go on with a recursive call
      :                        //   else:
        n | c != '$'           //     return false if n = 0 and we've reached the target
    ) &&                       //   unless the above result is falsy,
    (R[x] = ' ')               //   restore the current cell to a space
  )                            // end of every()

Python 2, 310 256 bytes
Thanks @cairdcoinheringaahing for except:0 -3 bytes
Thanks @Mnemonic for -8 bytes
Thanks @JonathanAllan for -3 bytes
Thanks @ovs for -5 bytes
G,L=input()
R=[]
def S(x,y,G,c,R):
 try:
	if x>-1<y<G[y][x]in' @':i=0;exec"T=[r[:]for r in G];T[y][x]='<v^>'[i];S(x+~-i/2,y+~-(i^2)/2,T,c-1,R);i+=1;"*4
	R+=[G]*(0==c<'$'==G[y][x])
 except:0
for i,y in enumerate(G):"@"in y>S(y.index("@"),i,G,L,R)
print R[0]

Try it online!
Some explanation:
try-except is used to ensure, that both x and y coordinates are in boundaries. Exception will be raised upon access to G[y][x]. Python is too good and negative indices are acceptable, so check x>-1<y is added.
T=[r[:]for r in G] used to create copy of G by values
~-i/2 and ~-(i^2)/2 are used to generate pairs (-1, 0), (0, 1), (0, -1), (1, 0), that used to move in grid (there still should be shorter way!)
R+=[G]*(0==c<'$'==G[y][x]) check, that '$' is reached in required number of steps. R is used to get this result from recursive function calls.
for i,y in enumerate(G):"@"in y>S(y.index("@"),i,G,L,R) Found x and y of '@' in input and call function S.
print R[0] R might contain more that one solution, so output just first

-4 bytes

You can save a byte by replacing if G[y][x]=='$': with if'$'==G[y][x]:.

Actually, that whole condition can be replaced with R+=(G[y][x]=='$')*(c==0)*[G] for another byte.

@Mnemonic Second fix does not save bytes, but still cool, thanks ;D

Huh, not sure what I was seeing.  You can save a couple bytes in the first condition with if(x>-1<y)*(G[y][x]in' @'):

Also, you can save a few on the loop at the end.  268 bytes

@Mnemonic Thanks! Even 2 more with cheeky list comprehension :D

A shorter way for your y+cmp(i%2,i/2) would be y+~-(i^2)/2; there may well be shorter still.

@JonathanAllan Thanks! Search continues..

@ovs Clever fixes, made me scrach my head for some time, thanks!

[S(y.index("@"),i,G,L,R)for i,y in enumerate(G)if"@"in y]-> for i,y in enumerate(G):"@"in y>S(y.index("@"),i,G,L,R)  for -2 bytes

Python 2, 264 261 251 249 bytes
def f(a,n,r=-1,s=0):
 j=len(a[0]);x=1;z=y=0
 if r<0:s,r=divmod(sum(a,[]).index('@'),j)
 for c in'>v<^':
	u=r+x;v=s+y;x,y=-y,x
	if j>u>-1<v<len(a):b=[e[:]for e in a];b[s][r]=c;w=a[v][u];z=n*(w<'!')and f(b,n-1,u,v)or n==1and w=='$'and b
	if z:return z

Try it online!

@Arnauld: Oops! Got a bit too fancy. Fixed.

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


text:
Distance between two points on the Moon
Given latitude/longitude of two points on the Moon (lat1, lon1) and (lat2, lon2), compute the distance between the two points in kilometers, by using any formula that gives the same result as the haversine formula.
Input

Four integer values lat1, lon1, lat2, lon2 in degree (angle) or
four decimal values ϕ1, λ1, ϕ2, λ2 in radians.

Output
Distance in kilometers between the two points (decimal with any precision or rounded integer).
Haversine formula

where

r is the radius of the sphere (assume that the Moon's radius is 1737 km),
ϕ1 latitude of point 1 in radians
ϕ2 latitude of point 2 in radians
λ1 longitude of point 1 in radians
λ2 longitude of point 2 in radians
d is the circular distance between the two points

(source: https://en.wikipedia.org/wiki/Haversine_formula)
Other possible formulas

d = r * acos(sin ϕ1 sin ϕ2 + cos ϕ1 cos ϕ2 cos(λ2 - λ1)) @miles'  formula.
d = r * acos(cos(ϕ1 - ϕ2) + cos ϕ1 cos ϕ2 (cos(λ2 - λ1) - 1)) @Neil's  formula.

Example where inputs are degrees and output as rounded integer
42, 9, 50, 2  --> 284
50, 2, 42, 9  --> 284
4, -2, -2, 1  --> 203
77, 8, 77, 8  --> 0
10, 2, 88, 9  --> 2365

Rules

The input and output can be given in any convenient format.
Specify in the answer whether the inputs are in degrees or radians.
No need to handle invalid latitude/longitude values
Either a full program or a function are acceptable. If a function, you can return the output rather than printing it.
If possible, please include a link to an online testing environment so other people can try out your code!
Standard loopholes are forbidden.
This is code-golf so all usual golfing rules apply, and the shortest code (in bytes) wins.

Using that particular formula is an unobservable requirement. Isn't it enough to give the same result as that formula would give?

May we take the input in radians?

Must we round, or may we return a result with decimals?

@Adám the inputs are in degree to avoid decimal inputs

@Adám decimal with any precision or rounded integer

@Adám yes of-course, you are allowed to use any formula that gives the same result.

@mdahmoune OK, so you listed in degrees for ease of writing, but may we require input to be in radians? Otherwise this challenge becomes a combo (which is bad) of angle conversion and of the main challenge.

@mdahmoune If any formula is allowed, you should state so.

ϕ1 latitude of point 1 in radians: since the only way the angles are used are as arguments to sin, their unit doesn't matter.

@Adám you can use degrees or radian just specify in the answer whether the inputs are in degrees or radian.

I don't think this challenge will prompt varied or interesting answers. When the method of solving it is the same, you get a bunch of cookie-cutter solutions.

@mbomb007 Who says the method must be the same... | {@}mdahmoune are you still going to keep that unobservable requirement? What if our language doesn't have sine and only cosine? Can we use cosine and shift the values instead? etc.

@user202729 it is mentioned in the question that you can use any formula that gives the same result as the haversine formula.

I've downvoted this question because it seems more to be 'Who's language can golf this formula the most', which, in my opinion, isn't particularly interesting.

@cairdcoinheringaahing Of course you can use another formula...

A shorter formula for most languages would be d = r * acos( sin ϕ1 sin ϕ2 + cos ϕ1 cos ϕ2 cos(λ2 - λ1) ) where r = 1737

@miles thanks you can update the question by adding your formula if you want

@miles r * acos(cos(ϕ1 - ϕ2) + cos ϕ1 cos ϕ2 (cos(λ2 - λ1) - 1)) is shorter still in some languages.

I agree that Neil's and miles' formulas are mathematically equivalent, but the haversine formula was intended to give better precision in the cases the angles are close to each other.

Are we supposed to pretend that the Moon is spherical?  It's less oblate than Earth, but still seems wrong to simplify that much...

@TobySpeight yes, at least for this challenge

Wolfram Language (Mathematica), 48 bytes
ArcCos[Sin@#*Sin@#3+Cos[#2-#4]Cos@#*Cos@#3]1737&

Try it online!
Uses the formula d = r * acos( sin ϕ1 sin ϕ2 + cos ϕ1 cos ϕ2 cos(λ2 - λ1) ) where r = 1737

R + geosphere, 54 47 bytes
function(p,q)geosphere::distHaversine(p,q,1737)

Try it online!
Takes input as 2-element vectors of longitude,latitude in degrees. TIO doesn't have the geosphere package but rest assured that it returns identical results to the function below.
Thanks to Jonathan Allan for shaving off 7 bytes.
R, 64 bytes
function(p,l,q,k)1737*acos(sin(p)*sin(q)+cos(p)*cos(q)*cos(k-l))

Try it online!
Takes 4 inputs as in the test cases, but in radians rather than degrees.

Are the e3 and /1000 really necessary?

@JonathanAllan no they are not. That's pretty dumb of me, but the default argument for the radius is the earth's in meters so it was logical at the time, lol

Note that the spherical law of cosines is not numerically stable, in particular for small distances. That's probably ok in Mathematica, but in R and most other languages it's debatable whether the "any formula that gives the same result as the haversine formula" criterion is fulfilled.

@ceasedtoturncounterclockwis I mostly included it for the sake of having it in base R. I suppose using an arbitrary precision floating point library would mitigate the effect.

Yes, or using a stable formula like, say, the haversine formula...

APL (Dyalog Unicode), 40 35 bytesSBCS
Anonymous tacit function. Takes {ϕ₁,λ₁} as left argument and {ϕ₂,λ₂} as right argument.
Uses the formula 2 r √(sin²((ϕ₁-ϕ₂)⁄2) + cos ϕ₁ cos ϕ₂ sin²((λ₁ – λ₂)⁄2))
3474×¯1○.5*⍨1⊥(×⍨1○2÷⍨-)×1,2×.○∘⊃,¨

Try it online! (the r function converts degrees to radians)

,¨ concatenate corresponding elements; {{ϕ₁ , ϕ₂} , {λ₁ , λ₂}}
⊃ pick the first; {ϕ₁ , ϕ₂}
∘ then
2×.○ product of their cosines; cos ϕ₁ cos ϕ₂
 lit. dot "product" but with trig function selector (2 is cosine) instead of multiplication and times instead of plus
1, prepend 1 to that; {1 , cos ϕ₁ cos ϕ₂}
(…)× multiply that by the result of applying following function to {ϕ₁ , λ₁} and {ϕ₂ , λ₂}:
 - their differences; {ϕ₁ - ϕ₂ , λ₁ - λ₂}
 2÷⍨ divide that by 2; {(ϕ₁ - ϕ₂)⁄2 , (λ₁ - λ₂)⁄2}
 1○ sine of that; {sin((ϕ₁ - ϕ₂)⁄2) , sin((λ₁ - λ₂)⁄2)}
 ×⍨ square that (lit. self-multiply); {sin²((ϕ₁ - ϕ₂)⁄2) , sin²((λ₁-λ₂)⁄2)}
Now we have {sin²((ϕ₁ - ϕ₂)⁄2) , cos ϕ₁ cos ϕ₂ sin²((λ₁ - λ₂)⁄2)}
1⊥ sum that (lit. evaluate in base-1); sin²((ϕ₁-ϕ₂)⁄2) + cos ϕ₁ cos ϕ₂ sin²((λ₁ - λ₂)⁄2)
.5*⍨ square-root of that (lit. raise that to the power of a half)
 ¯1○ arcsine of that
 3474× multiply that by this

The function to allow input in degrees is:
○÷∘180

÷180 argument divided by 180
○ multiply by π

JavaScript (ES7), 90 bytes
Note: see @OlivierGrégoire's post for a much shorter solution
A direct port of TFeld's answer. Takes input in radians.
(a,b,c,d,M=Math)=>3474*M.asin((M.sin((c-a)/2)**2+M.cos(c)*M.cos(a)*M.sin((d-b)/2)**2)**.5)

Try it online!
Using the infamous with(), 85 bytes
Thanks to @l4m2 for saving 6 bytes
with(Math)f=(a,b,c,d)=>3474*asin((sin((c-a)/2)**2+cos(c)*cos(a)*sin((d-b)/2)**2)**.5)

Try it online!

You can do with(Math)f=(a,b,c,d)=>3474*asin((sin((c-a)/2)**2+cos(c)*cos(a)*sin((d-b)/2)**2)**.5)

77 bytes using @miles' shorter algorithm: (a,b,c,d,M=Math)=>1737*M.acos(M.sin(a)*M.sin(c)+M.cos(a)*M.cos(c)*M.cos(d-b))

74 bytes using @Neil's shorter algorithm: (a,b,c,d,M=Math)=>1737*M.acos(M.cos(a-c)+M.cos(a)*M.cos(c)*(M.cos(d-b)-1))

65 bytes optimizing everybody's answer: (a,b,c,d,C=Math.cos)=>1737*Math.acos(C(a-c)+C(a)*C(c)*(C(d-b)-1))

@OlivierGrégoire Very nice. You probably should post it as a new answer.

JavaScript (Node.js), 65 bytes
(a,b,c,d,C=Math.cos)=>1737*Math.acos(C(a-c)+C(a)*C(c)*(C(d-b)-1))

Try it online!
Based on Kevin Cruijssen's answer, Miles' and Neil's comments, and upon request of Arnauld.

Python 2, 95 bytes
lambda a,b,c,d:3474*asin((sin((c-a)/2)**2+cos(c)*cos(a)*sin((d-b)/2)**2)**.5)
from math import*

Try it online!
Takes input in radians.

Old version, before i/o was slacked:
Takes input as integer degrees, and returns rounded dist
Python 2, 135 bytes
lambda a,b,c,d:int(round(3474*asin((sin((r(c)-r(a))/2)**2+cos(r(c))*cos(r(a))*sin((r(d)-r(b))/2)**2)**.5)))
from math import*
r=radians

Try it online!

you can drop int and round because decimals are allowed as output, you can also avoid conversion to radians because inputs as radians are also allowed

@mdahmoune, Thanks, updated

Japt, 55 50 bytes
MsU *MsW +McU *McW *McX-V
ToMP1/7l¹ñ@McX aUÃv *#7

Not necessarily quite as precise as the other answers, but boy did I have fun with this one. Allow me to elaborate.
While in most languages, this challenge is quite straightforward, Japt has the unfortunate property that there is no built-in for neither arcsine nor arccosine. Sure, you can embed Javascript in Japt, but that would be what ever the opposite of Feng Shui is.
All we have to do to overcome this minor nuisance is approximate arccosine and we're good to go!
The first part is everything that gets fed into the arccosine.
MsU *MsW +McU *McW *McX-V
MsU                        // Take the sine of the first input and
    *MsW...                // multiply by the cos of the second one etc.

The result is implicitly stored in U to be used later.
Following that, we need to find a good approximation for arccosine. Since I'm lazy and not that good with math, we're obviously just going to brute-force it.
ToMP1/7l¹ñ@McX aUÃv *#7
T                       // Take 0
 o                      // and create a range from it
  MP                    // to π
    1/7l¹               // with resolution 1/7!.
         ñ@             // Sort this range so that
           McX          // the cosine of a given value
               aU       // is closest to U, e.g. the whole trig lot
                        // we want to take arccosine of.
                 Ã      // When that's done,
                  v     // get the first element
                    *#7 // and multiply it by 1737, returning implicitly.

We could've used any large number for the generator resolution, manual testing showed 7! is sufficiently large while being reasonably fast.
Takes input as radians, outputs unrounded numbers.
Shaved off five bytes thanks to Oliver.
Try it online!

You can remove the ( in Mc(X-V. Since the char-code for 1737 isn't ISO-8859-1, it switches to UTF-8, which costs more. You can instead use the char-code for 173+7. https://ethproductions.github.io/japt/?v=1.4.5&code=I603&input=

You can also remove the , after ToMP :-)

@Oliver Thanks a lot, the parenthesis were necessary in my original version but became obsolete when golfing it around a bit, I completely missed it though. Also, didn't know about the encoding thing, thanks a lot for that, too.

If you do want to go the JavaScript route, keep in mind that you can run everything through shoco.

Java 8, 113 92 88 82 bytes
(a,b,c,d)->1737*Math.acos(Math.cos(a-c)+Math.cos(a)*Math.cos(c)*(Math.cos(d-b)-1))

Inputs a,b,c,d are ϕ1,λ1,ϕ2,λ2 in radians.
-21 bytes using @miles' shorter formula.
-4 bytes thanks to @OlivierGrégore because I still used {Math m=null;return ...;} with every Math. as m., instead of dropping the return and use Math directly.
-6 bytes using @Neil's shorter formula.
Try it online.
Explanation:
(a,b,c,d)->                  // Method with four double parameters and double return-type
  1737*Math.acos(            //  Return 1737 multiplied with the acos of:
   Math.cos(a-c)             //   the cos of `a` minus `c`,
   +Math.cos(a)*Math.cos(c)  //   plus the cos of `a` multiplied with the cos of `c`
   *(Math.cos(d-b)-1))       //   multiplied with the cos of `d` minus `b` minus 1

"Premature optimization is the root of all evil"! 88 bytes: (a,b,c,d)->1737*Math.acos(Math.sin(a)*Math.sin(c)+Math.cos(a)*Math.cos(c)*Math.cos(d-b))

"Premature optimization is the root of all evil" I guess you're indeed right.. Thanks!

I've found a shorter formulation: (a,b,c,d)->1737*Math.acos(Math.cos(a-c)+Math.cos(a)*Math.cos(c)*(Math.cos(d-b)-1))

(That formulation isn't shorter in the original Wolfram Language though.)

Ruby, 87 70 69 68 bytes
->{extend Math;1737*acos(cos(_1-_3)+cos(_1)*cos(_3)*(cos(_4-_2)-1))}

Unfortunately, TIO doesn't support _1 syntax so for TIO, 69 bytes
->a,b,c,d{extend Math;1737*acos(cos(a-c)+cos(a)*cos(c)*(cos(d-b)-1))}

Try it online!
Now using Neil's method, thanks to Kevin Cruijssen.

Using Neil's formula is 17 bytes shorter: ->a,b,c,d{include Math;1737*acos(cos(a-c)+cos(a)*cos(c)*(cos(d-b)-1))}

Haskell, 68 66 52 51 bytes
s=cos;(a!b)c d=1737*acos(s(a-c)+s a*s c*(s(d-b)-1))

Try it online!
-1 byte thanks to BMO

Jelly,  23 22  18 bytes
-4 bytes thanks to miles (use of { and } while using their formula.
;I}ÆẠP+ÆSP${ÆA×⁽£ġ

A dyadic function accepting [ϕ1, ϕ2,] on the left and [λ1, λ2] on the right in radians that returns the result (as floating point).
Try it online!

Mine... (also saved a byte here by using a {)
,IÆẠCH;ÆẠ{Ḣ+PƊ½ÆṢ×⁽µṣ

Try it online

Oh interesting, I refreshed the page again and it showed your edit, just clicking new answer to show the change doesn't update to show your edits. the 18 byte alternative was ;I}ÆẠP+ÆSP${ÆA×⁽£ġ

Never understood how to use { and } they never do what I'd expect. Doesn't that mean I can do the other way in 17?!

Maybe. { and } just create a dyad from a monad. A similar view might be P{ -> ḷP¥. Might be good to add a compose (from J) quick to do something like x (P+$) y -> (P x) + (P y) which can save a byte or two in similar situations.

MATLAB with Mapping Toolbox, 26 bytes
@(x)distance(x{:})*9.65*pi

Anonymous function that takes the four inputs as a cell array, in the same order as described in the challenge.
Note that this gives exact results (assuming that the Moon radius is 1737 km), because 1737/180 equals 9.65.
Example run in Matlab R2017b:

Excel, 53 bytes
=1737*ACOS(COS(A1-C1)+COS(A1)*COS(C1)*(COS(D1-B1)-1))

Using @Neil's formula.  Input in Radians.

Lobster, 66 bytes
def h(a,c,b,d):1737*radians arccos a.sin*b.sin+a.cos*b.cos*cos d-c

Uses miles's formula, but input is in degrees. This adds extra step of converting to radians before multiplying by radius.

Python 3, 119 103 bytes
This uses degrees.
from math import*
def f(L):a,o,A,O=map(radians,L);return 1737*acos(cos(a-A)+cos(a)*cos(A)*(cos(O-o)-1))

Try it online!

Using Neil's formula is 16 bytes shorter: 1737*acos(cos(a-A)+cos(a)*cos(A)*(cos(O-o)-1))

C (gcc), 100 88 65 64 bytes
88 → 65 using @miles' formula
65 → 64 using @Neil's formula
#define d(w,x,y,z)1737*acos(cos(w-y)+cos(w)*cos(y)*(cos(z-x)-1))

Try it online!

I believe you need to add two bytes for the -lm compiler flag.

@O.O.Balance: The presence of the flag is not always required. It depends on how the compiler was installed on the system.

Alright. Guess this means I can subtract two bytes on this answer of mine: https://codegolf.stackexchange.com/a/161452/79343 Thanks.

@O.O.Balance: Upvoted the answer. I also submitted my own solution.

Nice. Upvoted yours as well.

Python 3, 79 bytes
from geopy import*
lambda a,b:distance.great_circle(a,b,radius=1737).kilometers

TIO doesn't have geopy.py

@Nit, my understanding is that it is fair game to use a publicly available library that predates the question.  I thinks it's like using MATLAB's mapping tools, or other languages using a math library.

APL (Dyalog Unicode), 29 bytesSBCS
Complete program. Prompts stdin for {ϕ₁,ϕ₂} and then for {λ₁,λ₂}. Prints to stdout.
Uses the formula r acos(sin ϕ₁ sin ϕ₂ + cos(λ₂ – λ₁) cos ϕ₁ cos ϕ₂)
1737×¯2○+/(2○-/⎕)×@2×/1 2∘.○⎕

Try it online! (the r function converts degrees to radians)

⎕ prompt for {ϕ₁,ϕ₂}
1 2∘.○ Cartesian trig-function application; {{sin ϕ₁,sin ϕ₂} , {cos ϕ₁,cos ϕ₂}}
×/ row-wise products; {sin ϕ₁ sin ϕ₂ , cos ϕ₁ cos ϕ₂}
(…)×@2 at the second element, multiply the following by that:
 ⎕ prompt for {λ₁,λ₂}
 -/ difference between those; λ₁ – λ₂
 2○ cosine of that; cos(λ₁ – λ₂)
Now we have {sin ϕ₁ sin ϕ₂ , cos(λ₁ – λ₂) cos ϕ₁ cos ϕ₂}
+/ sum; sin ϕ₁ sin ϕ₂ + cos(λ₁ – λ₂) cos ϕ₁ cos ϕ₂
¯2○ cosine of that; cos(sin ϕ₁ sin ϕ₂ + cos(λ₁ – λ₂) cos ϕ₁ cos ϕ₂)
1737× multiply r by that; 1737 cos(sin ϕ₁ sin ϕ₂ + cos(λ₁ – λ₂) cos ϕ₁ cos ϕ₂)

The function to allow input in degrees is:
○÷∘180

÷180 argument divided by 180
○ multiply by π

PHP, 88 bytes
Port of Oliver answer
function f($a,$b,$c,$d,$e=cos){return 1737*acos($e($a-$c)+$e($a)*$e($c)*($e($d-$b)-1));}

Try it online!

SmileBASIC, 60 bytes
INPUT X,Y,S,T?1737*ACOS(COS(X-S)+COS(X)*COS(S)*(COS(T-Y)-1))

Wolfram Language (Mathematica), 66 bytes
Clearly the other Wolfram Language golfers only care about bytes. This program uses the beauty of Mathematica.
GeoDistance@@Map[#~GeoPosition~Entity["PlanetaryMoon","Moon"]&,#]&

Either I am misusing TIO, or it doesn't work there. This works on my machine, though.

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


text:
Tidy up my bit string
I have a series of binary switches, which I can represent as a bit string. The last person who used my switches left them in some arbitrary state without cleaning up, and it bugs me. I always keep the switches in one of four possible "tidy" configurations:

All 1: e.g., 111111111
All 0: e.g., 000000000
Alternating 1 and 0: e.g., 10101010 or 01010101

However, in addition to being fastidious about my switch arrangements, I'm also very lazy, and want to extend the smallest amount of effort possible to reset the switches to one of my preferred states.
Challenge
Write a program or function that takes a sequence of ones and zeros of any length. It should output a result of the same length that shows the closest "tidy" configuration.
Input and output

You may represent your bit sequence using a string or any language-native ordered type, such as a list or array. If using a non-string structure, items within the sequence may be number or string representations of 1 and 0.

Your strings may have leading and trailing characters like "..." or [...]

Your input and output formats are not required to match. (For example, you may input a list and output a string.)
Don't input or output base 10 (or other base) representations of the bit string. That's way too much effort to correspond back to switches -- I'm doing this because I'm lazy, remember?
Output must be a sequence as specified above. Don't output an enumerated value saying which of the four configurations is the best (e.g., don't say, "solution is case #3"). Actually output a bit sequence in that configuration.
Input may be of any length. Your code may not impose arbitrary limits on the size of the input.

If your language or interpreter imposes reasonable arbitrary limits on the size of an input or call stack (e.g, if you choose a recursive solution), then this is acceptable insofar as it is a shortcoming in your environment, not your code.

Notes

The distance between two strings is the Hamming distance. You must find the "tidy" configuration of the same length at the input that has the fewest number of differences from the input.
If multiple tidy configurations are equally best choices, you may output any best choice, or (at your option) multiple best choices, delimited in some way or as siblings in a data structure. The selection can be completely arbitrary and does not need to be consistent between executions.
The input might already be a tidy state.

Examples
Input:  1111110
Output: 1111111

Input:  001010000
Output: 000000000

Input:          0010100
Allowed output: 0000000
Allowed output: 1010101
[You may choose either allowed output, or both]

Input:  1111
Output: 1111

Input:  10
Output: 10

Input:  010101101
Output: 010101010

Input:          110
Allowed output: 111
Allowed output: 010

Python 2, 127 103 101 bytes
lambda a:min(zip(*[[1,0,i%2,~-i%2]for i in range(len(a))]),key=lambda N:sum(o^b for o,b in zip(a,N)))

Try it online!
Makes the lists 111..., 000..., 101... and 010... with the first zip then finds the min of these lists with key function: sum of the xor of each element in the each possible output the input.

Python 3, 101 98 bytes
lambda s:min([p*len(s)for p in('1','0','10','01')],key=lambda l:sum(map(str.__ne__,l,s)))[:len(s)]

Try it online!

Ruby, 105 87 bytes
->s{(0..3).map{|i|("%02b"%i*z=s.size)[0,z]}.min_by{|x|("%b"%eval("0b1#{x}^0b"+s)).sum}}

Try it online!
This code constructs the four "tidy" strings by elongating the bit representations of numbers 0 to 3 to the required size, and then selects the one that gives the minimum Hamming distance to our test string.
The distance  is calculated by XORing the integer representations of strings, and in theory we should then count the number of set bits in the result. But in practice, string byte sum method works just as well, and is golfier. The only extra trick that is now necessary, is to pad one of the bit strings with an extra "1" in front: 0xb1... to prevent dropping of leading zeroes in the result, as they are important for sum.

Pyth, 21 20 19 bytes
.iFm*ld].R.OdZ.TcQ2

Input/output as a list of 0s and 1s.
Try it here
Explanation
.iFm*ld].R.OdZ.TcQ2
              .TcQ2    Separate the bits at even and odd positions.
   m                   For each part...
        .R.OdZ         ... round the average bit...
    *ld]               ... and get a list of copies of that number.
.iF                    Interleave the results.

Jelly, 22 17 bytes
JµṠ,¬;‘Ḃ,ḂƲạ³S$ÐṂ

Try it online!
Outputs all minima.

Stax, 18 bytes
æQ|jX8Å½ΓÜ\`\Δ○║á♦

Run and debug it

Ruby, 89 87 bytes
->l{[a=[0],b=[1],a+b,b+a].map{|i|i*a=l.size}.min_by{|i|l.zip(i).count{|c,d|c!=d}}[0,a]}

Try it online!

Husk, 18 bytes
ΣTm(Ṡm`K(iA)Ċ2)Set

Try it online!

Java 10, 182 179 178 170 bytes
a->{int l=a.length,b[][]=new int[4][l],i=4*l,y,r=l,R[]=a;for(;i-->0;)b[y=i/l][i%l]=y<2?y:i%l+2/y&1;for(var B:b){for(i=y=0;i<l;)y+=a[i]^B[i++];if(y<r){r=y;R=B;}}return R;}

-11 bytes thanks to @ceilingcat.
Try it online.
Explanation:
a->{                  // Method with integer-array as both parameter and return-type
  int l=a.length,     //  Length of the input-array
      b[][]=new int[4][l],
                      //  Integer matrix of 4 rows and `l` columns
      i=4*l,          //  Index integer
      y,              //  Temp integer
      r=l,            //  Result smallest difference with the input-array
      R[]=a;          //  Result-integer array
  for(;i-->0;)        //  Loop over the cells:
    b[y=i/l][i%l]=    //    Set `y` to the current cell's y-coordinate,
                      //    and fill this cell in the matrix with:
      y<2?            //     If this is the first or second row:
       y              //      Fill this cell with this 0 or 1 from `y`
      :               //     Else:
       i%l+2/y&1;     //      Fill it with `(x+2//y)%2` instead
                      //      (which is `x%2` for the third row
                      //       and `(x+1)%2` for the fourth row)
  for(var B:b){       //  Loop over the rows of the matrix:
    for(i=y=0;        //   Reset `y` to 0, and use it as sum
        i<l;)         //   Inner loop over the cells of the matrix
      y+=a[i]^B[i++]; //    Add the xor of the values at the same positions
                      //    of both the input array and current row to the sum
    if(y<r){          //   If the sum is smaller than the current smallest difference:
      r=y;            //    Set the sum as new smallest difference
      R=B;}}          //    Set the result-array `R` to the current row of the matrix
  return R;}          //  Return the resulting array with the smallest difference

Example: Input-array [0,1,0,1,0,1,1,0,1]
The first nested loop creates the following matrix, where the rows are the same length as the input:
[[0,0,0,0,0,0,0,0,0],
 [1,1,1,1,1,1,1,1,1],
 [0,1,0,1,0,1,0,1,0],
 [1,0,1,0,1,0,1,0,1]]

The second nested loops uses an XOR between each value at the same position in this row and the input-array, and sums that together:
[0^0 + 1^0 + 0^0 + 1^0 + 0^0 + 1^0 + 1^0 + 0^0 + 1^0 = 5,
 0^1 + 1^1 + 0^1 + 1^1 + 0^1 + 1^1 + 1^1 + 0^1 + 1^1 = 4,
 0^0 + 1^1 + 0^0 + 1^1 + 0^0 + 1^1 + 1^0 + 0^1 + 1^0 = 3,
 0^1 + 1^0 + 0^1 + 1^0 + 0^1 + 1^0 + 1^1 + 0^0 + 1^1 = 6]

And then it returns the row with the lowest XOR-sum, which is [0,1,0,1,0,1,0,1,0] (3) in this case.

Coconut, 75 bytes
Port of my Python answer.
s->min(map(x->x*len(s),('1','0','10','01')),key=sum..map$((!=),s))[:len(s)]

Try it online!

PHP, 117 116 bytes
for(;~$f=$argn[$i++];${1}.=0,${0}.=1,${2}.=~$i&1,${3}.=$i&1,$d[2|$f^$i&1]++)$d[$f]++;echo${array_flip($d)[min($d)]};

Run as pipe with -nR or try it online.

JavaScript (Node.js), 101 100 bytes
s=>[0,1,10,"01"].map(m=x=>[...t="".padEnd(s.length,x)].map((x,i)=>c+=x^s[i],c=0)&&m<c||(m=c,T=t))&&T

Try it online!

05AB1E, 14 13 12 bytes
dāÈ‚D≠«Σ^O}н

Port of the approach I used in my Java answer.
Try it online or verify all test cases.
Explanation:
             # Create the list of 1s the same length as the input-list:
d            #  Check for each value in the (implicit) input-list if it's non-negative (≥0)
             # Create the list of alternating 0s/1s (starting at 0):
 ā           #  Push a list in the range [1, list-length) (without popping the list)
  È          #  Then check for each whether it's even (1 if even; 0 if odd)
   ‚         # Pair the two lists together
             # Create the list of 0s and list of alternating 1s/0s (starting at 1):
    D        #  Duplicate the pair of lists
     ≠       #  And invert each boolean by checking !=1
      «      # And then merge them together to have a list of four lists
       Σ     # Sort the list of lists by:
        ^    #  XOR the values of the current inner list and (implicit) input-list
             #  (at the same positions)
         O   #  And then sum it to get the amount of 1s
          }н # And after the sorting: only leave the first list (with the smallest sum)
             # (which is output implicitly as result)

Jelly, 16 bytes
J1;Ḃ;¬$Ʋ€Z=³S$ÐṀ

Try it online!
Sort of similar to dylnan's answer, which I noticed afterwards, but I think the method is unique enough to warrant a separate answer.
Explanation
J1;Ḃ;¬$Ʋ€Z=³S$ÐṀ  Main Link
J                 Range from 1 to len(z)
        €         For each element
       Ʋ
 1                1
  ;Ḃ              [1, k % 2]
    ¬$            Append the logical NOT of the list ([1, k%2, 0, !k%2])
         Z        Zip (basically, it generates a 4-long list per element, and then transposes it into the four lists)
              ÐṀ  Take the maximum element via
          =³S$    the number of matching elements (pairwise-equality into sum)


text:
Sorting Algorithms for Physical Process
Not sure if this is the correct community to post this is. But as I see this problem as an interesting puzzle to solve, I'd thought to give it a shot...
Problem Statement:
Let`s say we have:

N collections of parts: A, B,C,D,...etc
Each collection consists of n parts: 1,2,3,4,5 ...
All these parts are  randomly present in an input buffer:

B1, C5, D2,A4,A2, etc
The aim now is to sort all parts into their collections, and make sure that in each collection the parts are ordered correctly.
A desired output would be: A1,A2,A3,A4,A5 B1,B2,B3,B4,B5, ..etc
This will be a physical process in which the parts are sheets of material. This gives some real world constraints:

A sorting and output buffer of Nb locations is available.
On each of the buffer locations multiple sheets can be stacked.
To retrieve one particular sheet, all sheets that are placed on top of it need to be moved (and temporarily stored in another location). This takes physical effort + time and should therefor be minimized.
It is not possible to move a correctly ordered subset of a collection at once. This would involve picking up each sheet individually from it's stack.
Once a collection is completely sorted and ordered, it can be removed from the buffer.

The question:
I am getting to grips with the logic of this sorting and ordering problem. Some initial questions I have asked myself, and you might find interesting to think about/test/simulate.

For a given input (N, n) what is an efficient number of buffer locations (Nb)?
What should be the sorting logic in this problem? Which rules would work when N scales to max. 30 and n to max. 150
Does anyone have sources (papers, articles, algorithms, etc) on this type of problem?
What aspect of the system should be changed to make the sorting more efficient? For instance what would be the benefit of being able to physically move a subset of a collection at once, while maintaining it's ordering.

I was struggling with clearly writing down the specifics of this sorting and ordering problem, if something is unclear, let me know so I can provide more info.
Thanks!!

I think this is too open-ended as a puzzle or challenge for here. Maybe you could post in on CS theory? I'd suggesting focusing down to a narrower question scope.

"what is an efficient number of buffer locations": For Max N=30 and max n=150, Nb of 30*150 = 4500 will result in "fastest" sorting (Count-sort). Are buffer locations Nb expensive?

Welcome to PPCG! This is indeed interesting (makes me think of pancake sorting). One thing to note is that this would require a winning criteria here (looks like some kind of minimisation of the measure of physical effort and/or time which you mention but do not quantify). On another note, should (4) read "It is not possible to move an incorrectly ordered subset"?

Welcome to PPCG, I hope you stick around. Just to let you know, this site has a sandbox that can help you refine your challenges before you post them


text:
Digit Occurrences
Input:
A list of integers (which will never contain a zero)
Output:
A list of the same size with counts based on the following:

If the current item is negative: Look at all items before this item, and count how many times the digits occurred in those other numbers
If the current item is positive instead: Look at all items after this item, and count how many times the digit occurred in those other numbers

There is one twist: If the size of the list is even we only count every number once (even if it matches multiple digits), and if the size is odd we count every digit of the numbers for each digit of the current item (duplicated digits are counted multiple times).
Let's give some examples to clarify this a bit:
Example with even list:
Input:  [4, 10, 42, -10, -942, 8374, 728, -200]
Output: [3, 2,  4,  1,   2,    1,    1,   5   ]

Size of the list is even, so we only count each number once.

4: It's positive, so we look forward. There are three numbers containing the digit 4 (42, -942, 8374). So we start with a 3.
10: It's positive, so we look forward. There are two numbers containing either the digit 1 and/or 0 (-10, -200). So the second output is 2.
42: Again positive, so forward. There are four numbers containing either the digit 4 and/or 2 (-942, 8374, 728, -200). So the third output is 4.
-10: This time it's negative, so we look backwards. There is only one number containing the digit 1 and/or 0 (we ignore the minus sign) (10). So the fourth output is 1.
etc.

Example with odd list:
Input:  [382, -82, -8, 381, 228, 28, 100, -28, -2]
Output: [13,  2,   2,  4,   8,   3,  0,   11,  6 ]

Size of the list is odd, so we count every digit.

382: It's positive, so we look forward. There is one 3 in the other numbers (381), six 8's in the other numbers (-82, -8, 381, 228, 28, -28), and six 2's in the other numbers (-82, 228, 28, -28, 2). So we start with a 13.
-82: It's negative, so backwards. There is one 3 in the other number (382), and one 8 in the other number (382). So the second output is 2.
...
228: It's positive, so forward. There are three 2's in the other numbers (28, -28, -2), and another three 2's, and two 8's in the other numbers (28, -28). So this output is 8.
etc.

Challenge rules:

You can assume the input will never contain 0 as item, since it's neither positive nor negative.
You can assume the input-list will always contain at least two items.
I/O is flexible. Input/output can be array/list of integers, delimited string, digit/character-matrix, etc.
If the first number in the list is a negative number, or the last number in the list is a positive number, it will be 0 in the resulting list.
With odd lists, numbers containing the same digit multiple times are counted multiple times, like the 228 in the odd example above resulting in 8 (3+3+2) instead of 5 (3+2).

General rules:

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

Test cases:
Input:  [4, 10, 42, -10, -942, 8374, 728, -200]
Output: [3, 2,  4,  1,   2,    1,    1,   5   ]

Input:  [382, -82, -8, 381, 228, 28, 100, -28, -2]
Output: [13,  2,   2,  4,   8,   3,  0,   11,  6 ]

Input:  [10, -11, 12, -13, 14, -15, 16, -17, 18, -19]
Output: [9,  1,   7,  3,   5,  5,   3,  7,   1,  9  ]

Input:  [10, -11, 12, -13, 14, -15, 16, -17, 18, -19, 20]
Output: [11, 2,   8,  4,   5,  6,   3,  8,   1,  10,  0 ]

Input:  [88, 492, -938, 2747, 828, 84710, -29, -90, -37791]
Output: [8,  9,   3,    9,    3,   4,     5,   4,   12    ]

Input:  [-1, 11, 11, 1]
Output: [0,  2,  1,  0]

Input:  [1, 11, 11, -1]
Output: [3, 2,  1,  3 ]

Input:  [-1, 11, 1]
Output: [0,  2,  0]

Input:  [1, 11, -1]
Output: [3, 2,  3 ]

05AB1E, 30 bytes
vy0›iNƒ¦}ëN£}€Sþyδ¢IgÈiĀ€Ù}OOˆ

Try it online!

δ¢, never seen double-vector used well, nice one.

Python 2, 149 148 121 116 111 107 bytes
lambda l:[sum([any,sum][len(l)%2](map(`n`.count,`abs(v)`))for n in l[:i:2*(v<0)-1])for i,v in enumerate(l)]

Try it online!

Java (JDK 10), 204 bytes
a->{int l=a.length,r[]=new int[l],i=0,j,x,y,b,s,t=10;for(;i<l;i++)for(j=i+(s=a[i]>0?1:-1);0<=j&j<l;j+=s)for(b=0,x=a[i];x!=0;x/=t)for(y=a[j];b<1&y!=0;y/=t)if(x%t==-y%t|x%t==y%t){r[i]++;b+=1-l%2;}return r;}

Try it online!
Credits

-6 bytes thanks to Kevin Cruijssen
-1 byte thanks to Java Gonzar

[1,11,-1] should return [3,2,3]. It's an odd list, so all digits count. First 1: Look forward, three 1s in total: 11,-1. Second 11: Look forward for each digit: one 1 + one 1. Third -1: Look backward, three 1s in total: -1,11. (With odd lists you should look at each digit, even the same. I'll clarify this in the challenge, but the odd example with number 228 clarifies this a bit.)

@KevinCruijssen Should be fixed now.

It indeed does. I was already afraid the initial explanation might have been a bit too unclear when I posted it.. Now I'll see if I can golf anything of your answer. ;)

@KevinCruijssen It's very likely golfable: I made the strict minimum in it given the complexity of the answer. Plus I have to leave now

I don't have a lot of time either, but one thing you can golf is adding a new variable ,t and changing i+(a[i]>0?1:-1) to i+(t=a[i]>0?1:-1), and then simply use j+=t instead of j+=a[i]>0?1:-1.

You can save 2 if you declare for example t=10 and replace all those 10 for t, although it will be less understandable

@JavaGonzar Thank you! Though I only saved a byte. The goal here is not to be understandable but to make it run in as few bytes as possible, so yeah, any byte is a win even if it's not legible.

Forgot you had to add a colon, happy to help anyway :)

@ceilingcat the result isn't correct.

Suggest b-=x%t==-y%t|x%t==y%t?~l%2+0*r[i]++:0 instead of if(x%t==-y%t|x%t==y%t){r[i]++;b+=1-l%2

Perl 6, 100 85 bytes
{.kv.map:{sum map (?*,+*)[$_%2],.[grep (*-$^i)*$^v>0,^$_].map:{.comb⊍$v.abs.comb}}}

Try it online!
Uses the baggy multiplication operator ⊍.

Perl 5 -n, 92 bytes
($t=$&>0?$':$`)&say$q=y/ //%2?@a=$t=~/\b\d*[$&]+\d*\b/g:map$t=~/$_/g,$&=~/\d/g while/-?\d+/g

Try it online!

JavaScript (Node.js),164,158,140 139 bytes
a=>a.map((x,i)=>a.slice(x<0?0:i+1,x<0?i:l).map(b=>c+=[...b+""].map(X=>s+=X>=0&&(x+"").split(X).length-1,s=0)&&l%2?s:+!!s,c=0)|c,l=a.length)

Try it online!

This looks like JS6, not anything Node-y.

this is tio generated string. it has either Node Babel or SpiderMonkey JS. it still works on node so its fine

Jelly, 43 42 bytes
>0ị"ḊÐƤżṖƤƊAṾ€€FċÐ€¥e€€³LḂ©¤?"AṾ$€SṀ€S$®?€

Try it online!

Ruby, 126 bytes
->l{k=l.map{|i|i.abs.digits};c=-1;k.map{|n|x=k[l[c+=1]<0?0...c:c+1..-1];x.sum{|j|x=n.sum{|d|j.count d};l.size%2<1?x<1?0:1:x}}}

Try it online!


text:
Distance between the Sun and the nth planet
Challenge
Predict the distance between the Sun and the nth planet when using any formula that gives the same result as the Titius–Bode law: d=(3*2^n+4)/10.
BUT WAIT... there is one restriction:

Your source code can not include any of the Titius–Bode law's digits
So, your program can not contain the characters 0, 1, 2, 3, or 4

Input
n a non-negative integer value:

For Mercury n is -∞ no need to handle this case.
n=0 for Venus
n=1 for Earth
n=2 for Mars, and so on ...

Output
Distance in astronomical unit between the Sun and the nth planet (decimal with at least one decimal place).
Titius–Bode law
Distance in astronomical unit between the Sun and the nth planet is estimated by d=(3*2^n+4)/10.
Example
0          --> 0.7
1          --> 1.0 or 1
11         --> 614.8

Rules

The input and output can be given in any convenient format.
No need to handle invalid input values
Either a full program or a function are acceptable. If a function, you can return the output rather than printing it.
If possible, please include a link to an online testing environment so other people can try out your code!
Standard loopholes are forbidden.
This is code-golf so all usual golfing rules apply, and the shortest code (in bytes) wins.

The inputs and results you show do not match the formula.

@JeffZeitlin Thanks I just corrected the question

Hi, I've downvoted this challenge as it's basically a Do X without Y challenge without much room for creative golfing.

@AdmBorkBork About "Do X without Y", yes. About "creative golfing", I'm not sure. Let's just see how the answer goes.

@Lynn it's done

I originally downvoted this challenge as I agree with AdmBorkBork's statement (and I still do), but have reverted that downvote simply because of the fun I had making my Whispers solution.

"The number 3 is cursed.  Avoid it."

05AB1E, 7 bytes
oxOÌÌT/

Try it online!
Explanation
o          # push 2^input
 x         # pop a and push a, 2*a
  O        # sum stack
   ÌÌ      # add 2 twice
     T/    # divide by 10

literally. my. exact. solution.

C (gcc), 22 bytes
-Df(x)=((6<<x)+8.)/''

Try it online!

I recommend to comment that there is a special character between ''  Perhaps it is 'x14'?

Looks like that -D is setting type to double? it seems to work on variable declarations too. I've never seen it before, where is it documented, and what other types are available? It's difficult to google and I can't find it on the PPCG tips for golfing in C question.

@LevelRiverSt -D looks like a compile time define in OP's "Try it online!"  Nothing to do with double.

@chux it seems you are correct. It would seem though, that this code would be more accurately described as a gcc command line option, rather than C. Certainly shorter than #define in the source file. Google found it documented at https://www.rapidtables.com/code/linux/gcc/gcc-d.html

@LevelRiverSt It's pointed in meta

Haskell, 29 28 27 25 bytes
s=9-7
d n=(6*s^n+8)/5/s/s

Nothing special, I'm afraid. All allowed digits exactly once!
Try it online!

JavaScript (Node.js), 20 19 bytes
n=>((6<<n)+8)/5/~-5

Try it online!

JavaScript (ES6), 20 bytes
Saved 2 bytes thanks to @l4m2
Does not support Mercury.
n=>(5-9-(9-6<<n))/~9

Try it online!

JavaScript (ES7), 27 bytes
Supports Mercury.
n=>(k=5,--k+--k*--k**n)/-~9

Try it online!

9**.5 => 9-6

Java 8, 20 18 bytes
n->((6<<n)+8f)/''

Port of l4m2's C answer, thanks to Kevin Cruijssen. Try it online here.
Java 8, 30 24 bytes
n->(9-5+(9-6<<n))/(5f+5)

My original approach; admittedly, it's not very creative. Try it online here.
Thanks to Kevin Cruijssen for golfing 6 bytes.

-4 bytes by creating a port of l4m2's JavaScript answer: n->((6<<n)+8)*-.5/~9 (result is a double instead of a float now).

-2 more bytes by changing *+8)-.5/~9 to +8f)/''. (unprintable ASCII with value 20). Try it online. Credit to l4m2 again, this time his C answer.

@KevinCruijssen What's the point of the "unprintable ASCII with value 20"? Type 20 instead and it just works. Oh, and it's 1 byte shorter...

Oh... Didn't see the restriction. Sorry...

@OlivierGrégoire Np. I made the same mistake on someone else's answer at first, suggesting /2 instead of *.5. :)

Jelly,  14  8 bytes
-3 thanks to miles (use of æ«, bit-shift) ..and -3 more by golfing from there
6æ«+8H÷⁵

Try it online!
How?
6æ«+8H÷⁵ - Link: number, N (including -inf)
6        - literal six
 æ«      - bit-shift = 6*(2^N)
   +8    - add eight = 6*(2^N)+8
     H   - halve = 3*(2^N)+4
       ⁵ - literal ten
      ÷  - divide = (3*(2^N)+4)/10

Isn't something incredibly boring like “¤‘æ«+“¥‘÷⁵ a valid solution too?

Hadn't thought of bitshift, so probably

...yep that and more, thanks :)

dc, 18 17 bytes
zzrkr^zz+*8z/+A/p

Try it online!
Assuming n is all that's on the stack, we get the stack depth twice to push 1 and 2 onto the stack. Reverse these and use the 1 to set our precision (k). Reverse so that our stack is now 2 n, exponentiate (^). Use z to get stack depth twice, again pushing 1 and 2 onto the stack. Add them (+) to get 3, multiply (*) by our previous result. Push 8, get the stack depth with z to push 2, divide these (/) to push 4. Add this (+) to the previous result, and divide by 10 (A/). Finally, print.
Knocked off a byte using 8z/ instead of zF+v to make a 4.

Retina 0.8.2, 54 42 35 bytes
.+
@@@$&$*_@@@@
+`@_
_@@
M`@
.$
.$&

Try it online! Link includes test cases. Edit: Saved 12 bytes thanks to @Leo. Explanation:
.
@@@$&$*_@@@@

Generate a pseudo-binary number using @ as 1 and _ as *2, having 3 as the first digit and 4 as the last digit, thus representing 3*2^n+4.
+`@_
_@@

Convert to unary.
M`@

Convert to decimal.
.$
.$&

Divide by 10.

I think you need .+ on the first line, otherwise it won't work on numbers higher than 9. I see a couple of possible golfs: 1) you can save 1 byte by triplicating each @ and then appending four more @ instead of doing it all at once. 2) To divide by 10 you can just convert to decimal and then insert the point before the last digit. Try it online!.
(By the way, you could convert it to Retina 1 by changing $*_ to * and M to C)

@Leo Whoops, I was really overthinking that decimal conversion, thanks! You also inspired me to find an even better way of multiplying by three and adding four. But I hadn't realised we needed to support that many planets; I don't even know of a solar system with that many.

Yeah, the number of planets is a bit weird, but one of the test cases is 11... Anyway, your 3*2^n+4 algorithm is amazing, nice work!

Google Sheets, 27 26 25 23 bytes
=((8-5)*(7-5)^A5+9-5)/(5+5)
=(9^.5*(7-5)^A5+9-5)/(5+5)
=(9^.5*(7-5)^A5+9-5)*.7/7
=(7-5)^A5*(.8-.5)+.9-.5

Take input from cell A5.
For a no-digit version (except the A5 is unavoidable),
=(code("")*code("")^a5+code(""))/code("

(there is a trailing newline)

How is A5 unavoidable?

Whispers v2, 325 bytes
> 8
> 8
> 8
> 8
> 9
> 6
> Input
>> 5-6
>> 5-55
> 8
> 8
> 8
> 8
> 8
> 8
> 8
> 8
> 8
> 8
> 8
> 8
> 8
> 8
> 8
> 8
> 8
> 8
> 8
> 8
> 8
> 8
> 8
> 8
> 8
> 8
> 8
> 8
> 8
> 8
> 8
> 8
> 8
> 8
> 8
> 8
> 8
> 8
> 8
> 8
> 8
> 8
> 8
> 8
> 8
> 7
>> 9+9
>> 9*7
>> 55-56
>> 57⋅58
> 8
> 8
> 8
> 8
> 8
>> 58+55
>> 59+56
>> 66÷65
>> Output 67

Try it online!
Let me outline the problem with using Whispers:
Whispers is a single-expression, line-based programming language. Each line consists of a single mathematical expression. However, if the line starts with >>, the numbers used have different values to what they would normally express.
When a line begins with > (such as > 8) the value returned is the number shown, so that example would return 8 when referenced. Input returns an evaluated line from STDIN.
However, when the line starts with >>, such as >> 5-6, the numbers are interpreted as line references, i.e. the above line would call line 5, then line 6, then subtract the results.
Let's create a program that half-sticks to the rules first. This program doesn't use 0, 1, 2, 3, or 4 to represent those numbers, but does use them as line references. This 'half' solution is 96 bytes:
> 6
> 9
> Input
>> 2-1
>> 1=1
>> 4-5
>> 6*3
>> 7⋅4
>> 6+6
>> 8+9
>> 2+5
>> 10÷11
>> Output 12

Try it online!
Unfortunately, the challenge disallows the characters 0, 1, 2, 3, and 4 from appearing in the program, irregardless of what they represent. So, to work around this, we have to use line references with only the numbers 5, 6, 7, 8 and 9 in their digits. This has the consequence that we cannot use any lines between 10 and 54, which is what the massive chain of > 8 are. In fact, all lines that represent a forbidden line reference has > 8, just for consistency.
So, let's remove those lines, but pretend they're still there, we just can't see them:
> 9
> 6
> Input
>> 5-6
>> 5-55
> 7
>> 9+9
>> 9*7
>> 55-56
>> 57⋅58
>> 58+55
>> 59+56
>> 66÷65
>> Output 67

Which is a very similar structure to the 'half' solution. Here's how this shortened solution works, with an input 11:
> 9		; Line  5: Yield 9
> 6		; Line  6: Yield 6
> Input		; Line  7: Yield a line of input (11)
>> 5-6		; Line  8: Yield 3 	-	9 - 6
>> 5-55		; Line  9: Yield 2	-	9 - 7
⋮
> 7		; Line 55: Yield 7
>> 9+9		; Line 56: Yield 4	-	2 + 2
>> 9*7		; Line 57: Yield 2048 	-	2 ^ 11
>> 55-56	; Line 58: Yield 3	-	7 - 4
>> 57⋅58	; Line 59: Yield 6144	-	2048 ⋅ 3
⋮
>> 58+55	; Line 65: Yield 10	-	3 + 7
>> 59+56	; Line 66: Yield 6148	-	6144 + 4
>> 66÷65	; Line 67: Yield 614.8	-	6148 ÷ 10
>> Output 67	; Line 68: Output 614.8

><>, 27 bytes
l$:?!vll-+$:+!
:*lrl<;n,a+l

Try it online!
Some heavy abuse of the stack length command (l) command here. Luckily, most of the numbers needed are in ascending order. Takes input through the -v flag

Don't you need to add a byte for the flag?

Just now saw your other comment. If that's the convention now I will gladly use it.

@Hohmannfan For reference, here's the meta question where it was decided that command line flags are now free

Raku, 13 bytes
³+<*/Ⅹ+⅖

Try it online!
This formula uses Unicode characters with the right numeric values to stand in for the forbidden characters.

³ - SUPERSCRIPT THREE - value = 3
Ⅹ - ROMAN NUMERAL TEN - value = 10
⅖ - VULGAR FRACTION TWO FIFTHS - value = 0.4

Python 3, 27 26 bytes
lambda n:((6-9<<n)-~-5)/~9

Try it online!

Python 2, 38 34 31 28 27 bytes
lambda n:((6-9<<n)-9.+5)/~9

Try it online!

Saved:

-4 bytes, thanks to Giuseppe
-1 byte, thanks to Jonathan Allan

f(0) gives 0.55 instead of 0.7?

@mdahmoune Fixed

use negative numbers to save a byte: lambda n:((6-9<<n)-~-5)/~9

Symbolic Python, 69 56 bytes
___=_==_
__=-~___
_=__**~-_*-~__+___+___**-___
_/=__-~__

Try it online! Implements (3*2^(n-1)+2)/5
How?
# Input is stored in _ initially

___=_==_         # ___ = True (=1)
__=-~___         # __  = -~1 = 1 + 1 = 2
_=__**~-_*-~__+___+___**-___
# _ = 2**~-_ * -~2 + 1 + 1**-1 = 2**(n-1) * 3 + 1 + 1.0 = 3 * 2**(n-1) + 2.0
_/=__-~__        # _   = _ / (2 -~ 2) = _ / (2 + -~2) = _ / (2 + 2+1) = _ / 5

# Implicit output of _

Never thought I'd actually see someone submit an answer in this stupid esolang I decided to make!

Mathics, 34 bytes
d[n_]:=((9-6)*(8-6)^n+(9-5))/(5+5)

Try it here!
My first time golfing in Mathics, so there's probably a bit more optimizing to be done.

((9-6)(8-6)^#+(9-5))/(5+5)&

Jelly, 14 12 bytes
‘⁺
¢*+Ḥ$Ç⁺÷⁵

Try it online!
About time for an explanation
How it works

‘⁺        - Helper link. Can be called monadically, or niladically.
          - When called niladically, `0` is the left argument.
 ⁺        - Perform the previous command twice:
‘         -   Increment the left argument

¢*+Ḥ$Ç⁺÷⁵ - Main link. 1 argument: n
¢*        - Yield 2n
    $     - Perform the next two commands on 2n:
   Ḥ      -   Halve.           Yields 2n-1
  +       -   Add to 2n.       Yields 3⋅2n
     Ç    - Add 2.             Yields 3⋅2n + 2
      ⁺   - Add 2 again.       Yields 3⋅2n + 4
        ⁵ - Yield 10
       ÷  - Divide by 10.      Yields (3⋅2n + 4)/10

Stax, 7 bytes
â╬╫▓♠âε

Run and debug it
PackedStax source encoding makes the character restrictions trivial.  Unpacked, ungolfed, and commented this is the same program.
|2  2 to the power
3*  multiply by 3
4+  add 4
A/  divide by 10

Run this one

BRASCA, 29 bytes
ig$}}:a$^A}:a*A}+:l/ml%mn'.on

Try it!
BRASCA only supports whole integers, so I had to spend a couple bytes to at least get one decimal, to pass the test cases.
Explanation
                               - Implicit input
ig                             - Turn 0-9 into the actual numbers and concatenate
  $}}:a$^                      -    2^n
         A}:a*                 - (3*
              A}+              -       +4)
                 :l/           -          /10
                    ml%mn'.on  - Get the first decimal, and print the number.

MathGolf, 8 bytes
ó∙☻√ΓΣ♂/

Try it online.
Actually the same amount of bytes as the straight-forward approach without restricted-source:
ó3*4+♀√/

Try it online.
Explanation:
ó         # Take 2 to the power of the (implicit) input-integer
 ∙        # Triplicate it
  ☻       # Push 16
   √      # Take the square-root of that: 4.0
    Γ     # Wrap the four values on the stack into a list
     Σ    # Sum this list together
      ♂/  # Divide it by 10
          # (after which the entire stack is output implicitly as result)

ó         # Take 2 to the power of the (implicit) input-integer
 3*       # Multiply it by 3
   4+     # Add 4
     ♀√/  # Divide it by the square-root of 100 (10.0),
          # since `/` will be integer-division if both arguments are integers
          # (after which the entire stack is output implicitly as result)

C# .NET, 18 bytes
n=>((6<<n)+8f)/''

'' is an unprintable ASCII character with value 20.
Port of @l4m2's C answer.
Try it online.

Ruby, 25 bytes
->n{6-5.6+6%5.7*(9-7)**n}

Try it online!
Output ±ε due to float imprecision.

Whispers v2, 91 bytes
> Input
>> 9*56
>> 57⋅8
>> 58+7
>> 59÷6
> 5
>> ≺6
>> ≺7
>> ≺8
>> 5÷9
>> Output 65

Try it online!

PowerShell, 38 bytes
(.9-.6)*[math]::pow(8-6,"$args")+.9-.5

Try it online!
-11 bytes thanks to @mazzy

38 bytes.

Lua, 55 bytes
o=#" "t=o+o function x(m)return((o+t)*t^m+t^t)/(5*t)end

Try it online!

Scala, 41 bytes
A port of @O.O.Balance's answer.
Try it online!
val d:Int=>Float=n=>(9-5+(9-6<<n))/(5f+5)

Stax, 8 bytes
à╙i;?«°☻

Run and debug it
I think this is a little bit unfair because the original code contains digits, but PackedStax doesn't... here's what it unpacks to:
Stax, 9 bytes
|23*4+A:_

Run and debug it
|23*4+A:_
|2        # 2**n
  3*      # *3
    4+    # +4
      A:_ # float divided by 10

Vyxal, 6 bytes
ET⇧⇧₀/

Try it Online!
₀ != 0
Explained
ET⇧⇧₀/
E      # 2 ** n
 T     # * 3
  ⇧⇧   # + 2 + 2
    ₀/ # divided by 10

Thunno 2, 8 bytes
ODḌ+ƙƙT/

Port of Emigna's 05AB1E answer.
Explanation
ODḌ+ƙƙT/  # Implicit input
O         # Push 2 ** input
 DḌ       # Duplicate and double
   +      # Add (triple)
    ƙƙ    # Add 2 twice (add 4)
      T/  # Divide by ten
          # Implicit output

Screenshot:

Pip, 13 bytes
U(U Ea*@PI)/t

Contains no digits at all. Attempt This Online!
Explanation
Uses a slightly modified formula:
$$\frac{3\cdot(2^n+1)+1}{10}$$
U(U Ea*@PI)/t
     a         ; Command-line input
    E          ; 2 to that power
  U            ; Increment
      *        ; Times
       @PI     ; the first character of pi
U(        )    ; Increment that result
           /t  ; Divide by 10

x86 machine code, 21 20 bytes
6a 03                   push   0x3
58                      pop    eax
d3 e0                   shl    eax,cl
04 04                   add    al,0x4
50                      push   eax
db 04 24                fild   DWORD PTR [esp]
6a 0a                   push   0xa
de 74 24 00             fidiv  WORD PTR [esp+0x0]
58                      pop    eax
58                      pop    eax
c3                      ret

Pretty straightforward, except for two little details:

It's enough to add 4 to al - adding it to eax is 1 byte longer
[esp+0x0] - explicit displacement equal to 0 is needed to avoid the forbidden byte 0x34 (ASCII 4) in the instruction's encoding; thanks to l4m2 for the idea!

6A 03 58 D3 E0 04 04 50 DB 04 24 6A 0A DE 74 24 00 58 58 C3?

6A 03 58 D3 E0 04 04 50 89 E7 DB 07 58 6A 0A DE 37 58 C3 with edi changed

Might work with a suitable calling convention; I only know how to work with fastcall though, on MS Windows.


text:
Alphabet Histogram
Given an input sentence consisting of one or more words [a-z]+ and zero or more spaces , output an ASCII-art histogram (bar graph) of the letter distribution of the input sentence.
The histogram must be laid out horizontally, i.e. with the letter key along the bottom in alphabetical order from left to right, with a Y-axis labeled 1- and every 5 units. The Y-axis must be the smallest multiple of five that is at least as tall as the tallest bar, and must be right-aligned. The X-axis is labeled with the input letters, with no gaps between. For example, input a bb dd should have label abd and not ab d, skipping the c. The bars themselves can be made of any consistent ASCII character -- I'll be using X here in my examples.
test example

5-

   X
   X   X
1-XXXXXXXX
  aelmpstx

Since there are three e, two t, and one of almsx.
More examples:
the quick brown fox jumped over the lazy dogs

5-
      X         X
      X         X
     XX  X      X  X XX
1-XXXXXXXXXXXXXXXXXXXXXXXXXX
  abcdefghijklmnopqrstuvwxyz

now is the time for all good men to come to the aid of their country

10-
              X
              X
              X  X
      X       X  X
 5-   X       X  X
      X   X   X  X
      X  XX XXXX X
   XXXXX XXXXXXX X
 1-XXXXXXXXXXXXXXXXXX
   acdefghilmnorstuwy

a bb ccc dddddddddddd

15-

      X
      X
10-   X
      X
      X
      X
      X
 5-   X
      X
     XX
    XXX
 1-XXXX
   abcd

a bb ccccc

5-  X
    X
    X
   XX
1-XXX
  abc

I/O and Rules

Input can be taken in any reasonable format and by any convenient method. This also means you can take input in all-uppercase, if that makes more sense for your code.
Leading/trailing newlines or other whitespace are optional, provided that the characters line up appropriately.
Either a full program or a function are acceptable. If a function, you can return the output rather than printing it.
Output can be to the console, returned as a list of strings, returned as a single string, etc.
Standard loopholes are forbidden.
This is code-golf so all usual golfing rules apply, and the shortest code (in bytes) wins.

I think this would be a bar graph rather than a histogram, as it's categorical rather than numeric data, but I'm mostly being pedantic.

is the input guaranteed to be non-empty?

@dzaima Yes, the input is guaranteed non-empty. There will be at least one word.

To confirm, we can't go up to, say, 15 lines in the first example and include y axis markers for 10 and 15, right?

@dylnan Right. The Y-axis should only be large enough to contain the data.

@dylnan No, not necessarily. The input could consist of only one word without any spaces.

Just being a pendant, but this isn't a histogram, it's a bar chart. Still a nice challenge though!

"Leading/trailing newlines or other whitespace are optional, provided that the characters line up appropriately." -- so columns of whitespace are acceptable?

@JonathanAllan If you're asking if you could do something like abc e for the columns, no that's not okay. If you have a whole leading column of whitespace (e.g., a leading space on every line), that's fine.

I was asking for a d e h style rather than a  de  h

@JonathanAllan The letters must be adjacent. I'll make that explicitly clear.

Maybe add test cases that test extension of the Y-axis at the right points, i.e. with 10 and with 11?

Can the y-axis labels be left-aligned?

@MagicOctopusUrn Nope, right-aligned. That's just the rules. ;-)

Does the X axis need to be sorted?

A Tuftian approach would be to make the bars out of the characters represented and not have a separate label row.

@dmckee For some cases that could be golfier too! :P

Related, but only in the output style.

The histogram character has to be consistent, but across cases or within each case?

@Adám It needs only be consistent within the same case. If it's different on subsequent runs, or different inputs, that's fine. I just don't want a mishmash of characters so you can't understand the graph.

a quick brown fox jumpest over a lazy dog has fewer extra letters.

R, 239 230 bytes
K=table(el(strsplit(gsub(" ","",scan(,"")),"")));m=matrix(" ",L<-sum(K|1)+1,M<-(M=max(K))+-M%%5+1);m[2:L,M]=names(K);m[1,M-g]=paste0(g<-c(1,seq(5,M,5)),"-");m[1,]=format(m[1,],j="r");for(X in 2:L)m[X,M-1:K[X-1]]=0;write(m,1,L,,"")

Try it online!
table does the heavy lifting here, uniquifying the characters, sorting them, and returning their counts.
Everything else is just ensuring the offsets are right for printing, which is the "real" work of an ascii-art challenge.
Thanks to @dylnan for pointing out a bug.
Thanks to @rturnbull for the scan approach, dropping 2 bytes.

237 bytes

@rturnbull I managed to knock off a few more bytes after that, thanks!

Stax, 37 bytes
ü╣úwóΓµ┐Wh0íJ▌Ñìs┤►ï╖öz<à↔/Ü@τ|:╢Ω$‼φ

Run and debug it

gnu sed -r, 516 490 278 249 + 1 bytes
s/$/:ABCDEFGHIJKLMNOPQRSTUVWXYZ /
:a
s/(.)(:.*\1)/\2\1/I
ta
s/[A-Z]+/ /g
h
z
:b
s/ \w/ /g
G
s/:/&I/g
/:II{5}+ *$/M!bb
s/[a-z]/X/g
G
s/:(I{5}+|I)\b/0\1-/g
s/:I*/  /g
s/ (\w)\1*/\1/g
s/$/; 10123456789I0/
:c
s/(.)I(.*\1(I?.))|;.*/\3\2/
/\nI/s/^/ /Mg
tc

Try it online!

I am sure this can be improved, but for now, this should be good considering it is made in sed, where you don't have native arithmetic or sorting. So I lied, this wasn't good enough, so I improved (rewrote) it by another 212 bytes, with a tip regarding the sorting algorithm from Cows quack, which gave me a idea to make the unary to decimal conversion shorter too.
Description of inner workings:
s/$/:ABCDEFGHIJKLMNOPQRSTUVWXYZ /
:a
s/(.)(:.*\1)/\2\1/I
ta
s/[A-Z]+/ /g
h
z

This sorts the input and separates the groups with spaces. This works by first appending an uppercase alphabet plus space separated by a colon to the end. Then it moves each character in front of the colon to a matching character behind the colon using a case-insensitive substitution in a loop. The uppercase letters are then replaced by spaces and the string is copied to the holding space.
:b
s/ \w/ /g
G
s/:/&I/g
/:II{5}+ *$/M!bb

This loop works by reducing each character group size by one, appending the sorted original line and incrementing unary counters after the colon that remained from the sorting. It loops until an empty line with a number of 5*n + 1 is reached (since the last line ultimately results in whitespace). The pattern space looks something like this after the loop:
:IIIIII
:IIIII
:IIII
:III  e
:II  ee     t
:I a eee l m p s tt x

Then the formatting follows:
s/[a-z]/X/g            # makes bars consistent
G                      # appends line that becomes x-axis
s/:(I{5}+|I)\b/0\1-/g  # moves zero in front of line 1 or 5-divisible
                       # lines for the decimal conversion and adds -
s/:I*/  /g             # removes numbers from other lines
s/ (\w)\1*/\1/g        # collapses groups of at least 1 into 1
                       # character, deleting the space before it
                       # so that only size-0-groups have spaces

And finally, the unary to decimal converter remains:
s/$/; 10123456789I0/
:c
s/(.)I(.*\1(I?.))|;.*/\3\2/
/\nI/s/^/ /Mg
tc

It basically appends a string where the knowledge of conversion is. You can interprete it as :space:->1 and 0->1->2->3->4->5->6->7->8->9->I0. The substitution expression s/(.)I(.*\1(I?.))|;.*/\3\2/ works similar to the sorting one, replacing the characters in front of I's [ (.)I ] by the character that is next to the one from the front of the I in the conversion string [ (.*\1(I?.)) ] and if there is no I left, it removes the appended string [ |;.* ]. The substitution [ /\nI/s/^/ /Mg ] adds padding if needed.
Thanks to Cows quack for reducing the size by 26 bytes and for the shorter sorting algorithm.

Welcome to PPCG, and nice first answer!

You can use \w (matches word characters) in a number of places to save some bytes. Also :b ... tb can simply become s/\B\w/X/g. You can remove the line that follows it, s/:/:,/g, by modifying the earlier substitutions. You can look at https://goo.gl/JvD7Rs (shortened TIO link to sed program) to see what I mean.

You can improve on the sorting algorithm, hint: try appending zyx...cba to the input.

Brilliant unary to decimal converter! Yours is at least 30 bytes shorter than the one in Tips for golfing in sed

Dyalog APL, 109 97 96 95 93 88 bytes
{⊖(⍉r),⍨⍕↑(⊂'')@{1@0~⍵∊1,5×⍵}⍳≢⍉↑r←↑r,⍨⊂' -','   - '⍴⍨5×⌈5÷⍨≢1↓⍉↑r←↓{⍺,∊⍕¨0×⍵}⌸⍵[⍋⍵]∩⎕A}

Try it online!
Requires ⎕IO←0
Way too many bytes saved thanks to Adám and Cows quack!

For the last bit, you can try ⍵[⍋⍵]~' ' (sorts and removes spaces before passing through ⌸)

'X'/⍨≢ → ∊⍕¨×

and ⍵>0 → ×⍵

Your TIO link has an unnecessary Header.

2⌷⍴ → ≢⍉ twice

~' ' → ∩⎕A and take input in uppercase.

and ¯1+≢ → ≢1↓

¯1+⍳ → ⍳ and ×⍵ → 0×⍵ with ⎕IO←0

{(1=⍵)∨(×⍵)∧0=5|⍵:⍵⋄''}¨ → (⊂'')@{1@0~⍵∊1,5×⍵}

05AB1E, 58 47 bytes
áê©S¢Z5‰`Ā+L5*1¸ì'-«ð5×ý#À¦Áí.Bís'X×ζ‚ζJR»,®3ú,

Try it online!
-11 bytes thanks to @Emigna

Maybe this could help? Don't have time to tie them together but maybe they can give some inspiration.

@Emigna I'll have a look, definitely different than mine :).

@Emigna 57 bytes after I stitched it... given I didn't try too hard to optimize. Try it online!

47 bytes with some restructuring and optimization.

Your letters don't line up with the X's for certain inputs. https://tio.run/##AVUAqv8wNWFiMWX//8Ohw6rCqVPColo14oCwYMSAK0w1KjHCuMOsJy3Cq8OwNcOXw70jw4DCpsOBw60uQsOtcydYw5fOtuKAms62SlLCuyzCrjPDuiz//2Fh

That could be fixed at the cost of 1 byte

Python 2, 192 bytes
s=input()
d={c:s.count(c)for c in s if' '<c}
h=-max(d.values())/5*-5
for y in range(h,-1,-1):print('%d-'%y*(y%5==2>>y)).rjust(len(`-h`))+''.join(('X '[y>v],k)[y<1]for k,v in sorted(d.items()))

Try it online!
Explanation
Line 2 computes the histogram values in a fairly straightforward way, discarding ' '.
Line 3 uses the trick of computing ceil(x/5) as -(-x/5): we round the maximal frequency up to the next multiple of 5 using the formula -x/5*-5. This is h.
Line 4 is a loop counting from h down to 0 inclusive, printing each row:

If y%5==2>>y we print a label. This is when y ∈ {1, 5, 10, 15, 20, …}
(This formula could maybe be shorter. We just need something that's 1 or True for {1, 5, 10, …}, and 0 or False or even a negative integer for all other values of y.)
We right-justify the label (or empty space) into len(`-h`) spaces: this is a neat one-byte saving over len(`h`)+1!
Then, we print either X's and spaces for this row (if y ≥ 1) or the letters (if y = 0), running through key-value pairs in d in ascending order.

Nice tick creation with '%d-'%y*(y%5==2>>y). Do you mind if I use that in my answer?

-~-(y%5*~-y) works too but it's one byte longer unfortunately.

Ruby, 250 248 234 188 173 157 153 bytes
->s{a=s.scan(/\w/).sort|[]
m=-(c=a.map{|l|s.count l}).max/5*-5
m.downto(1).map{|i|(i%5<1||i<2?"#{i}-":'').rjust(m)+c.map{|l|l<i ?' ':?X}*''}<<' '*m+a*''}

Try it online!
Thanks to:

dylnan for -16 bytes with less strict padding
Lynn for -2 bytes by rounding up with -x/5*-5
Kirill L. for -2 bytes by getting unique array elements with |[]

APL (Dyalog Classic), 56 bytes
⊖h,⍨{∊⍺'-'/⍨~×5|⍵-⍵<2}⌸⍕⍪⍳≢h←(⊢↑⍨≢+5|1-≢)⍉(⊢,⌸⊣\)∊⍞∘∩¨⎕a

Try it online!

Pyth, 65 bytes
J.tm+ed*hd\Xr8S-Qd)=+J*]d%_tlJ5_.e+?q<k2%k5.F"{:{}d}-",klQ*dhlQbJ

Try it here
Explanation
J.tm+ed*hd\Xr8S-Qd)=+J*]d%_tlJ5_.e+?q<k2%k5.F"{:{}d}-",klQ*dhlQbJ
J.tm+ed*hd\Xr8S-Qd)
     Get the bars.
                   =+J*]d%_tlJ5
     Round up the height to the next number that's 1 mod 5.
                               _.e+?q<k2%k5.F"{:{}d}-",klQ*dhlQbJ
     Stick the axis labels on.

Charcoal, 62 bytes
≔Ｅ²⁷⟦⟧ηＦθ⊞§η⌕βιι≔⊟ηθ≦ＬηＰ⭆β⎇§ηκιω↑↑ΦηιＦ÷⁺⁹⌈η⁵«≔∨×⁵ι¹ιＪ±¹±ι←⮌⁺ι-

Try it online! Link is to verbose version of code. Explanation:
≔Ｅ²⁷⟦⟧η

Create a list of 27 lists.
Ｆθ⊞§η⌕βιι

Push each input character to the list corresponding to its position in the lowercase alphabet. Non-lowercase characters get pushed to the 27th list.
≔⊟ηθ

Discard the 27th element of the list.
≦Ｌη

Take the lengths of all the elements of the list.
Ｐ⭆β⎇§ηκιω

Print the lowercase letters corresponding to non-zero list elements.
↑↑Φηι

Print the non-zero list elements upwards. Since this is an array of integers, each integer prints as a (now vertical) line, each in a separate column.
Ｆ÷⁺⁹⌈η⁵«

Calculate the number of tick marks on the Y-axis and loop over them.
≔∨×⁵ι¹ι

Calculate the position of the next tick mark.
Ｊ±¹±ι

Jump to the next tickmark.
←⮌⁺ι-

Print the tickmark reversed and back-to-front, effectively right-aligning it.

Jelly, 48 bytes
What a mine-field to traverse!
J’⁶D;”-Ɗ%5^ỊƲ?€Uz⁶ZU
ḟ⁶ṢµĠ¬;⁶$L%5Ɗ¿€;"@Qz⁶Ç;"$ṚY

A full-program printing the result (as a monadic link it would return a list containing characters and integers from [0,9])
Try it online! Or see the test-suite
How?
J’⁶D;”-Ɗ%5^ỊƲ?€Uz⁶ZU - Link 1, get y-axis: list of columns (including x-axis & top-spaces)
J                    - range of length  [1,2,3,4,5,6,...,height+1] (+1 for x-axis)
 ’                   - decrement        [0,1,2,3,4,5,...] (line it up with the content)
             ?€      - if for €ach...
            Ʋ        - ...condition: last four links as a monad:
        %5           -   modulo by five
           Ị         -   insignificant? (1 for 0 and 1, else 0)
          ^          -   XOR (0 for 1 or multiples of 5 greater than 0, else 0)
  ⁶                  - ...then: literal space character
       Ɗ             - ...else: last three links as a monad:
   D                 -   decimal list of the number, e.g. 10 -> [1,0]
     ”-              -   literal '-' character
    ;                -   concatenate, e.g. [1,0,'-']
               U     - upend (reverse each)
                z⁶   - transpose with a filler of space characters
                  Z  - transpose
                   U - upend (i.e. Uz⁶ZU pads the left with spaces as needed)

ḟ⁶ṢµĠ¬;⁶$L%5Ɗ¿€;"@Qz⁶Ç;"$ṚY - Main link: list of characters
ḟ⁶                          - filter out space characters
  Ṣ                         - sort
   µ                        - start a new monadic chain, call that S
    Ġ                       - group indices of S by their values
     ¬                      - logical NOT (vectorises) (getting 0 for the X "characters")
             ¿€             - while for €ach...
            Ɗ               - ...condition: last three links as a monad:
         L                  -   length
          %5                -   modulo by five
        $                   - ...do: last two links as a monad:
      ;⁶                    -   concatenate a space character
                  Q         - deduplicate S (get the x-axis)
               ;"@          - zip with (") concatenation (;) with swapped arguments (@)
                   z⁶       - transpose a with filler of space characters
                        $   - last two links as a monad:
                     Ç      -   call last link (1) as a monad (get y-axis)
                      ;"    -   zip with concatenation (complete the layout)
                         Ṛ  - reverse (otherwise it'll be upside-down)
                          Y - join with newlines
                            - implicit print

Java (JDK), 295 bytes
s->{int d[]=new int[26],m=0;char a;for(int c:s.getBytes())m=c>32&&++d[c-=65]>m?(d[c]+4)/5*5:m;String r=m+"-",z=r.replaceAll("."," ");for(;m>0;r+="\n"+(--m%5>0&m!=1|m<1?z:z.format("%"+~-z.length()+"s-",m)))for(a=0;a<26;a++)r+=d[a]>0?m>d[a]?" ":"x":"";for(a=64;a++<90;)r+=d[a-65]>0?a:"";return r;}

Try it online!
Credits

-3 bytes thanks to Kevin Cruijssen
-1 byte thanks to ceilingcat

@aoemica Correct. I fixed it.

It's not much, but you can save 2 bytes. --m%5==0 can be --m%5<1, because you also have the &m>0 check. And m<=d[a]?"x":" " can be m>d[a]?" ":"x".

@KevinCruijssen 2 bytes are 2 bytes! I don't think there is much to golf anymore, except for a different algorithm.

1 more byte by changing (--m%5<1|m==1)&m>0 to --m%5<1|m==1&&m>0

C# (.NET Core), 344 340 338 + 18 bytes
Includes 18 bytes for using System.Linq;
Saved 6 bytes thanks to @KevinCruijssen.
n=>{var l=n.Where(c=>c!=32).GroupBy(c=>c).OrderBy(c=>c.Key).ToDictionary(k=>k.Key,c=>c.Count());int h=(l.Values.Max()/5+1)*5,o=(h+"").Length+1,m=l.Keys.Count+o,t=h+1,i=0,j;var a=new string[t];for(string p,q;i<t;a[i++]=q)for(q=(p=i>0&i%5<1|i==1?i+"-":"").PadLeft(j=o);j<m;){var c=l.ElementAt(j++-o).Key;q+=i<1?c:l[c]>=i?'X':' ';}return a;}

Try it online!

You have a space at j< m; that can be removed. And int i=0,j can be placed as ,i=0,j after the other ints for -4 bytes in total. You'll have to including the 18 bytes for the using System.Linq; however..

@KevinCruijssen Thanks, I missed these. And I added the 18 bytes.

+1 from me. Oh, and you can save 2 more bytes by changing for(;i<t;){string p=i>0&i%5<1|i==1?i+"-":"",q=p.PadLeft(o);for(j=o;j<m;){...}a[i++]=q;} to for(string p,q;i<t;)for(p=i>0&i%5<1|i==1?i+"-":"",q=p.PadLeft(j=o);j<m;a[i++]=q){...}. Try it online.

@KevinCruijssen Thats really clever, thanks!

Bash + coreutils, 332 324 323 318 312 302 298 296 293 291 bytes
c()(cut -d\  -f$@)
p=printf
cd `mktemp -d`
grep -o [^\ ]<<<$@|sort|uniq -c|c 7->a
sort -k2b
r=$[`c 1 <a|sort -n|tail -1`+5]
s=${#r}
t()($p \ ;((i++<s))&&t;i=)
for((;--r;));{
((r%5&&r>1))&&t||$p %${s}s- $r;IFS='
'
for l in `<b`;{ ((r<=`c 1 <<<$l`))&&$p X||$p \ ;}
echo
}
t
c 2 <b|tr -d \\n

Try it online!
Annotated:
c()(cut -d\  -f$@)
p=printf              # saving a few bytes

cd `mktemp -d`        # for temp files

grep -o [^\ ]<<<$@    # grabs all non-space characters
    |sort|uniq -c     # get character frequency
    |c 7->a           # slightly hacky way of stripping leading spaces;
                      #     uniq -c adds 6 spaces in front of each line

sort -k2b          # store frequencies sorted alphabetically in b

r=$[`                 # r = highest frequency +5:
    c 1 <a            #     get frequencies
    |sort -n|tail -1  #     get maximum frequency
    `+5]              #     +4 so at least one multiple of 5 is
                      #     labeled, +1 because r gets pre-decremented

s=${#r}                    # s = length of r as a string
t()($p \ ;((i++<s))&&t;i=) # pad line with s+1 spaces

for((;--r;));{         # while (--r != 0)
    ((r%5&&r>1))&&     # if r isn't 1 or a multiple of 5
        t||            #     then indent line
        $p %${s}s- $r; # otherwise print right-aligned "${r}-"
        IFS='
'                      # newline field separator
    for l in `<b`;{          # for all letters and their frequencies:
        ((r<=`c 1 <<<$l`))&& #     if frequency <= current height
            $p X||           #         then print an X
            $p \ ;}          #     otherwise print a space
    echo
}
t # indent x-axis labels
c 2 <b|tr -d \\n # print alphabetically sorted characters

Thanks to @IanM_Matrix for saving 3 bytes.

cat b could be [...a].map(x=>x>" "&&(d=c[x]=(c[x]||x)+"X")[m]?m=d.length-1:0,c={},m=i=0)&&Object.keys(c).sort().map(x=>[...c[x].padEnd(m)].map((l,j)=>A[m-j-1]+=l),A=[...Array(m+=6-m%5)].map(x=>(++i>=m||((D=m-i)%5&&m-i^1)?"":D+"-").padStart((m+" ").length)))&&A.join`
`

Try it online!

Couple of quick savings I can spot on my phone: 1. Take input as an array of individual characters, 2. Replace x!=" " with x>" ".

3. Replace m=0 with i=m=0 and map((x,i)=> with map(x=>.

Python 2, 249 224 219 215 205 197 187 188 182 176 bytes
def f(s):S=sorted(set(s)^{' '});C=map(s.count,S);P=max(C)+4;return zip(*(zip(*[('%d-'%y*(y%5==2>>y)).rjust(P)for y in range(P,0,-1)])+[(n*'#').rjust(P)for n in C]))+[[' ']*P+S]

Try it online!
Returns a list of lists of characters representing lines.

Saved some bytes by including a lot of extra whitespace.
Had an unnecessary map(list,yticks) in there.
Changed space padding to save some bytes.
I thought I was sorting but I was not: +2 bytes. But I saved one independently at the same time. y==1 replaced by y<2.
-6 bytes thanks to Lynn by using '%d-'%y*(y%5==2>>y) instead of (`y`+'-')*(not y%5or y<2).

Slightly ungolfed:
def f(s):
	S=sorted(set(s)^{' '})  # sorted list of unique letters (without ' ')
	C=map(s.count,S)        # count of each unique letter in the input
	P=max(C)+4              # used for padding and getting highest y tick
	B=[(n*'#').rjust(P)for n in C]     # create bars
	yticks = [('%d-'%y*(y%5==2>>y)).rjust(P)for y in range(P,0,-1)]  # create y ticks at 1 and multiples of 5
	yticks = zip(*yticks)                      # need y ticks as columns before combining with bars
	return zip(*(yticks+B))+[[' ']*P+S]        # zip ticks+bars then add row of sorted unique letters.

Excel VBA, 316 bytes
An Anonymous VBE immediate window function that takes input from cell [A1] and outputs to the VBE immediate window.
For i=1To 26:Cells(2,i)=Len(Replace([Upper(A1)],Chr(i+64),11))-[Len(A1)]:Next:m=-5*Int(-[Max(2:2)]/5):l=Len(m)+1:For i=-m To-1:?Right(Space(l) &IIf(i=-1Xor i Mod 5,"",-i &"-"),l);:For j=1To 26:?IIf(Cells(2,j),IIf(Cells(2, j) >= -i, "X", " "),"");:Next:?:Next:?Spc(l);:For i=1To 26:?IIf(Cells(2,i),Chr(i+96),"");:Next

Ungolfed Version
Public Sub bar_graph()
    For i = 1 To 26
        ''  gather the count of the letter into cells
        Cells(2, i) = Len(Replace([Upper(A1)], Chr(i + 64), 11)) - [Len(A1)]
    Next
    m = -5 * Int(-[Max(2:2)] / 5)   ''  get max bar height
    l = Len(m) + 1                  ''  length of `m` + 1
    For i = -m To -1
        ''  print either a label or free space (y-axis)
        Debug.Print Right(Space(l) & IIf((i = -1) Xor i Mod 5, "", -i & "-"), l);
        For j = 1 To 26
            ''  print 'X' or ' ' IFF the count of the letter is positive
            If Cells(2, j) Then Debug.Print IIf(Cells(2, j) >= -i, "X", " ");
        Next
        Debug.Print                 ''  print a newline
    Next
    Debug.Print Spc(l);             ''  print spaces
    For i = 1 To 26
        ''  print the letters that were used (x-axis)
        Debug.Print IIf(Cells(2, i), Chr(i + 96), "");
    Next
End Sub

Perl 5 -n, 198 168 bytes
s/[a-z]/$\<++${$&}?$\=${$&}:0/eg;$\++while$\%5;$;=1+length$\++;printf"%$;s".'%s'x26 .$/,$\%5&&$\-1?"":"$\-",map$$_>=$\?X:$$_&&$",a..z while--$\;say$"x$;,map$$_&&$_,a..z

Try it online!

Python 3, 177 bytes
lambda s:[[list(("%d-"%i*(i%5==2>>i)).rjust(len(q)))+["* "[s.count(c)<i]for c in q]for i in range(max(map(s.count,q))+4,0,-1)]+[[" "]*len(q)+q]for q in[sorted(set(s)-{' '})]][0]

Try it online!
This may not be the most byte-efficient approach in Python, but I really wanted to solve this with a "true one-liner" lambda.
Outputs a list of character lists. Abuses multiple leading newlines and spaces just like everybody else. It may actually be further reduced to 174 bytes if it is acceptable to wrap the result in another list, so that we could transfer the final [0] indexing to the footer.

C, 201 bytes
char c[256],*p,d;main(int a,char **b){for(p=b[1];*p;p++)++c[*p|32]>d&*p>64?d++:0;for(a=(d+4)/5*5;a+1;a--){printf(!a||a%5&&a!=1?"    ":"%3i-",a);for(d=96;++d>0;c[d]?putchar(a?32|c[d]>=a:d):0);puts(p);}}

Input is taken from the command line (first argument). Uses exclamation marks instead of X's to further reduce code size. Counter on the left is always three characters long.
Tested with GCC and clang.

for(p=b[1];*p;p++) can most likely be for(p=b[1]-1;*++p;), main(int a,char **b) could probably be golfed to m(a,b)char**b;.

Since a!=1 will be boolean, a%5&&a!=1? should be equivalent to a%5&a!=1? or a%5&&~-a.

JavaScript (ES8), 200 bytes
Takes input as an array of characters. Returns a string.
s=>(s.sort().join``.replace(/(\w)\1*/g,s=>a.push(s[0]+'X'.repeat(l=s.length,h=h<l?l:h)),h=a=[]),g=y=>y--?(y<2^y%5?'':y+'-').padStart(`${h}_`.length)+a.map(r=>r[y]||' ').join``+`
`+g(y):'')(h+=5-~-h%5)

Try it online!
Commented
s => (                    // s[] = input array of characters (e.g. ['a','b','a','c','a'])
  s.sort()                // sort it in lexicographical order (--> ['a','a','a','b','c'])
  .join``                 // join it (--> 'aaabc')
  .replace(/(\w)\1*/g,    // for each run s of consecutive identical letters (e.g. 'aaa'):
    s => a.push(          //   push in a[]:
      s[0] +              //     the letter, which will appear on the X-axis
      'X'.repeat(         //     followed by 'X' repeated L times
        L = s.length,     //     where L is the length of the run (--> 'aXXX')
        h = h < L ? L : h //     keep track of h = highest value of L
    )),                   //   initialization:
    h = a = []            //     h = a = empty array (h is coerced to 0)
  ),                      // end of replace() (--> a = ['aXXX','bX','cX'] and h = 3)
  g = y =>                // g = recursive function taking y
    y-- ?                 //   decrement y; if there's still a row to process:
      (                   //     build the label for the Y-axis:
        y < 2 ^ y % 5 ?   //       if y != 1 and (y mod 5 != 0 or y = 0):
          ''              //         use an empty label
        :                 //       else:
          y + '-'         //         use a mark
      ).padStart(         //     pad the label with leading spaces,
        `${h}_`.length    //     using the length of the highest possible value of y
      ) +                 //     (padStart() is defined in ECMAScript 2017, aka ES8)
      a.map(r => r[y]     //     append the row,
                 || ' ')  //     padded with spaces when needed
      .join`` + `\n` +    //     join it and append a linefeed
      g(y)                //     append the result of a recursive call
    :                     //   else:
      ''                  //     stop recursion
)(h += 5 - ~-h % 5)       // call g() with h adjusted to the next multiple of 5 + 1

PHP, 180 bytes
$c=count_chars($argn,1);unset($c[32]);for($s=max($c)+4;$s;){printf($s%5&&$s>1?$z='   ':'%2d-',$s--);foreach($c as$d)echo$d>$s?X:' ';echo"
";}foreach($c as$a=>$d)$z.=chr($a);echo$z;

Try it online!


text:
What are these letters?
So what might be the shortest language for this simple task?
Task:
You are given an input of type String - the string is a valid hexadecimal number ([0-9A-F]).
Convert it to a decimal number and print it to the console.
Tests:
HEX -> DEC
1 -> 1
98 -> 152
539 -> 1337
1337 -> 4919
A5F9 > 42489
F -> 15

Win Condition:
This is code golf - shortest code wins.
Rules:

You must take the input(like function parameter) as String.
You must return the result as String.

Related.

Are quotes allowed in the input? e.g. "98"

@recursive "The string is a valid hexadecimal number ([0-9A-F])" The regex wouldnt match ", so no.

Why do we have to use the standard streams, instead of, e.g., function arguments?

@Dennis to make it more tricky - stdin is string for every language I know, so the crux is to convert it couple of times...

@0x45 But the input needs to be a string anyway (not a decimal number), so what's the added difficulty? Also, ⎕ is stdin as number in APL.

Updated the task @Adám

Printing a number to stdout/stderr constitutes returning a string, right?

What about languages which can only handle numbers (and therefore I/O strings as list of ASCII codes)?

Convert the ASCII to Char and then concatenate to a String  @Adám

@Adám printing to stdout is String, yes.

Convert the ASCII to Char? But the whole point is that such a language has no concept of character data.

Repost of https://codegolf.stackexchange.com/questions/3741/hexadecimal-to-decimal ?

@l4m2 I thought of flagging this question for the same reason but the other question was closed. Would the best path to be to edit that 2015 question to be more clear and re-open it?

Why the requirement to output as a string? Trivial as this challenge may be, that requirement adds absolutely nothing to it.

Can the letters in the hex be lowercase?

@Engineer Toast I think you meant the 2011 one? The 2015 one that Martin Ender linked is the opposite conversion. With regards to the 2011 one, it does have two clear restrictions (NaN -> 0, length limit of 8) that this question doesn't have (and then everything else is a little murky), so would we be replacing it entirely or merging the restrictions of both questions?

Is it OK to add a leading 0 to the output?  I.e. 042489
What about a trailing .?  I.e. 42489.

@Wernisch leading 0 okay, . not.

@Pandacoder I did mean the 2011, thanks. I had gotten the two confused. That makes a difference, too. After 6.5 years, it's probably better to improve this question rather than re-open the old one.

@EngineerToast usually you don't come back from -12.

05AB1E, 1 byte
H

Try it online!

Am I missing something? I feel like... I feel like I am.

If "print as a string" implies "surround result with quotes":
05AB1E, 5 bytes
H'".ø

Try it online!

05AB1E is based in Python, so it doesn't really matter if it's a string, integer or whatever; H will convert an integer, a string, a Ferrarri or 27 gnomes on patrol into hex. Given, the latter two aren't valid, it will error upon trying to execute or return the original string with no function applied.

Aww man

Excel, 14 bytes
=0&HEX2DEC(A1)

Concatenates a leading 0 to convert to String.  I.e. 042489

Excel, 20 bytes
=TEXT(HEX2DEC(A1),0)

Naive solution.

Format both outputs verified as String (=T(B2))

Pyth, 5 4 bytes
iz16
Parses input as a hex number and returns the base 10 equivalent.

Welcome to PPCG!

Haskell, 24 23 22 bytes
show.abs.read.("0x"++)

Thanks to @user9549915 for saving a byte
Try it online!

Question updated. You might save some bytes now

You can save a byte by using abs instead of (+0)

JavaScript (Node.js), 20 15 14 bytes
Thanks to l4m2 for catching my stupid mistake and saving me a byte. :)
x=>'0x'+x-0+''

Try it online!
JavaScript (Node.js), 15 bytes
x=>'0x'+x-[]+''

Try it online!
Original 20 bytes
l=>''+parseInt(l,16)

Try it online!

-[] => -0 lol

JavaScript (Node.js), 18 bytes
My first JS golf!
x=>''+eval('0x'+x)

Try it online!
Just prepends 0x to the input and evaluates that, since it then represents a hexadecimal number in JS. Finally, we need to concatenate the empty string to convert to string.

no eval required

@l4m2 Yeah I realized that after seeing this improvement to mine, and thanks to op order I was able to drop () too

@l4m2 So now what? If I change this, then my solution will be identical to Pandacoder's, though we arrived to it independently.

Python 2, 20 bytes
lambda s:`int(s,16)`

Try it online!

J, 6 bytes
":@dfh

Try it online! (Contains a test suite, including type checking the parameters and the return value.)
This is pretty simple:
":@dfh
   dfh    obtain *d*ecimal *f*rom *h*ex
  @       then
":        format the result (cast to string)

Jelly, 8 bytes
⁾0x;ŒVṾ

This is a monadic link that takes a string as argument and returns a string.
Try it online!
How it works
⁾0x;ŒVṾ  Monadic link. Argument: s (string)

⁾0x;     Prepend "0x" to s.
    ŒV   Eval as Python code.
         This returns the result as an integer.
      Ṿ  Uneval; turn the integer into its string representation.

It seems to work fine on TIO without Ṿ.

Works perfectly, yes. The challenge explicitly asks to return a string though. :/

><>, 23 bytes
0l1=?n88+*{'0'-:a)7*-+!

Try it online!
If the hex can be contain lowercase letters instead of uppercase, we can do it in 17 bytes:
0l1=?n88+*{e0p +!

Java 8, 24 bytes
s->Long.valueOf(s,16)+""

Try it online here.

Charcoal, 6 bytes
Ｉ⍘↧Ｓ¹⁶

Try it online! Link is to verbose version of code. Save 1 byte if the input can be in lower case. Charcoal doesn't automatically convert numbers to decimal on output, so the cast operator is necessary anyway. Explanation:
   Ｓ    Input string
  ↧     Lower case
    ¹⁶  Literal 16
 ⍘      Base conversion
Ｉ       Cast to string
        Implicitly print

WinDbg, 15 bytes
.printf"%d",$u0

Input is done by first setting the pseudo-alias $u0 with the input string and then running the code (eg- to set pseudo-alias: r$.u0=a5f9).
Prints the input, conversion from hex to decimal is implicit.
How it works:
.printf"%d",        $$ Prints a decimal
            $u0     $$ The decimal to print

If the extra sugar that WinDbg prints when evaluating an expression is allowed:
WinDbg, 4 bytes
?$u0

How this one works:
?                  $$ Evaluates an expression
 $u0               $$ The expression to evaluate

This one would have output like this (for input= A5F9):
Evaluate expression: 42489 = 0000a5f9

C# .NET, 34 bytes
s=>System.Convert.ToInt32(s,16)+""

I have the feeling this is overly long, but the alternative s=>int.Parse(s,System.Globalization.NumberStyles.HexNumber)+"" is even worse..
Try it online.

Perl 5 -lp, 6 bytes
#!/usr/bin/perl -lp
$_=hex

Try it online!

Stax, 3 bytes
i|H

Run and debug it
i ensures that the input doesn't get automatically evaluated as an integer, and |H converts from/to hexadecimal.  The link above is for the online interpreter, but the language really does use stdin and stdout.  The C# implementation of the language does this, which is available from the repository above.

R, 27 bytes
paste(strtoi(scan(,""),16))

Try it online!
strtoi will always return a number of type integer which is a signed 32-bit integer type, and paste implicitly converts to character, as required.

I don't know the details about this language, but you aren't taking from stdin are you?

@0x45 well...sorta. scan() takes input from stdin except that stdin will in certain circumstances (like on TIO) redirect to the file so while technically on TIO it's not stdin, it's equivalent.

Question updated. You might save some bytes now

@0x45 nah it's the same either way. Thank you, though.

I'm not very familiar with R, but it seems you are returning an integer instead of a string (as per the challenge rules).

@O.O.Balance ah, I see. Must have missed that a while back. I'll fix it.

Jelly, 10 bytes
ØHiÐ€ɠ’ḅ⁴Ṿ

Try it online!
How it works
ØHiÐ€ɠ’ḅ⁴Ṿ - Main link, no arguments

ØH         - Yield the string “0123456789ABCDEF”. Call that H
     ɠ     - Read a line from STDIN, e.g. “A5F9”. Call that A
   Ð€      - For each character in A
  i   ’    - Get the 0-based index of that character in H
        ⁴  - Yield 16
       ḅ   - Convert from base
         Ṿ - Convert to string

Question updated. You might save some bytes now

@0x45 Oddly enough, I doubt it. Reading from STDIN takes one byte here ɠ, but if the input cannot be surrounded by ", then it would automatically be evaluated, which ɠ doesn't do, and unevaluating could take more bytes.

dc, 5 bytes
16i?p

Try it online!
Rather trivial. If input really needs to be a string vs. the language's natural hex input, then 16i?xp takes care of that in 6 bytes.

Julia, 23 bytes
!s=dec(parse(Int,s,16))

Try it online!
dec appears to be shorter than repr or string.

Ruby, 14 bytes
p gets.to_i 16

Try it online!

APL (Dyalog), 13 bytes
⍕16⊥(⎕D,⎕A)⍳⊢

Try it online!

16⊥⍞⍳⍨⎕D,⎕A as a full program prints to stdout and so doesn't require ⍕.

Japt, 4 bytes
Outputting as a string doubles the byte count!
nG s

Try it

I had nG before the OP said we couldn't have quotes in the input. And the output has to be a string? -__-

Batch, 15 bytes
@cmd/cset/a0x%1

If input via command-line argument is unacceptable, then for 26 bytes:
@set/ph=
@cmd/cset/a0x%h%

Io, 24 bytes
method(x,x fromBase(16))

Try it online!

Tcl, 20 bytes
proc D n {expr 0x$n}

Try it online!

Alternative approach: 21 bytes https://tio.run/##K0nO@f@/oCg/WcFFIU@hujg5MU9BJU9BtaL2f05uYoFCqkI1lyGXpQWXqbEll6GxsTmXo6mbJZdbrUJ1QWlJsYJKqlWMQrQLkI6t/Q8A

Tcl, 19 bytes
puts [expr 0x$argv]

Try it online!

Coconut, 15 bytes
str..int$(?,16)

Try it online!