text:
Could you make me a hexagon please?
Today, we're going to make an ASCII hexagon. You must write a program or function that takes a positive integer n, and outputs a hexagon grid of size n, made up of asterisks. For example, a hexagon of size 2 looks like this:
 * *
* * *
 * *

While a hexagon of size 3 looks like this:
  * * *
 * * * *
* * * * *
 * * * *
  * * *

You may use any of the default input and output methods, for example STDIO/STDOUT, function arguments and return values or reading/writing a file.
You may assume that input is always valid, so if it's not a positive integer, your program may do whatever you want. You do however have to handle the special case of a size 1 hexagon, which happens to be a single asterisk:
*

Leading and trailing whitespace is allowed as long as the output is visually the same.
Examples:
1:
*

2:
 * *
* * *
 * *

3:
  * * *
 * * * *
* * * * *
 * * * *
  * * *

4:
   * * * *
  * * * * *
 * * * * * *
* * * * * * *
 * * * * * *
  * * * * *
   * * * *

5:
    * * * * *
   * * * * * *
  * * * * * * *
 * * * * * * * *
* * * * * * * * *
 * * * * * * * *
  * * * * * * *
   * * * * * *
    * * * * *

6:
     * * * * * *
    * * * * * * *
   * * * * * * * *
  * * * * * * * * *
 * * * * * * * * * *
* * * * * * * * * * *
 * * * * * * * * * *
  * * * * * * * * *
   * * * * * * * *
    * * * * * * *
     * * * * * *

12:
           * * * * * * * * * * * *
          * * * * * * * * * * * * *
         * * * * * * * * * * * * * *
        * * * * * * * * * * * * * * *
       * * * * * * * * * * * * * * * *
      * * * * * * * * * * * * * * * * *
     * * * * * * * * * * * * * * * * * *
    * * * * * * * * * * * * * * * * * * *
   * * * * * * * * * * * * * * * * * * * *
  * * * * * * * * * * * * * * * * * * * * *
 * * * * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * * * * *
 * * * * * * * * * * * * * * * * * * * * * *
  * * * * * * * * * * * * * * * * * * * * *
   * * * * * * * * * * * * * * * * * * * *
    * * * * * * * * * * * * * * * * * * *
     * * * * * * * * * * * * * * * * * *
      * * * * * * * * * * * * * * * * *
       * * * * * * * * * * * * * * * *
        * * * * * * * * * * * * * * *
         * * * * * * * * * * * * * *
          * * * * * * * * * * * * *
           * * * * * * * * * * * *

As usual, this is code-golf, so standard loopholes apply, and you should try to write the shortest possible program measured in bytes. Of course, some languages are inherently shorter or longer than others, so remember that the goal is not necessarily to have the shortest overall byte count, but to beat submissions in the same or similar languages.
May the best golfer win!

Why do we even have a hexagonal-grid tag?

Also, someone needs to write a hexagony solution.

If anyone wants to go for the bounty, you can probably reuse the output loop of my Hexagony answer over here.

"Could you make me a hexagon please?" - sure, here you go: http://i.imgur.com/1emYIia.png

@Pavel because a lot of operations on a hexagonal grid are distinct from on the more standard square grid, and portable between solutions to different problems. Such operations as coordinate manipulation, rotation, output layout, etc.

Hexagony + Bash Coreutils, 0+3+8 = 11 Bytes
Includes +3 for -g flag and +8 for |tr . \* non-standard invocation (see this meta post)

Input is given as an argument to Hexagony. When the Hexagony interpreter is called with the -g N option it prints a hexagon of .s. We then use tr to replace those with *s.

I edited your answer with "bash coreutils" also, because I'm fairly certain this works in bash (i.e. linux or MacOS only), and because you used another language in your code.

@EasterlyIrk Thank you! I meant to do that when I found the meta post and rewrote the answer.

Wow, that's genius. And you're beating all the golfing languages!

you don't need the backslash before the * unless there are files(etc) in the current working directory.  what do the rules say about files external to your solution?

@Jasen I don't know what meta has to say about it, but I don't think you can require files with specific names, so I don't think you can require a lack of files either. Good idea though.

I wouldn't really call this using the Hexagony language, more like using bash (or some other shell) with the Hexagony interpreter as one of the commands. That would be e.g. hexagony -g $1|tr . \*, assuming the hexagony interpreter is named this way.

@PaŭloEbermann We define a language by it's interpreter don't we?

This would benefit from an actual, runnable command...

@jpmc26 For a length 5 hex you would run ruby ./interpreter.rb -g 5|tr . \*

the "program" itself is missing ?

@OlivierDulac The "program" is zero bytes. All of the work is being done by the "flags".

Python 2, 61 bytes
i=n=input()
while~-n+i:i-=1;j=abs(i);print' '*j+'* '*(2*n+~j)

Prints a trailing space at the end of each line.
Thanks to Erik the Outgolfer for saving a byte.

Starting from this, you derive a non PEP8 but valid Python 3 code with 69 bytes, by int(input()) instead of input() and the usual print(' '*j+'* '*(2*n+~j)) replacing print' '*j+'* '*(2*n+~j) - cool code b.t.w. ;-)

That is some seriously cool code!

Hexagony, 91 87 86 bytes
?{2'*=&~}=&}='P0</0P}|@..;>;'.\};0Q/..\&(<>"-_"&}=\?_&\/8.=-\<><;{M/.(.(/.-{><.{&'/_.\

Try it online!
Finally did it.
Initially (before realizing how expensive loops are) I expect this may be able to fit in side length 5, but now it's hard enough to fit it into side length 6.
To get this I actually have to modify the linear code a little. In fact, writing this makes me realize a way to golf the linear code down by 1 2 byte.

JavaScript (ES6), 77 81 84
@Upvoters: don't miss the answer by @ETHproductions, that is 76 bytes
Edit Revised after change in spec, trailing space allowed
Just for the hat ... hey! No hat?
f=(n,b='* '.repeat(n+n-1),o=b)=>--n?f(n,b=` ${b}`.slice(0,-2),b+`
${o}
`+b):o

Test

f=(n,b='* '.repeat(n+n-1),o=b)=>--n?f(n,b=` ${b}`.slice(0,-2),b+`
${o}
`+b):o

function update()
{
  O.textContent=f(+I.value)
}

update()
<input id=I type=number min=1 value=3 oninput='update()'>

JavaScript (ES6), 77 76 bytes
g=(n,s=`
*`+' *'.repeat(n*2-2),c=s,q=c.replace('*',''))=>--n?g(n,q+s+q,q):s

I told myself I wouldn't sleep until I had set a new ES6 record without looking at the other answers, so here it is...
Test snippet

g=(n,s=`
*`+' *'.repeat(n*2-2),c=s,q=c.replace('*',''))=>--n?g(n,q+s+q,q):s

for(var i = 1; i < 7; i++) console.log(g(i)) // joe

C, 91 89 80 74 bytes
w,y;f(s){for(y=-s;++y<s;)for(w=printf("\n%*s",y,"");++w<s*printf(" *"););}

I pretty much tweaked around to get the correct formulas, then mashed it all together.
Call f with the number n, and it will print the hexagon to stdout.
Ungolfed and explained (80-byte version):
w,y;
f(s) {
    // y iterates over [-s + 1 ; s - 1] (the number of rows)
    for(y = -s; ++y < s;)
        // w iterates over [abs(y) + 2 ; s * 2 - 1] (the number of stars on the row)
        for(
            // This prints a backspace character (ASCII 8)
            // padded with abs(y) + 2 spaces, effectively
            // printing abs(y) spaces to offset the row.
            // Also initializes w with abs(y) + 2.
            printf("\n%*c", w = abs(y) + 2, 8);

            // This is the for's condition. Makes use
            // of the 2 returned by printf, since we coïncidentally
            // need to double the upper bound for w.
            w++ < s * printf("* ");

            // Empty for increment
        )
            ; // Empty for body
}

See it live on Coliru
Notes:

printf can handle negative padding, which results in a left-aligned character with the padding on the right. Thus I tried something to the effect of w = printf("%*c*", y, ' ') so it would take care of the absolute value, and I could retrieve it from its return value. Unfortunately, both zero and one padding widths print the character on its own, so the three center lines were identical.
Update: Jasen has found a way to do exactly this by printing an empty string instead of a character -- 6 bytes shaved off!

The backspace character is handled incorrectly by Coliru -- executing this code on a local terminal does remove the leading space on each line.

w=printf("\n%*s",abs(y),"");++w<s*printf(" *");

@Jasen I can't believe I missed that... Thanks!

05AB1E, 14 13 bytes
Code:
F¹N+„ *×})û.c

Explanation:
F       }        # Input times do (N = iteration number)
 ¹N+             #   Calculate input + N
    „ *×         #   Multiply by the string " *"
         )       # Wrap everything into an array
          û      # Palindromize the array
           .c    # Centralize

Uses the CP-1252 encoding. Try it online!

I don't understand what the "centralize" part does. When I remove it, I get an array of strings without the appropriate number of leading spaces.

@DJMcMayhem On an array, you can see it as if it's a string joined by newlines with the text center-aligned. This is what it does on input.

10 bytes by changing F¹N+...}) to L+<...

Jelly, 24 bytes
R+’µạṀx@€⁶żx@K¥€”*$F€ŒḄY

Try it online!
Jelly is ashamed of the fact that it does not have a centralization atom, so it's beaten by 05AB1E and V. By 11 and 7 bytes respectively!
If you find any way to golf this, please comment. Any help is appreciated.
Explanation:
R+’µạṀx@€⁶żx@K¥€”*$F€ŒḄY Main link. Arguments: z.
R+’                      The sizes of the hexagon's rows. (implicit argument)
   µ                     Start a new monadic chain with the above argument.
    ȧṀx@€⁶               The spaces you must prepend to each row. (implicit argument)
           x@K¥€”*$      The stars (points) of each row, space-joined, as a single link. (implicit argument)
          ż        F€    Conjoin and merge the leading spaces with the stars appropriately.
                     ŒḄ  Create the second half of the hexagon without the middle row.
                       Y Join the rows with newlines. This makes the shape look like a hexagon.

Bonus: To find how many stars are there in a hexagon, use this:
Ḷ×6S‘

Phew, the explanation was overwhelming.

What would a "centralization atom" do?

@DJMcMayhem See the 05AB1E answer for an example.

Octave , 62 58 bytes
@(n)' *'(dilate(impad(1,2*--n,n),[k='01010'-48;~k;k],n)+1)

Previous answer:
@(n)' *'(dilate(impad(1,2*(m=n-1),m),[k='01010'-48;~k;k],m)+1)

that can be called as
(@(n)' *'(dilate(impad(1,2*(m=n-1),m),[k='01010'-48;~k;k],m)+1))(5)

Try (paste) it on Octave Online
For example the base image for n=5 is
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

that can be created with
impad(1,2*(n-1),n-1)

The dilation morphological operator applied 4 times on the image using the following neighbor mask:
0 1 0 1 0
1 0 1 0 1
0 1 0 1 0

that can be created with [k='01010'-48;~k;k]
result of dilation:
0 0 0 0 1 0 1 0 1 0 1 0 1 0 0 0 0
0 0 0 1 0 1 0 1 0 1 0 1 0 1 0 0 0
0 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 0
0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0
1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1
0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0
0 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 0
0 0 0 1 0 1 0 1 0 1 0 1 0 1 0 0 0
0 0 0 0 1 0 1 0 1 0 1 0 1 0 0 0 0

then replace 0  and 1 with ' '  and '*' respectively
    * * * * *
   * * * * * *
  * * * * * * *
 * * * * * * * *
* * * * * * * * *
 * * * * * * * *
  * * * * * * *
   * * * * * *
    * * * * *

APL (Dyalog Unicode), 40 36 35 33 27 25 bytes
(⍉⊖⍪1↓⊢)⍣2∘↑⍳↓¨∘⊂'* '⍴⍨+⍨

Assumes ⎕IO←0, i.e. zero-based indexing. The output contains one leading and one trailing spaces on each line.
Many thanks to @FrownyFrog and @ngn for lots of golfing.
Try it online!
How it works
(⍉⊖⍪1↓⊢)⍣2∘↑⍳↓¨∘⊂'* '⍴⍨+⍨  ⍝ Main function train
                 '* '⍴⍨+⍨  ⍝   Repeat '* ' up to length 2×⍵
            ⍳↓¨∘⊂          ⍝   Generate lower-right corner of the hexagon
          ∘↑               ⍝   Convert to matrix
(⍉⊖⍪1↓⊢)                   ⍝   Palindromize vertically and transpose
        ⍣2                 ⍝   ... twice

V, 17 bytes
é*Àñ>{MÄpXA *Î.

Try it online!
As usual, here is a hexdump, since this contains unprintable characters:
00000000: e92a c0ad f13e 7b4d c470 5841 202a 1bce  .*...>{M.pXA *..
00000010: 2e                                       .

postgresql9.6, 290 bytes
do language plpgsql $$ declare s constant smallint:=4;declare n smallint;declare a constant int[]:=array(select generate_series(1,s));begin foreach n in array a||array(select unnest(a)t order by t desc offset 1)loop raise info'%',concat(repeat(' ',s-n),repeat(' *',s+(n-1)));end loop;end;$$

formatted sql is here:
do language plpgsql $$
declare s constant smallint := 4;
declare n smallint;
declare a constant int[] := array(select generate_series(1, s));
begin
foreach n in array a || array(select unnest(a)t order by t desc offset 1) loop
    raise info '%', concat(repeat(' ', s - n), repeat(' *', s + (n - 1)));
end loop;
end;
$$;

output:
INFO:      * * * *
INFO:     * * * * *
INFO:    * * * * * *
INFO:   * * * * * * *
INFO:    * * * * * *
INFO:     * * * * *
INFO:      * * * *

lpad may be able to save you a few bytes. I'd also call the language pl/pgsql, but that raises questions about whether you have to count the do language plpgsql $$ and the closing $$;. Those would be best addressed on meta, if they haven't come up before.

Also, why do you need multiple DECLAREs? Wouldn't a single one work?

Python 2, 100 97 89 88 87 81  79 bytes
-1 from @Flp.Tkc
-6 again from @Flp
-2 with thanks to @nedla2004. I was trying to find how to get rid of the second slice but didn't think of that one :)
i=input()
a=[" "*(i-x)+"* "*(i+x)for x in range(i)]
print'\n'.join(a+a[-2::-1])

Try it online!
Creates an array for the top half then adds the reversed array minus the middle line then prints. Prints exactly "as is" apart from 1 which prints with a leading space (I guess that is allowed as a * is visually the same as a * with or without a leading space).

This gives wrong solution for 1 - " *". I think it should be asterisk without space in front?

@АндрейЛомакин - From OP: "Leading and trailing whitespace is allowed as long as the output is visually the same." A single star is visually the same as a single star with a space in front of it or at least that was my interpretation ;-)

But you are actually correct in that I contradicted what I have just said in my answer. I have updated the answer to clarify. Better now? BTW, nice job on finding an old answer and spotting a potential error. Respect.

I was attempting this challenge myself, and can't come up with anything better, was studing yours for inspiration.

I hope my humble effort has helped you. Sure we Wiĺl have some fun golfing together in the future. Enjoy PPCG. I sure do ☺

Breaks at side length 39, but probably because of the limited output space.

@Hippopotomonstrosesquipedalian Caused by line wrapping. With infinite screen width and height it would work for any number :)

JavaScript (ES6), 83 81 bytes
This is my first (code golf) answer. I hope I formatted everything correctly.
a=>{for(b=c=2*a-1;c;)console.log(" ".repeat(d=Math.abs(a-c--))+"* ".repeat(b-d))}

Unlike the 2 current ES6 answers, I'm not recursively calling a function and I am using the console for output.

Could you use alert if you specify browser js?

@FlipTack, not really, since I gradually build up the string (line by line). If I alerted it, it'd alert line by line, and not the whole thing.

Haskell, 99 97 79 bytes
h n=mapM_(putStrLn.(\k->([k..n]>>" ")++([2..n+k]>>"* ")))([1..n-1]++[n,n-1..1])

Explanation:
This program is based on the observation that each line of a n-Hexagon contains (n-k) spaces followed by (n+k-1) asterisks, for some k dependent on the line number.
h n=                                             h is a function of type Int -> IO ()
  mapM_                                          mapM_ executes a function returning
                                                 monadic actions on all objects
                                                 in a list, in order. Then it executes
                                                 these actions, in order. For this code, it
                                                 transforms each value in the list into a
                                                 monadic action that prints
                                                 the corresponding line

      (                                          the function consists of two components
        putStrLn                                 the second part is printing the result of
                                                 the first part to stdout

        .                                        concatenating both components

        (\k->                                    the first parts first prints (n-k) spaces
                                                 and then (n+k-1) asterisks

          ([k..n]>>" ")                          create the list of the integers from
                                                 k to n (That is actually one more entry
                                                 than necessary, but just results in a
                                                 leading whitespace per line, while
                                                 saving 2 bytes compared to [1..n-k]).
                                                 Then create a new list where
                                                 each element of that first list is
                                                 replaced with the string " " and
                                                 concatenate that result into one string

          ++                                     concatenate both lists

          ([2..n+k]>>"* ")                       create the list of the integers
                                                 from 2 to n+k (of length n+k-1).
                                                 Then create a new list where each
                                                 element of that first list is replaced
                                                 with the string "* " and concatenate
                                                 that result into one big string
        )

      )
      ([1..n-1]++[n,n-1..1])                     the list simply goes from 1 to n and
                                                 back, supplying the k

Edit: Switched to mapM_. I was not aware that was available without using import

Canvas, 9 bytes
╷⁸＋* ×］／─

Try it here!
Beating the built-in :D
Explanation:
{╷⁸+* ×]/─  implicit "{"
{      ]    map over 1..input
 ╷            decrement: 0..input-1
  ⁸+          add the input: input..(input*2-1)
    * ×       repeat "* " that many times
        /   diagonalify that - pad each line with 1 less space than the previous
         ─  palindromize vertically

No idea why there's the huge padding, but it's allowed & I'm fixing that soon™. fixed? Hope I didn't break stuff

JavaScript (ES6), 83 bytes

f=
n=>[...Array(n+--n)].map((_,i,a)=>a.map((_,j)=>j<n-i|j<i-n?``:`*`).join` `).join`
`
<input type=number min=1 oninput=o.textContent=f(+this.value)>

Batch, 161 bytes
@echo off
set s=*
set l=for /l %%i in (2,1,%1)do call
%l%set s= %%s%% *
%l%echo %%s%%&call set s=%%s:~1%% *
echo %s%
%l%set s= %%s:~0,-2%%&call echo %%s%%

Note: Trailing space on line 2. Ungolfed:
@echo off
set s=*
rem build up the leading spaces and stars for the first row
for /l %%i in (2,1,%1) do call :s
rem output the top half of the hexagon
for /l %%i in (2,1,%1) do call :t
rem middle (or only) row
echo %s%
rem output the bottom half of the hexagon
for /l %%i in (2,1,%1) do call :b
exit/b
:s
set s= %s% *
exit/b
:t
echo %s%
rem for the top half remove a space and add a star to each row
set s=%s:~1% *
exit/b
:b
rem for the bottom half add a space and remove a star from each row
set s= %s:~0,-2%
echo %s%
exit/b

Perl 6, 49 bytes
->\n{say " "x n*2-1-$_~"*"xx$_ for n...n*2-1...n}

Try it online!
How it works
->\n{                                           }  # Lambda accepting edge size (e.g. 3)
                               for n...n*2-1...n   # For each row-size (e.g. 3,4,5,4,3):
                       "*"xx$_                     # List of stars     (e.g. "*","*","*")
         " "x n*2-1-$_                             # Spaces to prepend (e.g. "  ")
                      ~                            # Concatenate.      (e.g. "  * * *")
     say                                           # Print

PHP, 83 79 bytes
for($p=str_pad;++$y<2*$n=$argn;)echo$p($p("
",1+$k=abs($n-$y)),4*$n-$k-2,"* ");

Run as pipe with -nR or try it online.

This is close to Kodos´ answer; but str_pad is shorter than str_repeat even when golfed.
And the ++ in the loop head saves some more.

Powershell, 91 89 78 68 63 52 48 bytes
param($n)$n..1+1..$n|gu|%{' '*$_+'* '*(2*$n-$_)}

Test script:
$script = {
param($n)$n..1+1..$n|gu|%{' '*$_+'* '*(2*$n-$_)}
}

12,6,5,4,3,2,1 |%{
    $_
    . $script $_
}

Output (extra leading space):
12
            * * * * * * * * * * * *
           * * * * * * * * * * * * *
          * * * * * * * * * * * * * *
         * * * * * * * * * * * * * * *
        * * * * * * * * * * * * * * * *
       * * * * * * * * * * * * * * * * *
      * * * * * * * * * * * * * * * * * *
     * * * * * * * * * * * * * * * * * * *
    * * * * * * * * * * * * * * * * * * * *
   * * * * * * * * * * * * * * * * * * * * *
  * * * * * * * * * * * * * * * * * * * * * *
 * * * * * * * * * * * * * * * * * * * * * * *
  * * * * * * * * * * * * * * * * * * * * * *
   * * * * * * * * * * * * * * * * * * * * *
    * * * * * * * * * * * * * * * * * * * *
     * * * * * * * * * * * * * * * * * * *
      * * * * * * * * * * * * * * * * * *
       * * * * * * * * * * * * * * * * *
        * * * * * * * * * * * * * * * *
         * * * * * * * * * * * * * * *
          * * * * * * * * * * * * * *
           * * * * * * * * * * * * *
            * * * * * * * * * * * *
6
      * * * * * *
     * * * * * * *
    * * * * * * * *
   * * * * * * * * *
  * * * * * * * * * *
 * * * * * * * * * * *
  * * * * * * * * * *
   * * * * * * * * *
    * * * * * * * *
     * * * * * * *
      * * * * * *
5
     * * * * *
    * * * * * *
   * * * * * * *
  * * * * * * * *
 * * * * * * * * *
  * * * * * * * *
   * * * * * * *
    * * * * * *
     * * * * *
4
    * * * *
   * * * * *
  * * * * * *
 * * * * * * *
  * * * * * *
   * * * * *
    * * * *
3
   * * *
  * * * *
 * * * * *
  * * * *
   * * *
2
  * *
 * * *
  * *
1
 *

Explanation:
param($n)           # define script parameter
$n..1+              # int range from n to 1 step -1; append
1..$n|              # int range from 1 to n
gu|                 # alias for Get-unique eliminates equal neighbors - here is 1,1 -> 1
%{                  # for each int from [n, n-1, n-2, ... 2, 1, 2, ... n-2, n-1, n]
    ' '*$_+         # string (' ' have repeated $_ times) append
    '* '*(2*$n-$_)  # string ('* ' have repeated 2*n-$_ times)
}

Nice use of gu.

Hexagony (linear), 128 127 126 bytes
Note that this is not Hexagony, just a (meta-)language Timwi supported in Esoteric IDE, so this is not eligible for the bounty.
However this can be converted to a Hexagony solution (and I think it will be smaller than this solution) I may do that later. It takes more effort I did it over here.
The initial ❢ takes 3 bytes (e2 9d a2). Each newline takes 1 byte (0a).
❢?{2'*=(
A
if > 0
 "-"&}=&~}=&}=?&
 B
 if > 0
  }P0;'(
  goto B
 &{&'-{=-(
 C
 if > 0
  'P0;Q0;}(
  goto C
 {M8;{(
 goto A
@

No Try it online!. This only works in Esoteric IDE.
Annotated code:
❢?        # read input n
[n]
{2'*=(     # x = 2n-1
[x]
A
if > 0    # loop (x) from 2n-1 to 1
 "-      # a = x - n
 [a]
 "&}=&~}=&    # a = abs(a). Let K be this amount
 }=?&
 B
 if > 0       # print ' ' (a) times
  }P0;'(
  goto B
 &        # current cell = a (= K)
 {&       # a = n if K>0 else x
          # Note that K=abs(x-n). So if K==0 then x==n.
          # Therefore after this step a is always equal to n.
 '-{=-    # compute n-(K-n) = 2n+K
 (        # decrement, get 2n+K-1
 C
 if > 0   # print ' *' this many times
  'P0;Q0;}(
  goto C
 {M8;{    # print a newline, goto x
 (        # x -= 1
 goto A
@

Javascript (ES6), 143 bytes
It's finally Christmas break (merry Christmas!), so I have some time for golfing.
And boy has it been a while - hence the large byte count.
Here goes:

c=[];a=a=>{for(i=0;i-1;j--)c.push(c[j]);return a==1?"*":c.join`\n`}
console.log(a(3));

A few improvements: for(j=c.length-2;j>-1;j--)c.push(c[j]) can be written as for(j=a-1;j;c.push(c[--j])) and for(i=0;i<a;i++){c.push(" ".repeat(a-i-1)+"* ".repeat(i+a-1)+"*")} could be for(i=0;in{(1-n..n-1).map{|j|i=j.abs;' '*i+'* '*(n*2+~i)}*$/}

lambda function takes n as argument and returns a string separated by newlines. ($/ is a variable containing the default line separator.)
in test program
f=->n{(1-n..n-1).map{|j|i=j.abs;' '*i+'* '*(n*2+~i)}*$/}

puts f[gets.to_i]

You can save 1 byte by using (1-n...n) with 3 dots

Seems consensus is to include the output code (i.e. puts) in the char count. But re-reading the definition it only says your function should "output" the result which could be read as "return" the result. Cool solution.

@MatiasBjarland http://meta.codegolf.stackexchange.com/a/2456/15599

Charly, 125 bytes
let i="".promptn()let o=0let j=0let w=write loop{w(" "*(i-1-o),"* "*(i+o))w("
")if j<i-1{o+=1}else{o-=1}if o<0{break}j+=1}

Charly GitHub Page: https://github.com/KCreate/charly-lang

Python 2, 111 bytes
n=input()
l=range(n,2*n-1)
S=l+[2*n-1]+l[::-1]
W=range(1,n)
for w in W[::-1]+[0]+W:print" "*w+"* "*S[0];S=S[1:]

A boring, straightforward implementation (and a full program). Outputs a trailing whitespace at each line.
Testcases:
1:
*

2:
 * *
* * *
 * *

3:
  * * *
 * * * *
* * * * *
 * * * *
  * * *

4:
   * * * *
  * * * * *
 * * * * * *
* * * * * * *
 * * * * * *
  * * * * *
   * * * *

SmileBASIC, 74 bytes
FOR I=0TO N-1P
NEXT
FOR I=N-2TO.STEP-1P
NEXT
DEF P?" "*(N-I);"* "*(N+I)END

Adds a leading and trailing space.
These "hexagons" look horrible when the characters have the same width and height...

Java, 157 149 129 127 93 92 bytes
s->{for(int j=~--s,t;j++<s;System.out.println(repeat(" ",t=j<0?-j:j)+repeat("* ",s-~s-t)));}

8 bytes removed by Jonathan Frech.
56 bytes removed by Kevin Cruijssen.
1 byte removed by ceilingcat.

Try it online!

149 bytes.

94 bytes. NOTE: Java 11 has String#repeat(int), but TIO is still JDK 10, hence the emulated repeat(String,int) method (with the same byte-count). The actual code in Java 11 would be: s->{for(int j=~--s,t;++j<=s;System.out.println(" ".repeat(t)+"* ".repeat(s-~s-t)))t=j<0?-j:j;}

@KevinCruijssen, nice, thank you, I'll update it when Java 11 is released.

@Eugene Sure. :) In that case some things to golf in the current Java version (8+) for now: 129 bytes.

@KevinCruijssen That's quite a heavy golfing here, updated it, thanks.

Me again. Found one more thing to golf for -2 bytes. 127 bytes This can also be used to golf 1 byte in the Java 11 solution above.

Japt -R, 11 10 bytes
Æ°çSi*Ãû ê

Try it (or use TIO to run multiple tests)

Explanation
               :Implicit input of integer U
Æ              :Map the range [0,U)
 °             :  Postfix increment U
  ç            :  Repeat
   S           :    Space
    i*         :    Prepend asterisk
      Ã        :End map
       û       :Centre pad each string with spaces to the length of the longest string
         ê     :Palindromise
               :Implicitly join with newlines and output

racket/scheme
(define (f n)
  (define (s t n)
    (if (= n 0) t (s (~a t "* ") (- n 1))))
  (define (h t p a i)
    (if (= i 0)
        (display t)
        (let ((x (~a t (make-string p #\space) (s "" a) "\n"))
              (q (if (> i n) (- p 1) (+ p 1)))
              (b (if (> i n) (+ a 1) (- a 1))))
          (h x q b (- i 1)))))
  (h "" (- n 1) n (- (* 2 n) 1)))

testing:
(f 1)
*

(f 4)
   * * * *
  * * * * *
 * * * * * *
* * * * * * *
 * * * * * *
  * * * * *
   * * * *

Welcome to the site!  This is a code-golf competition so you ought to include your byte count. Also you can remove a lot of the whitespace present in this answer to shorten it.

Thanks for your input, Cat Wizard. I'm new to code golfing, and I suppose scheme isn't the best language for it, but I'll try to shorten it up, eliminate whitespace, and add a byte count on my next entry.

Vyxal C, 8 bytes
ʁ+×*vṄøm

Try it Online!
ʁ        # Range(n) (0...n-1)
 +       # Plus n (n...2n-1)
  ×*     # That many asterisks
    vṄ   # Join each by spaces
      øm # Palindromise
         # (C flag) Center and join by newlines

Palindromise is now ∞, so this is 7 bytes: Try it Online!

tcl, 123
Based in Python 2 ...
gets stdin i;set n $i;while {$n+[incr i -1]} {puts [string repe " " [expr abs($i)]][string repe "* " [expr 2*$n+~abs($i)]]}

PHP, 91 bytes
for($r=str_repeat;$j<$h=($n=$argv[1])*2-1;)echo$r(' ',$a=abs(++$j-$n)).$r('* ',$h-$a)."\n";

Run it in the command line like this:
php -d error_reporting=0 -r "for($r=str_repeat;$j<$h=($n=$argv[1])*2-1;)echo$r(' ',$a=abs(++$j-$n)).$r('* ',$h-$a).\"\n\";" "5"

Ungolfed:
<?php
// Store reference to str_repeat function for repeated uses
$r = str_repeat;

// Loop through each line until n*2+1 (the height of the hexagon)
for(;$j < $h = ($n = $argv[1]) * 2 - 1;) {

    // Add spacing to the beginning of each line.
    echo $r(' ', $a = abs(++$j - $n));

    // Add asterisks for each line
    echo $r('* ', $h - $a);

    // Add newline to the end of the line
    echo "\n";
}

QBIC, 82 76 bytes
Because you said please.
:~a=1|?A\[a-1|H=space$(a-b)┘G=A[a+b-2|G=G+@* `┘]Z=H+_tG|+H+@┘`+Z]?_fZ|+B+G+A

This can definitelyprobably be golfed further.

Python 3, 111 Bytes
d=int(input());i=' *';y=''
for x in range(d-1):y+=(' '*(d-x-1)+i*(d+x)+' '*(d-x)+'\n')
print(y+i*(2*d-1)+y[::-1])

Builds the top section, copies the reverse for the bottom and slots a line in the middle. Best approach I could think of.

This could be shortened by changing to Python2.

@TuukkaX unfortunately I don't know Python2 well enough to change it. You are welcome to suggest a solution

Pyth - 60 57 50 bytes
p*tQd*Q"* "VtQp*-Q+2Nd*h+QN"* ";VtQp*hNd*-*tQ2N"*

Try it online!
p                    print the next item (without trailing newline)
*tQd                multiply (input-1) by " "
*Q"*"                (implicit print) input times "* "
VtQ                 for all numbers 0 through (input-1) (as represented by N)
p                    print the next item (without trailing newline)
*-Q+2Nd              input-(N+2)  times " " (as represented by d)
*h+QN"*"            (implicit print) input+N+1  times "* "
;                    end for statement
V-Q1                 for all numbers 0 through input-1 (as represented by N)
p                    print the next item (without trailing newline)
*hNd                N+1 times " "
*-*tQ2N"*          (2*(input-1))-N   times "* " (implicit end string with EOF)
(implicit end of for loop with EOF)
(EOF == End of file)

I would be interested to see an explanation of how this works.

will do @WheatWizard!

PostgreSQL, 86
I was gonna write a CJam answer, but I saw somebody did Postgres and I had to compete :)
\prompt n
select lpad('',@i)||repeat('* ',2*:n-1- @i)from generate_series(1-:n,:n-1)i;

Run it like this: psql -Atf hex.sql dbname username and type in the number (or append e.g. <<<3 to the command).

Retina, 81 bytes
Assumes ISO 8859-1 encoding. All whitespace is significant.
\d+
$* $&$*a
^

.*
$0¶$0
m+`^(( *) (a+))¶\1
$1¶$2a$3¶$2a$3¶$1
m`^(a+)¶\1
$1
a
*

Try it online!
Explanation
The code consists of 6 regex replacements on the input.
\d+
$* $&$*a

This replaces the input (we'll call it n) with n spaces and n as. I use a during most of program and replace it with * in the end because * is a reserved regex character and would need to be escaped if used directly.
^

(Note the space after ^) This removes the first space in the text. The result is a line consisting of n-1 spaces followed by n as.
.*
$0¶$0

The line is duplicated.
m+`^(( *) (a+))¶\1
$1¶$2a$3¶$2a$3¶$1

The most complicated stage in the program. It will replace any line that consists of a non-zero number of spaces followed by some number of as that also has an exact copy of itself following on the next line. It will be replaced with itself, a line consisting of 1 less space and 1 more a, that same line again, followed by the original line. More simply, it takes any two identical, directly adjacent lines and inserts two copies of a line with 1 less space and 1 more a in between them. This replacement will be made continually until the text stops changing, which happens when two lines consisting of only as have been inserted.
m`^(a+)¶\1
$1

This removes the duplicate of the line consisting of all as (since this line is the middle of the hexagon).
a
*

Finally, replace all instances of a with * .

Groovy, 64 63 62 58 56 bytes
{n->(1-n..n-1)*.abs().any{println' '*it+'* '*(2*n+~it)}}

Example call:
{n->(1-n..n-1)*.abs().any{println' '*it+'* '*(2*n+~it)}}(4)

produces:
   * * * *
  * * * * *
 * * * * * *
* * * * * * *
 * * * * * *
  * * * * *
   * * * *

R, 72 bytes
function(n,a=n-1)for(i in abs(a:-a))cat(rep(c('','*'),c(i,2*n-1-i)),'
')

Try it online!

K (oK), 44 38 34 bytes
Solution:
{(-a+3*x)$(2*x+a,:1_|a:!x)#\:"* "}

Try it online!
Example:
{(-a+3*x)$(2*x+a,:1_|a:!x)#\:"* "}4
("    * * * * "
"   * * * * * "
"  * * * * * * "
" * * * * * * * "
"  * * * * * * "
"   * * * * * "
"    * * * * ")

Explanation:
Create lists of * of the desired length and then left-pads them the required amount.
{(-a+3*x)$(2*x+a,:1_|a:!x)#\:"* "} / the solution
{                                } / lambda taking implicit argument x, e.g. 4
                             "* "  / the string "* "
                          #\:      / take (#), each-left (\:)
          (              )         / do this together
                       !x          / til x, range 0..x, e.g. 0 1 2 3
                     a:            / assign to variable a
                    |              / reverse it, e.g. 3 2 1 0
                  1_               / drop the first, e.g. 2 1 0
               a,:                 / append that to a, e.g. 0 1 2 3 2 1 0
             x+                    / add x, e.g. 4 5 6 7 6 5 4
           2*                      / multiply by 2, e.g. 8 10 12 14 12 10 8
         $                         / pad (negative means left-pad)
 (      )                          / do this together
     3*x                           / x multiply by 3, e.g 12
   a+                              / add a, e.g. 12 13 14 15 14 13 12
  -                                / negate, e.g. -12 -13 -14 -15 -14 -13 -12

Extra:
There is a leading space, this can be removed at the cost of 1 extra byte:
{(1-a+3*x)$(2*x+a,:1_|a:!x)#\:"* "}

Edits:

-1 byte thanks to ngn (reuse a rather than defining b)
-3 bytes by returning list of strings rather than printing to STDOUT

you can modify a instead of introducing a second variable b: b:a, -> a,: and -b+3*x -> -a+3*x

\0:` - I believe it should be okay to return a list of strings instead of printing it to stdout

Kotlin, 113 89 bytes
24 bytes saved thanks to mazzy
{n:Int->for(o in 1-n..n-1){val c=Math.abs(o)
println("".padEnd(c)+"* ".repeat(2*n-c-1))}}

Try it online!

87 bytes: n:Int->for(m in 1-n..n-1){val c=Math.abs(m);println("".padEnd(c)+"* ".repeat(2*n-c-1))}

Sisi, 233 bytes
0set n3
1set i1
2set d1
3set o""
4set j n-i
5jumpif j7
6jump10
7set o o+" "
8set j j-1
9jump5
10jumpif o12
11set d0-1
12set j n+i
13set j j-1
14jumpif j16
15jump19
16set o o+"* "
17set j j-1
18jump14
19print o
20set i i+d
21jumpif i3

Try it online!
Note: because Sisi has no way of taking input, this meta consensus allows for input to be inserted into the source code. For this program, the value of n should be inserted directly after n on line 1. In the code above, the value n = 3 is used.
Pseudocode
Because of Sisi's limitations, we have to generate and print one line at a time in order. So we run a loop in which i will go from 1 up to n and back down to 1:
i = 1
d = 1
while i > 0
  construct string of (n-i) spaces
  append to that (n+i-1) copies of "* "
  print it
  if i = n
    d = -1
  end
  i = i + d
repeat

Ungolfed version
10 set n 3
20 set i 1
30 set d 1

100 set o ""
110 set j n-i
120 jumpif j 140
130 jump 200
140 set o o+" "
150 set j j-1
160 jump 120

200 jumpif o 300
210 set d 0-1

300 set j n+i
310 set j j-1
320 jumpif j 340
330 jump 400
340 set o o+"* "
350 set j j-1
360 jump 320

400 print o
410 set i i+d
420 jumpif i 100

QBasic, 76 bytes
INPUT n
FOR i=-n+1TO n-1
s=ABS(i)
?SPC(s)
FOR j=2TO 2*n-s
?"* ";
NEXT
?
NEXT

(This requires real QBasic, in which ?SPC(s) is expanded to PRINT SPC(s);, unlike QB64, in which it becomes PRINT SPC(s).)
Similar approach to my Sisi answer, except QBasic has ABS and so it's more efficient to run a FOR loop from -n+1 to n-1.

ABAP, 172 bytes
FORM h USING s.DO s * 2 - 1 TIMES.WRITE /''.DATA(y) = sy-index.DO s * 2 - 1 TIMES.IF sy-index > s - y AND sy-index > y - s.WRITE'*'.ELSE.WRITE ``.ENDIF.ENDDO.ENDDO.ENDFORM.

For ABAP I am pretty impressed by how short it turned out to be. I suppose having written the C# answer beforehand was helpful, but merely from an "understanding what to do" perspective, since the languages are so vastly different. There might be potential to save some bytes by using a single do-loop instead, but that would require a few calculations which in turn would have so much whitespace in them that it's likely going to be worse.
Test Cases
Size = 1, 5, 13

Has some leading and trailing whitespace thanks to how WRITE works, but luckily it's not an issue. In fact this saves us a whole byte with WRITE'*' including an implicit trailing space. Wow!
Explanation (also on Pastebin with syntax highlighting)
FORM h USING s. "ABAP subroutine
  DO s * 2 - 1 TIMES. "basically a simple for loop; loop over each line top to bottom
    WRITE /''. "Newline. No effect on first line for some reason. *shrug*
    "Also, WRITE /. works, too, but outputs TWO line feeds here. Ugh.
    DATA(y) = sy-index. "Save current index in loop to Y
    DO s * 2 - 1 TIMES. "Loop for each character left to right
      IF sy-index > s - y      "Check if we need to write a '*'
         AND sy-index > y - s. "by subtracting size from current line and vice versa
        WRITE'*'. "Print the '*'. WRITE has an implicit space after the output!
      ELSE.
        WRITE ``. "Empty literal. CANNOT be '' or ' ' because then we don't get any output.
      ENDIF.      "Yeah, WRITE is odd. Don't ask.
    ENDDO.        "End of inner loop
  ENDDO.          "End of outer loop
ENDFORM.          "End of subroutine

C# (.NET Core), 106 105 bytes
Private method, takes the size as input and returns a string containing the hexagon.
Edit: Holy cow. I stared at this single-for-loop version for so long, finally figured out how to make it one byte shorter than the double-for-loop version!
string h(int s){var o="";for(int q=2*s,y=q;q*q>++y;o+=y%q>y/q-s&y%q>s-y/q?"* ":y%q<1?"\n":" ");return o;}

Try it online!
s is the size, x and y represent "coordinates" in the output string (position on the line & current line). In an earlier version I wrote this nice little passage: h>e?x>h-e:x. I found it very fitting, but unfortunately had to scrap it when optimizing my code.
I was initially worried about handling size = 1, but it turns out my code worked just fine. Phew!
Suggestions are welcome! :)

Previous 106 byte version with two for-loops: Try it online!

VBA (Excel), 77 bytes
Using Immediate Window and A1 as input.
a=[a1]-1:for x=-a to a:y=Abs(x):?space(y)StrConv(String(1+a*2-y,"*"),64):next

And for fun.
    a=[A1
   ]-1:For
   x=-a To
 a:y=Abs(x):
?Space(y)StrC
 onv(String(
  1+a*2-y,"
   *"),64)
    :Next

JavaScript (Node.js), 103 bytes
f=(n,m=n+--n)=>[...Array(m)].map((_,i)=>m-Math.abs(i-n)).map(e=>' '.repeat(m-e)+'* '.repeat(e)).join`
`

Try it online!

JavaScript (Node.js), 70 bytes
f=(n,i=n,w=" ".repeat(--i)+"* ".repeat(n++))=>w+(i?`
${f(n,i)}
`+w:"")

Try it online!
With one trailing space at the end of each line.

APL(NARS) 60 chars, 120 bytes
{1≥k←⍵:'*'⋄⊃{(' '⍴⍨k-⍵+1),((2×k+⍵)⍴'* ')}¨(0..⍵-1),(⍵-2)..0}

test
  f←{1≥k←⍵:'*'⋄⊃{(' '⍴⍨k-⍵+1),((2×k+⍵)⍴'* ')}¨(0..⍵-1),(⍵-2)..0}
  f 1
*
  f 2
 * *
* * *
 * *
  f 3
  * * *
 * * * *
* * * * *
 * * * *
  * * *

the only difficult is that (2×7)⍴'* ' would mean "repeat '* ' until you write the 14th character" so that would repeat '* ' 7 times...

C, 88, 83
This solution uses just one for loop unlike the other C solution using 2 for loops because of this I suspect it can be golfed much further, but it's 4:30am so I'll attempt that tomorrow.
y,w;f(s){for(w=++s*2-1;y++<w*w-w*2;)printf(" %c",y%w?y%w-1<=abs(s-y/w-2)?0:42:13);}

Revision history:
2) y,w;f(s){for(w=++s*2-1;y++<w*w-w*2;)printf(" %c",y%w?y%w-1<=abs(s-y/w-2)?0:42:13);}
1) y,w;f(s){for(w=++s*2-1;y++<w*w-w*2;)printf("%s",y%w?y%w-1<=abs(s-y/w-2)?" ":"* ":"\n");}

For example my for loop can already be shortened to for(w=s*2-1;y++<w*w;) and would require only minimal logic changes inside the loop of which I am 90% sure would actual decrease byte size further.

You know you spend too much time of PPCG when you golf instead of sleep :P

Common Lisp, 97 96 bytes
(lambda(x)(dotimes(i(1-(* x 2)))(format t"~v@t~v{* ~}~%"(set'c(abs(1+(- i x))))(-(* x 2)1 c)1)))

needed to figure out formula for:
a) how many spaces before text: |1+x-i| ~~ (abs(1+(- i x)
b) how many characters: 2x-1-|1+x-i| ~~ (-(* x 2)1 c)
idea for using dotimes and abs for looping from Strigoides's answer here
Ideas for improvement are welcomed

F#, 101 98 Bytes
let r=String.replicate
let h n=for i in[0..n-1]@[n-2..-1..0]do(r(n-i)" ")+r(n+i)"* "|>printfn"%s"

Ungolfed:
let replicate = String.replicate
let ungolfed_hexagon n =
  for i in [0..n-1]@[n-2..-1..0] do // For each hexagon line index [0 .. n-1 .. 0]
      (replicate (n-i) " ")  // Space padding
    + (replicate (n+i) "* ") // Hexagon stars
    |> printfn "%s"

Usage: Call h n, where n is the hexagon size, and it will print the hexagon.

k, 51 bytes
`0:{x,|-1_x}@|{m:-1+2*x;{(x#" "),(2*m-x)#"* "}'!x}@

Explanation:
              {                                  }@ / function(x)
               m:-1+2*x;                            / m = (2*x)-1
                        {                    }'!x   / for x in range(0, x):
                         (x#" "),                   /   x*" " +
                                 (2*m-x)#"* "       /           m-x*"* "
             |                                      / reversed()
   {       }@                                       / function(x)
    x,                                              / x +
      |-1_x                                         /     reversed(x[1:])
`0:                                                 / print array line by line

Perl 5 with -na -M5.010, 44 bytes
say$"x abs,"* "x(2*"@F"-1-abs)for 1-$_..$_-1

Try it online!
Uses the same range as a few of the other answers.

Jelly, 16 15 bytes
ḶU⁶ẋż+Ḷ⁾ *ẋƲŒḄY

Try it online!

Now beats V!

Charcoal, 33 31 17 bytes
≔×*ＮθＦθ«Ｐ^θ→→»‖Ｂ↓

-14 bytes thanks to @Neil.
Try it online (verbose) or Try it online (pure).
Explanation:
Put a string in a variable consisting of the input amount of *:
Assign(Times("*", InputNumber()), q);
≔×*Ｎθ

Loop the input amount of times by doing a for-each over the characters of this string:
For(q){ ... }
Ｆθ« ... »

Print the string in both a down-left and down-right direction, without moving the cursor position:
Multiprint(:^, q);
Ｐ^θ

And move two positions to the right at the end of every iteration:
Move(:Right); Move(:Right);
→→

After the loop, reflect everything downwards with one line overlap:
ReflectButterfly(:Down);
‖Ｂ↓

FYI I'm down to 22 bytes using a different algorithm (ported from my answer to another hexagon-drawing question).

I got to 20 bytes using a polygon but 17 bytes based on your algorithm.

Pyth, 23 bytes
jm.[*4Q*"* "+Qd\ +PUQ_U

Try it online
Explanation:
jm.[*4Q*"* "+Qd\ +PUQ_UQ   Trailing Q inferred, Q=eval(input())
                     _UQ   Reversed 0-range, yields [Q-1, Q-2, ... , 1, 0]
                  PUQ      Tailless 0-range, yields [0, 1, ... , Q-3, Q-2]
                 +         Concatenate them, yields [0 ... Q-1 ... 0]
 m                         Map d in the above to:
            +Qd              Q+d
       *"* "                 Repeat *_ that many times
  .[*4Q        \             Centre pad the above to length 4*Q
j                          Join on newlines, implicit print

Python 3, 117 113 bytes
def h(s):n="\n".join;t=[" "*(s-i-1)+"* "*(s+i)for i in range(s-1)];return"%s\n%s\n%s"%(n(t),"* "*(2*s-1),n(t[::-1])

Generates the top, then the middle, then reverses the top to generate the bottom half.

JavaScript (Node.js), 121 99 bytes
i=>[...t=[...Array(i)].map((_,z)=>''.padEnd(i-z)+'* '.repeat(z+i)),...t.reverse().slice(1)].join`
`

Try it online!

99 bytes

til you don't need ( ) if the only arg is a multiline string

it's actually an array of the string i think

C (gcc), 164 125 124 123 bytes
i,h;main(z,b)int**b;{z=atoi(b[1]);for(i=z--+z;i--;puts(""))for(h=z+1*2n=i+1iO+*' '=xI>=x-n iFx~x*'* '+1-*2n x

Try It Online!

authors: Андрей Ломакин


text:
Natural Pi #2 - River
Goal
Given an string with a train of hashes, calculate its total length and divide by the distance from start to finish.
Simulation
What are we simulating? According to this paper, the ratio of the length of a river to the distance between start and end is approximately Pi! (This may have been disproved empirically, but I could find the data and for this challenge we'll assume it is true).
How are we simulating this?

Take a string input of whitespace and hashes
Each hash will have two others adjacent to it

With the exception of the first and last hash which will have only 1

Each character lies on a lattice point (x, y)
x is the character's index in its line

eg c is the 4th character in 0123c567

y is the character's line number

eg c is on the 3rd line:

      0line
      1line
      2line
      3c...

Sum the distances between adjacent hashes, call it S
Take the distance between the first and last hashes, call it D
Return S/D

Specification

Input

Flexible, take input in any of the standard ways (eg function parameter,STDIN) and in any standard format (eg String, Binary)

Output

Flexible, give output in any of the standard ways (eg return, print)
White space, trailing and leading white space is acceptable
Accuracy, please provide at least 4 decimal places of accuracy (ie 3.1416)

Scoring

Shortest code wins!

Test Cases
These are my approximations of the rivers. My approximations might be poor or these my be poor sample of the river population. Also, I did this calculations by hand; I could have miss calculated.
Yellow River
        ### ####
       #   #    #
       #       #          #
       #       #         #
       #       #        #
      #         #      #
##   #          # #####
  ##  #          #
    ##

1.6519

Nile River
         #
         #
          #
           #
           #
          #
         #
        #
        #  #
        # # #
         #  #
            #
          ##
         #
         #
        #
        #
       #
       #
       #
       #
   #  #
  # ##
  #
  #
   #
    #
     #
     #
      #
     #
    #
     #
      #

1.5498

Mississippi River
 ###
#   #
     #
     #
    #
   #
  #
  #
  #
   #
    #
     #
      #
       #
        #
        #
        #
         #
          #
           #
          #
       ###
      #
       #
      #
     #
    #
    #
    #
    #
     #
      ##
        #
        #
         ##
           ##
             ##
               #
              #
             #
            #
           #
          #
         #
        #
        #
        #
        #
        #
       #
      #
     #
      #
       #
        ####
            #
             #

1.5257

TL;DR
These challenges are simulations of algorithms that only require nature and your brain (and maybe some re-usable resources) to approximate Pi. If you really need Pi during the zombie apocalypse, these methods don't waste ammo! There are nine challenges total.

They're called hashes on their own. "Hashtag" is just the term for an inline tag signified with #<tag>

I assume that the distance should be calculated using the Pythagorean theorem. Is this correct?

Also, can we take the input as a list of lines?

@Loovjo ^^ It can be, it is Euclidean geometry so however you want to calculate it is fine. ^ Yes, input is flexible.

Can the input be a matrix of zeros and ones?

@LuisMendo Yes, that would be fine

Can we return a rational number?

Does the paper really say pi? The outputs look more similar to pi/2

@LuisMendo I believe it does say pi (but I don't have access to it anymore). Several articles about this paper say that the average sinuosity is 3.14. This particular article suggests that, empirically, the average sinuosity of rivers is around 1.94.

@NonlinearFruit Thanks. Then it's probably that the ASCII versions are not sinuous enough :)

@LegionMammal978 Accuracy, please provide at least 4 decimal places of accuracy

From these results, it seems the ratio is closer to Pi/2 than Pi.

MATL, 48 44 42 37 33 bytes
Quite a few bytes saved thanks to rahnema1's idea (Octave answer) of collapsing two convolutions into one
t5BQ4B&vX^Z+*ssGt3Y6Z+1=*&fdwdYy/

This takes the input as a binary matrix, with ; as row separator. 1 corresponds to hash and 0 to space.
Try it online! Or verify all test cases.
Here's a format converter that takes inputs as 2D char arrays (again, with ; as separator) and produces string representations of the corresponding binary matrices.
Explanation
This was fun! The code uses three two 2D-convolutions, each for a different purpose:

To detect vertical and horizontal neighbours, which contribute a distance of 1, the required mask would be
0 1 0
1 0 1
0 1 0

But we only want each pair of neighbours to be detected once. So we take half the mask (and the last row of zeros can be removed):
0 1 0
1 0 0

Similarly, to detect diagonal neighbours, which contribute a distance of sqrt(2), the mask would be
1 0 1
0 0 0
1 0 1

but by the same reasoning as above it becomes
1 0 1
0 0 0

If this mask is multiplied by sqrt(2) and added to the first, the two convolutions can be replaced by one convolution with the combined mask
sqrt(2) 1  sqrt(2)
1       0        0

Start and end points are, by definition, the points with only one neighbour. To detect them we convolve with
1 1 1
1 0 1
1 1 1

and see which points give 1 as result.

To produce the combined mask of item 1 it's shorter to generate its square and then take the square root. The mask in item 2 is a predefined literal.
t     % Take input matrix implicitly. Duplicate
5B    % 5 in binary: [1 0 1]
Q     % Add 1; [2 1 2]
4B    % 4 in binary: [1 0 0]
&v    % Concatenate vertically
X^    % Square root of each entry
Z+    % 2D convolution, maintaining size
*     % Multiply, to only keep results corresponding to 1 in the input
ss    % Sum of all matrix entries. This gives total distance
Gt    % Push input again. Duplicate
3Y6   % Predefined literal. This gives third mask
Z+    % 2D convolution, maintaining size
1=    % Values different than 1 are set to 0
*     % Multiply, to only keep results corresponding to 1 in the input
&f    % Push array of row indices and array of column indices of nonzeros
d     % Difference. This is the horizontal difference between start and end
wd    % Swap, difference. This is the vertical difference between start and end
Yy    % Hypothenuse. This gives total distance in straight line
/     % Divide. Display implicitly

Some people used to say, that convolution is the key to success!

Octave, 99 bytes
@(a)sum((c=conv2(a,[s=[q=2^.5 1 q];1 0 1;s],'same').*a)(:))/2/{[x y]=find(c<2&c>0),pdist([x y])}{2}

nearly same method as MATL answer but here kernel of convolutions is
1.41 ,  1  , 1.41
1    ,  0  , 1
1.41 ,  1  , 1.41

that sqrt(2) =1.41 is for diagonal neighbors  and 1  is for direct neighbors  so when we sum values of the result over the river we get twice the real distance.
ungolfed version:
a=logical([...
0 0 0 0 0 0 0 0 1 1 1 0 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 1 0 0 0 1 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1
0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 1 0
0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0
0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0
1 1 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 1 1 1 1 1 0 0 0 0
0 0 1 1 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0
0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 ]);
sq = sqrt(2);
kernel = [...
    sq ,  1  , sq
    1  ,  0  , 1
    sq ,  1  , sq];
%2D convolution
c=conv2(a,kernel,'same').*a;
#river length
river_length = sum(c (:))/2;
#find start and end points
[x y]=find(c<2&c>0);
# distance between start and end points
dis = pdist([x y]);
result = river_length/ dis

Try (paste) it on Octave Online

Your idea to lump the first two convolutions into one saved me a few bytes :)

{[x y]=find(c<2&c>0),pdist([x y])}{2} is so damn clever!!!

a good news is that we do not have restrictions of MATLAB!

@flawr Agreed. That should go to the Octave golfing tips!

@LuisMendo some entries included in tips

@rahnema1 Great! Since the tips question asks for one tip per answer, I suggest you move the rows part to a new answer. The rest of the current answer can be left as is, because it's all related to indexing in Octave

JavaScript (ES6), 178
Input as a string with newlines in rectangular form : each line padded with spaces to the same length (as in the examples)
r=>r.replace(/#/g,(c,i)=>([d=r.search`
`,-d,++d,-d,++d,-d,1,-1].map((d,j)=>r[i+d]==c&&(--n,s+=j&2?1:Math.SQRT2),n=1),n||(v=w,w=i)),w=s=0)&&s/2/Math.hypot(v%--d-w%d,~(v/d)-~(w/d))

Less golfed
r=>(
  r.replace(/#/g, // exec the following for each '#' in the string
    (c,i) => // c: current char (=#), i: current position
    ( // check in 8 directions
      // note: d starts as the offset to next row, prev x position
      // and is incremented up to offset to next row, succ x position
      // note 2: there are 2 diagonal offsets, then 2 orthogonal offsets
      //         then other 2 diagonal, then 2 more orthogonal
      [d=r.search`\n`,-d, ++d,-d, ++d,-d, 1,-1].map( // for each offset
        (d,j) => // d: current offset, j: array position (0 to 7)
        r[i+d] == c && // if find a '#' at current offset ...
          (
            --n, // decrement n to check for 2 neighbors or just 1
            s += j & 2 ? 1 : Math.SQRT2 // add the right distance to s
          ),
      n = 1), // n starts at 1, will be -1 if 2 neighbors found, else 0
      // if n==0 we have found a start or end position, record it in v and w
      n || (v=w, w=i)
   ),
  w=s=0), // init s and w, no need to init v
  // at the end
  // d is the length of a line + 1
  // s is twice the total length of the river
  // v and w can be used to find the x,y position of start and end
  s/2/Math.hypot(v%--d-w%d,~(v/d)-~(w/d))
)

Test

F=
r=>r.replace(/#/g,(c,i)=>([d=r.search`\n`,-d,++d,-d,++d,-d,1,-1].map((d,j)=>r[i+d]==c&&(--n,s+=j&2?1:Math.SQRT2),n=1),n||(v=w,w=i)),w=s=0)&&s/2/Math.hypot(v%--d-w%d,~(v/d)-~(w/d))

Yellow=`        ### ####
       #   #    #
       #       #          #
       #       #         #
       #       #        #
      #         #      #
##   #          # #####
  ##  #          #
    ##                     `

Nile=`         #
         #
          #
           #
           #
          #
         #
        #
        #  #
        # # #
         #  #
            #
          ##
         #
         #
        #
        #
       #
       #
       #
       #
   #  #
  # ##
  #
  #
   #
    #
     #
     #
      #
     #
    #
     #
      #        `

Missi=` ###
#   #
     #
     #
    #
   #
  #
  #
  #
   #
    #
     #
      #
       #
        #
        #
        #
         #
          #
           #
          #
       ###
      #
       #
      #
     #
    #
    #
    #
    #
     #
      ##
        #
        #
         ##
           ##
             ##
               #
              #
             #
            #
           #
          #
         #
        #
        #
        #
        #
        #
       #
      #
     #
      #
       #
        ####
            #
             #  `
console.log('Yellow River',F(Yellow))
console.log('Nile River',F(Nile))
console.log('Mississippi River',F(Missi))

source: Stack Exchange

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

sort: votes


text:
Coprimes up to N
Given a number n >= 2, output all the positive integers less than n where gcd(n, k) == 1 (with k being any one of the output numbers).  Numbers of this sort are coprime to each other.
Example: 10 gives the output [1, 3, 7, 9] (in any form you like, as long as the numbers are unambiguously separated and in some sort of list).  The list cannot have duplicate entries and doesn't have to be sorted.
More test cases:
2 -> [1]
3 -> [1, 2]
6 -> [1, 5]
10 -> [1, 3, 7, 9]
20 -> [1, 3, 7, 9, 11, 13, 17, 19]
25 -> [1, 2, 3, 4, 6, 7, 8, 9, 11, 12, 13, 14, 16, 17, 18, 19, 21, 22, 23, 24]
30 -> [1, 7, 11, 13, 17, 19, 23, 29]

We are also not counting numbers above n that are coprime to n, solely because I'm fairly certain there's infinite solutions.
Also note: Numbers that are coprime to each other are also said to be relatively prime or mutually prime to each other.

Do seperate strings (e.g. 1\n3\n) count as valid output?

@devRicher that works, sure.

The intuition about there being an infinite number of numbers above n that are coprime to n feels correct to me. There are infinitely many primes, and a prime would be coprime with every number below it. Therefore, every prime greater than n (of which there are infinitely many) are also part of the coprime list.

@BrianJ Not just that. If c and n are coprimes, c + kn and n are also coprimes, for all integers k.

Fun fact: these are called totatives.

Jelly, 3 bytes
gÐṂ

Try it online!
How does this work?

gÐṂ  - (Monadic) Full program.

g    - Greatest common divisor.
 ÐṂ  - Keep the elements with minimum link value (i.e. those with GCD == 1)
       Note that this automatically creates the range [1, input] (inclusive).

Proof of validity
Since we want to extract the coprimes only, the minimum value of the Greatest-Common-Divisors list has to be 1 for the ÐṂ trick to work. Let's prove that (in two different methods):

The implicitly generated range, \$[1, \text{input}]\$ contains \$1\$ and \$\gcd(1, x) = 1\:\:\forall\:\:x \in \mathbb{Z}^{*}\$. The greatest common divisor is always a strictly positive integer, hence \$1\$ is guaranteed to occur and will always be the minimum value.

Two consecutive positive integers are always coprime. Consider \$x, y \in \mathbb{Z}^{*}\$, with \$y = x + 1\$. Then we take another positive integer \$k\$ such that \$k \mid x\$ and \$k \mid y\$.
This implies that \$k \mid (y - x)\$, so \$k \mid (x + 1 - x)\$, thus \$k  \mid 1\$. The only positive integer to divide \$1\$ is \$1\$ itself, so it is guaranteed to appear in the list and will always be the minimum value.

You outgolfed Dennis in his own language after 9 months!

@Adám I am not sure whether ÐṂ existed back then, anyway I am quite satisfied with this one.

For the record, DṂ did exist, but it only worked for monads. The commit implemented Þ, ÐṂ, ÐṀ for dyads is dated May 9, 2017.

@Dennis I knew there'd be a good reason why you didn't have the 3-byte version. We were wondering about that in chat too, so thanks for the useful information!

Python 2, 61 47 bytes
lambda n:[k/n for k in range(n*n)if k/n*k%n==1]

Try it online!
Background
Consider the ring \$(Z_n, +_n, \cdot_n)\$. While this ring is usually defined using residue classes modulo \$n\$, it can also be thought of as the set \$Z_n = \{0, \dots, n - 1\}\$, where the addition and multiplication operators are defined by \$a +_n b = (a + b)\:\%\: n\$ and \$a \cdot_n b = a \cdot b\:\%\: n\$, where \$+,\:\cdot\text{, and } \%\$ denote the usual addition, multiplication, and modulo operators over the integers.
Two elements \$a\$ and \$b\$ of \$Z_n\$ are called mutual multiplicative inverses modulo \$n\$ if \$a \cdot_n b = 1\:\%\:n\$. Note that \$1\:\%\:n = 1\$ whenever \$n > 1\$.
Fix \$n > 1\$ and let \$a\$ be a coprime of \$n\$ in \$Z_n\$. If \$a \cdot_n x = a \cdot_n y\$ for two elements \$x\$ and \$y\$ of \$Z_n\$, we have that \$a \cdot x\:\%\:n = a \cdot y\:\%\:n\$. This implies that \$a \cdot (x - y)\:\%\:n = a \cdot x\:\%\:n - a \cdot y\:\%\:n = 0\$, and we follow that \$n  \mid  a \cdot (x - y)\$, i.e., \$n\$ divides \$a \cdot (x - y)\$ evenly. Since \$n\$ shares no prime divisors with \$a\$, this means that \$n  \mid  x - y\$. Finally, because \$-n < x - y < n\$, we conclude that \$x = y\$. This shows that the products \$a \cdot_n 0, \dots, a \cdot_n (n - 1)\$ are all different elements of \$Z_n\$. Since \$Z_n\$ has exactly \$n\$ elements, one (and exactly one) of those products must be equal to \$1\$, i.e., there is a unique \$b\$ in \$Z_n\$ such that \$a \cdot_n b = 1\$.
Conversely, fix \$n > 1\$ and let \$a\$ be an element of \$Z_n\$ that is not coprime to \$n\$. In this case, there is a prime \$p\$ such that \$p  \mid  a\$ and \$p  \mid  n\$. If \$a\$ admitted a multiplicative inverse modulo \$n\$ (let's call it \$b\$), we'd have that \$a \cdot_n b = 1\$, meaning that \$a \cdot b\:\%\:n = 1\$ and, therefore, \$(a \cdot b - 1)\:\%\:n = a \cdot b\:\%\:n - 1 = 0\$, so \$n  \mid  a \cdot b - 1\$. Since \$p  \mid  a\$, we follow that \$p  \mid  a \cdot b\$. On the other hand, since \$p  \mid  n\$, we also follow that \$p  \mid  a \cdot b - 1\$.  This way, \$p  \mid  (a \cdot b) - (a \cdot b - 1) = 1\$, which contradicts the assumption that \$p\$ is a prime number.
This proves that the following statements are equivalent when \$n > 1\$.

\$a\$ and \$n\$ are coprime.

\$a\$ admits a multiplicative inverse modulo \$n\$.

\$a\$ admits a unique multiplicative inverse modulo \$n\$.

How it works
For each pair of integers \$a\$ and \$b\$ in \$Z_n\$, the integer \$k := a \cdot n + b\$ is unique; in fact, \$a\$ and \$b\$ are quotient and remainder of \$k\$ divided by \$n\$, i.e., given \$k\$, we can recover \$a = k/n\$ and \$b = k\:\%\: n\$, where \$/\$ denotes integer division. Finally, since \$a ≤ n - 1\$ and \$b ≤ n - 1\$, \$k\$ is an element of \$Z_{n^2}\$; in fact, \$k ≤ (n - 1) \cdot n + (n - 1) = n^2 - 1\$.
As noted above, if \$a\$ and \$n\$ are coprime, there will be a unique \$b\$ such that \$a \cdot b\:\%\:n = 1\$, i.e., there will be a unique \$k\$ such that \$k / n = a\$ and \$k / n \cdot k\:\%\:n = (k / n) \cdot (k\:\%\:n)\:\%\:n = 1\$, so the generated list will contain \$a\$ exactly once.
Conversely, if \$a\$ and \$n\$ are not coprime, the condition \$k / n \cdot k\:\%\:n = 1\$ will be false for all values of \$k\$ such that \$a = k / n\$, so the generated list will not contain \$a\$.
This proves that the list the lambda returns will contain all of \$n\$'s coprimes in \$Z_n\$ exactly once.

"GCD? Where we're going, we don't need GCD."

Woah. That's all I wanted to write, but apparently I needed 15 characters. Still, woah. Great job.

Jelly, 4 bytes
gRỊT

Try it online!
How it works
gRỊT  Main link. Argument: n

 R    Range; yield [1, ..., n].
g     Compute the GCD of n and each k in [1, ..., n].
  Ị   Insignificant; return 1 for GCDs less or equal to 1.
   T  Truth; yield the indices of all truthy elements.

Coding in this language takes some gRỊT

I managed to (ab)use the "Minimum link value" quick (ÐṂ) in order to get 3 bytes.

Mathematica, 25 bytes
Range@#~GCD~#~Position~1&

Slightly weird output format, where each result is wrapped in a separate list, e.g. {{1}, {3}, {7}, {9}}. If that's not okay, I've got two solutions at 30 bytes:
Select[Range[x=#],#~GCD~x<2&]&
#&@@@Range@#~GCD~#~Position~1&

Mathematica actually has CoprimeQ but that's way too long.

What does Q mean in CoprimeQ?

@ConorO'Brien "question" I guess. All decision problem built-ins end in Q like EvenQ, PrimeQ or SubsetQ.

Python, 93 82 74 bytes
f=lambda a,b:f(b,a%b)if b else a<2
lambda c:[i for i in range(c)if f(i,c)]

f recursively checks for coprimes, and the second lambda generates them.  Outputs a list.

2sable, 4 bytes
Code:
ƒN¿–

Explanation:
ƒ       # For N in the range [0, input]..
 N¿     #   Compute the GCD of N and the input
   –    #   If 1, print N with a newline

Uses the CP-1252 encoding. Try it online!

Good job (almost) beating Dennis. (few minutes late though).

Actually, 8 bytes
;╗R`╜┤`░

Try it online!
Explanation:
;╗R`╜┤`░
  R`  `░  elements of range(1, n+1) where
;╗  ╜     n and the element
     ┤    are coprime

I believe you can just do range(1, n) if that saves any bytes.

@ETHproductions It doesn't. The two options are R (range(1, n+1)) and r (range(n)). Since they're equivalent, I chose R (since I accidentally hit caps lock while writing the code).

Yeah, that's what I figured. I didn't see an instruction that seemed dedicated to incrementing, but I thought there might have been one anyway

MATL, 7 bytes
:GZd1=f

Try it online!

JavaScript (ES6), 64 61 bytes
Saved 3 bytes thanks to @user81655
n=>[...Array(n).keys()].filter(b=>(g=a=>b?g(b,b=a%b):a<2)(n))

Test snippet

f=n=>[...Array(n).keys()].filter(b=>(g=a=>b?g(b,b=a%b):a<2)(n))

for(var i = 2; i < 50; i++) console.log(i + ":", `[${ f(i) }]`);

Can't you swap a== with a<2?

@EasterlyIrk Not sure, a might be 0 at some point. I'll have to check

You could move the GCD function into the filter to remove the need to receive a b parameter: ...keys()].filter(b=>(g=a=>b?g(b,b=a%b):a<2)(n))

@user81655 That's great, thanks! :-)

MATLAB/Octave, 22 bytes
@(n)find(gcd(1:n,n)<2)

Try it online!

Jellyfish, 19 18 bytes
p
[#
`B
&~xr1
NnEi

This works by computing the prime factorization of every number in the range and checking whether it intersects that of the input (Jellyfish doesn't have a gcd builtin yet).
For golfing reasons, the output is in descending order.
Try it online!
Explanation
First off, i is evaluated input; for input 10, the value of the i-cell is 10.
r1
i

Here r (range) is applied to the input and 1.
Because the input is greater than 1, the range is in descending order; for input 10, this gives [9 8 7 6 5 4 3 2 1].
[#
`B
&~x
Nn

This part is one big function, which is evaluated on i and the above range.
~x
n

Intersection (n) of prime factors (x).
&~x
Nn

Is it empty? (N)
`
&~x
Nn

Thread to level 0, testing for each element of the range.
[#
`B
&~x
Nn

Filter (#) the range with respect to this list of booleans.
The function produced by [ wants to use the argument to # as its own argument, so we put a B to block # from getting any arguments.
Otherwise, the value of the ~-cell would be used as the argument of the big function.
Finally, p prints the result.

Stacked, noncompeting, 24 21 bytes
Saved 3 bytes, inspired by Borsunho's ruby. (1 eq to 2<)
{!n:>1+:n gcd 2<keep}

Try it here!
This is an n-lambda that takes a single argument and yields the array.
{!n:>1+:n gcd 2<keep}
{!                  }  n-lambda
  n                    push n
   :>                  range [0, n)
     1+                range [1, n]
       :               duplicate
        n gcd          element-wise gcd with n
              2<       element-wise equality with 1
                       this yields the range [1, n] and a boolean mask of coprime numbers
                keep   then, we simply apply the mask to the range and keep coprimes.

Why is this noncompeting?

@ZacharyT mainly, keep wasn't working nicely.

CJam, 14 bytes
{:X{Xmff%:*},}

Try it online!
Explanation
We don't need to check all possible divisors of a and b to test whether they're coprime. It's sufficient to look at whether any of the prime factors of b divides a.
:X     e# Store the input in X.
{      e# Filter the list [0 1 ... X-1] by the results of this block...
  Xmf  e#   Get the prime factors of X.
  f%   e#   Take the current value modulo each of those prime factors.
  :*   e#   Multiply the results. Iff any of them divide the current
       e#   value, there's a 0 in the list, and the result of the product
       e#   is also 0, dropping the value from the resulting list.
},

Mathematica, 26 bytes
Pick[r=Range@#,r~GCD~#,1]&

Ohhhh, I've been looking for something like Pick. I guess now I'm glad I didn't find it, though. ;) But it should be very useful for future challenges.

Dyalog APL, 10 bytes.
0~⍨⍳×1=⊢∨⍳

Explanation (input n):
0~⍨⍳×1=⊢∨⍳
         ⍳ - 1 ... n (Thus, ⎕IO is 1)
       ⊢∨  - Each GCD'd by n
     1=    - Test equality with 1 on each element
   ⍳×      - multiplied by its index
0~⍨        - without 0.

I love the way APL code looks like the face you make when you read it. ⍨

Yep, and it demolishes almost every not code-golf-oriented language. :).

Why only "might" work?

I'm just going to assume it works.

@ZacharyT why can't you test it? When I paste it into try-apl.org, it errors with invalid token.

This doesn't work on tryapl.org.

I don't have Dyalog.

@ZacharyT You can test on try-apl.org.

It's v16. Won't work.

Those 6 characters are actually 14 bytes in UTF-8 or 12 bytes in UTF-16 (try 80⎕DR'⍸1=⊢∨⍳'). You may want to link to this.

Thank's, I'll revert it to the old version to save 2 bytes.

There. It's changed to the 10 byte version.

@ZacharyT How did you even get a hold of version 16.0?

Ugh. I was being insane. Following your suggestion from a while back. Thinking it was released like an idiot.

Perl 6, 20 bytes
{grep 2>* gcd$_,^$_}

Julia 0.5, 23 bytes
!n=1÷gcd.(1:n,n)|>find

Try it online!

julia 1.0+ version: !n=findall(gcd.(1:n,n).<2) - no find and findall needs boolean.

Brachylog, 16 13 bytes
>.$p'(e:A*?),

This is a function that takes N as input, and generates all integers less than and coprime to it.
Try it online! As is often the case in Brachylog, this has had extra code added to make the function into a full program; Brachylog's interpreter, if given a function rather than a full program, will run it but not print the output, which means you can't really observe its workings.
Explanation:
A Brachylog program is a chain of constraints; typically, the LHS of one constraint is the RHS of the next.
>.$p'(e:A*?),
>              The input is greater than
 .             the output, whose
  $p           prime factorisation does
    '(     )   not obey the following constraint:
      e        it has an element which
       :A*     can be multiplied by something to
          ?    produce the input.
            ,  (This comma turns off an unwanted implicit constraint.)

Golfed down three characters by realising there's no reason to check to see if the common factor (which is already known to be a prime factor of the output) is a prime factor of the input. We already know it's prime, so we can just check if it's a factor. I'm pleasantly surprised here that :A*? doesn't send the interpreter into an infinite loop and doesn't allow a non-integer value for A, but as the interpreter does what I want, I'll take it.

Japt -f, 9 8 5 2 bytes
jN

Try it

2 bytes saved thanks to ETH pointing out a brainfart, which led to another byte saved.

You could do o f_jU

Thanks, @ETHproductions. Don't know what I was thinking here! Must've been one of those (many) moments when I forget j can also be used to test if 2 numbers are co-prime.

Mathematica, 33 bytes
xSelect[Range@x,x~CoprimeQ~#&]

Contains U+F4A1

What's the unprintable do?

@EasterlyIrk introduces an unnamed function with a named argument. it's rendered as an arrow in Mma.

@MartinEnder oh, cool.

U+F4A1 is a private use character. As Martin said, it's rendered as an arrow in Mathematica.

Haskell, 27 bytes
f n=[k|k<-[1..n],gcd n k<2]

Try it online!

memes, 11 bytes
Uses UTF-8 encoding.
d`}}]i=1?ip

Explanation:
d     Set program to not output result
`}    Loop next input-times
}]i   GCD of input and loop index
=1?   Is it equal to 1? If yes,
ip    Print out loop index

} accesses the next input item, but last input is looped through when given, so inputting 6 will result as 6 6 6 6 6 ... in STDIN, making it possible for reading two outputs from one.

05AB1E, 3 bytes
Lʒ¿

Try it online!
Has new features.

PARI/GP, 27 bytes
n->[k|k<-[1..n],gcd(k,n)<2]

This uses the set-notation introduced in version 2.6.0 (2013). In earlier versions, four more bytes were needed:
n->select(k->gcd(k,n)<2,[1..n])

would be needed.

How does this work?

@EasterlyIrk The same as most of these submissions -- make a range from 1 to n ([1..n]), check if gcd is 1 (gcd(n,k)<2), return the numbers with this property. The -> is function/closure notation, shorter by 2 bytes than normal function syntax and [...|...<-...,...] is the set notation explained in the answer (see section 2.3.14 in the User's Manual, or search for <-).

Ruby, 3634
->n{n.times{|i|p i if i.gcd(n)<2}}

Admittedly, this isn`t a very inspired answer.
2 bytes saved thanks to Conor O'Brien.

You can shave off two bytes by removing parentheses around (n)

Python 3, 60 bytes
Imports gcd instead of writing a new lambda for it. Golfing suggestions welcome. Try it online!
import math
lambda c:[i for i in range(c)if math.gcd(c,i)<2]

I don't think you can golf this more. Importing gcd directly or math as m both add bytes.

Julia, 30 bytes
n->filter(x->(gcd(n,x)<2),1:n)

Anonymous function. filter removes elements from a list that aren't truthy according to a function.
In this case, the function is x->(gcd(n,x)<2) (true if the gcd of the input and the list element is less than 2).  The list is the range 1:n.

-2bytes: x->(gcd(n,x)<2) could be x->gcd(n,x)<2.

05AB1E, 4 bytes
GN¿–

Try it online!
How it works
     # implicit input
G    # for N in range(1..input)
 N   # push N
  ¿  # gcd(input, N)
   – # if 1, print N

C (gcc), 54 bytes
k;f(n){for(k=0;++k/n<n;k/n*k%n-1||printf("%u ",k/n));}

This is a port of my Python answer.
Try it online!

50 bytes. It outputs in reverse order (allowed by the author), and clutters stdin and stderr

Whispers v2, 65 bytes
> Input
> 1
>> (1]
>> L⊓1
>> L=2
>> Select∘ 4 5 3
>> Output 6

Try it online!
Uses the recently implemented Select∘ command.
How it works
The entire program is built from lines 4, 5 and 6
>> L⊓1
>> L=2
>> Select∘ 4 5 3

This is the first use of any of the three Select statements, this time using the Select∘ statement. All forms of the Select statements take n line references as arguments. The last number references the array to select from (let's say \$A\$), and the others reference the functions to iterate over that array (i.e the array of functions, \$B\$). However, they differ as follows:

Select∧ - Only select elements which are truthy under all functions in \$B\$:

$$R := [x \in A \: | \: f(x) \top, \forall f \in B]$$

Select∨ - Only select elements which are truthy under any function in \$B\$

$$R := [x \in A \: | \: f(x) \top, \exists f \in B]$$

Select∘ - Only select elements which, when all functions in \$B\$ are composed together, are truthy under this new function:

$$\text{Let }B := [f(x), g(x), h(x)]$$
$$R := [x \in A \: | \: h(g(f(x))) \: \top]$$
In this program, we can define \$A := [1, 2, ..., \alpha-1, \alpha]\$, where \$\alpha\$ is the input. We then define line 4 (>> L⊓1) as \$f(x) = \gcd(x, \alpha)\$ and line 5 (>> L=2) as \$g(x) := (x = 1)\$. Finally, we can define \$B = [f(x), g(x)]\$. This sets us up for the select statement as shown above.
When we encounter the Select∘ statement, we take \$R\$ (the final array) as defined by the third relationship above. To make things slightly easer, we'll define
\begin{align}
h(x) & := g(f(x)) \\
 & := gcd(x, \alpha) = 1
\end{align}
\$R\$ is then equal to the array where \$\forall x \in R\$, \$h(x) \: \top\$. Finally, on the last line, we output \$R\$.
Shorter version, 56 bytes
> Input
> 1
>> (1]
>> L⟂1
>> Select∘ 4 3
>> Output 5

Try it online!
This is much less interesting as it uses the co-prime builtin. In this case, any of the three select statements can be used.

Vyxal, 5 bytes
'?ġ1=

Try it Online!
Explanation:
       # Implicit input
'      # Apply function for n in range [0,input) and filter:
 ?     #   Input
  ġ    #   GCD of input and current number
   1=  #   Equal to 1?
       # Implicit output

This can be 4 bytes or 3.375 bytes now

JavaScript (Firefox 30-57), 53 bytes
n=>[for(i of Array(n*n).keys())if(i*(i=i/n|0)%n==1)i]

Port of @Dennis's amazing Python answer. 60 bytes in ES6:
n=>[...Array(n*n)].map((_,i)=>i/n|0).filter((i,j)=>i*j%n==1)

Similar idea of looking for the multiplicative inverse, also 60 bytes in ES6:
n=>[...Array(n).keys()].filter((i,_,a)=>a.some(j=>i*j%n==1))

Pyth, 5 bytes
x1iLQ

Try it online!
How it works
Note that Pyth uses 0-indexing.
x1iLQ   Q = eval(input())

x1iLQQ  implicit Q at the end
  iLQQ  [gcd(Q,0), gcd(Q,1), ..., gcd(Q,Q-1)]
x1      all occurences of 1 in the above list (return their indices)

Husk, 7 6 bytes
§foε⌋ḣ

-1 thanks @Leo!
Try it online!
Explanation
        -- implicit input N
§f   ḣ  -- filter the range [1..N] with
  oε⌋   --   is gcd(N,·) at most 1

C (gcc), 99 bytes
#include<stdio.h>
g(a,b){return b>0?g(b,a%b):a;}c(n,i){for(i=1;i<n;i++)g(n,i)<2?printf("%i ",i):0;}

Try it online!

Java 8, 98 bytes
import java.util.*;n->{Set r=new HashSet();for(int i=0;++i/n<n;)r.add(i/n*i%n==1?i/n:1);return r;}

Port of @Dennis' amazing Python answer.
Explanation:
Try it here.
import java.util.*;     // Required import for Set and HashSet

n->{                    // Method with integer parameter and Set return-type
  Set r=new HashSet();  //  Result-Set
  for(int i=0;          //  Index-integer (starting at 0)
      ++i/n<n;)         //  Loop as long as `i/n` is smaller than `n`
                        //  (starting `i` at 1 by first increasing it by 1 with `++i`)
    r.add(i/n           //   If `i/n`,
          *i%n          //   multiplied by `i` modulo-`n`,
              ==1?      //   is exactly 1:
           i/n          //    Add `i/n` to the Set
          :             //   Else:
           1            //    Add 1 to the Set
  );                    //  End of loop
  return r;             //  Return the result-Set
}                       // End of method

Gaia, 2 bytes
S⁇

Try it online!
I seem to have outgolfed myself.

S⁇  - Full program.

 ⁇  - Filter-Keep (operates on the automatically generated range).
S   - Check if the input and the current element are coprime.

C 177 ,  150  , 135 , 102 bytes
Not very golfy but...
p,i,t,x,y,N;f(n){
int A[9]={};
for(i=0,N=n;p<n;n/=p){
for(p=2+(n&1);n%p;)p+=2;
A[i++]=p;
}
for(y=0;y++<N;){
for(i=t=0;x=A[i++];)
t|=!(y%x);
if(!t)printf("%d ",y);
}
}

EDIT: one line 150
p,i,t,x,y,N;f(n){int A[9]={};for(i=0,N=n;p<n;n/=A[i++]=p)for(p=2+(n&1);n%p;)p+=2;for(y=0;y++<N;){for(i=t=0;x=A[i++];)t|=!(y%x);printf("\0 %d"+!t,y);}}

EDIT2:
f(n){int p,t,x,i=0,y=0,N=n,A[9]={};for(;p<n;n/=A[i++]=p)for(p=2;n%p;)p++;for(;y++<N;printf("\0 %d"+!t,y))for(i=t=0;x=A[i++];)t|=y%x<1;}

Stores array of primefactors of N,
Then prints numbers < N that don't divide those.
EDIT3:
Got rid of Array, recalulating primefactors instead
f(n){int p,t,i=0,N=n;for(;i++<N;printf("\0 %d"+!t,i))for(n=N,p=t=0;p<n;n/=p,t|=i%p<1)for(p=1;n%++p;);}

Try it online!

I'm pretty sure you can remove the newlines in C

95 bytes

Funky, 59 bytes
g=(a,b)=>b?g(b,a%b):(a>1)ort[#t]=i
f=n=>fort={}n>i++g(n,i)t

This defines the function f, which generates a list of all co-primes from 1 to n.
Try it online!

Pari/GP, 28 bytes
n->[x|x<-[0..n],gcd(x,n)==1]

Try it online!

SNOBOL4 (CSNOBOL4), 149 bytes
	DEFINE('G(A,B)')
	N =INPUT
I	X =X + 1
	EQ(X,N)	:S(END)
	K =G(N,X)
	OUTPUT =EQ(K,1) X :(I)
G	T =REMDR(A,B)
	A =B
	B =T
	G =EQ(B) A	:F(G)S(RETURN)
END

Try it online!
Uses the Euclidean algorithm in the function G to calculate the GCD; prints values with newlines between them.
	DEFINE('G(A,B)')		;*let the interpreter know a function G is available
	N =INPUT			;*read input
I	X =X + 1			;*increment step
	EQ(X,N)	:S(END)			;*if X==N, end
	K =G(N,X)			;*K =GCD(N,X)
	OUTPUT =EQ(K,1) X :(I)		;*if K==1, output X. goto I
G	T =REMDR(A,B)			;*function body: euclidean algorithm
	A =B
	B =T
	G =EQ(B) A	:F(G)S(RETURN)	;*if B==0, G=A and return.
END

J, 16 Bytes
C=:I.@(1:=]+.i.)

C for coprime.
How it works:
C=:                | Define the verb C
             i.    | Integers between 0 and n-1 inclusive
          ]+.      | GCD with n. Gets applied to each element of i.n
       1:=         | Test whether each element of the array is 1. If it is, put 1, otherwise 0
   I.              | Return the indexes of the 1s. If there are none (i.e., on input 1) returns 0.

Parenthesis and @ are just so it gets executed in the right order.
Step by step example:
    (]+.i.) 10
10 1 2 1 2 5 2 1 2 1

    (1:=]+.i.) 10
0 1 0 1 0 0 0 1 0 1

    I.@(1:=]+.i.) 10
1 3 7 9

    C 10
1 3 7 9

Wonder, 35 bytes
@(!>@=1len inx 'fac#0fac#1).'rng1#0

Usage:
(@(!>@=1len inx 'fac#0fac#1).'rng1#0)3

Basically filters over a range from 1 to the input with a predicate:

Find all factors of both the current mapped item and the input.
Find the intersection of both arrays.
Check if the result is of length 1. If the 2 numbers are coprime, then their factors' intersection set should only contain 1.

Julia 1.0, 33 bytes
(n)->[k for k=1:n if gcd(n,k)==1]

Try it online!

it is actually 30 bytes: n->[k for k=1:n if gcd(n,k)<2]

Scala, 35 bytes
n=>BigInt(1)to n filter(_.gcd(n)<2)

Try it in Scastie!

MMIX, 76 bytes (19 instrs)
void __mmixcall coprimes(octa n,
                         void *d, void (*__mmixcall f)(void *d, octa i));

(jelly xxd)
00000000: fe03 0004 c104 0000 f701 0000 2704 0401  “¤¡¥Ḋ¥¡¡ẋ¢¡¡'¥¥¢
00000010: 5a04 0003 f604 0003 f800 0000 c105 0400  Z¥¡¤ẇ¥¡¤ẏ¡¡¡Ḋ¦¥¡
00000020: c106 0000 1e06 0605 c106 0500 fe05 0006  Ḋ©¡¡œ©©¦Ḋ©¦¡“¦¡©
00000030: 5b05 fffd 2706 0601 4306 fff5 c106 0100  [¦”’'©©¢C©”ṫḊ©¢¡
00000040: c107 0400 bf05 0200 f1ff fff1            Ḋ¬¥¡Ḃ¦£¡ȯ””ȯ

Disassembly and explanation
coprimes    GET    $3,rJ        // savedj = rJ
            SET    $4,$0        // i = n
            PUT    rD,0         // zero out hidiv register
0H          SUBU   $4,$4,1      // loop: i--
            PBNZ   $4,1F        // iflikely(i) goto continuation
            PUT    rJ,$3        // rJ = savedj
            POP    0,0          // return
1H          SET    $5,$4        // continuation: p = i
            SET    $6,$0        // q = n
1H          DIVU   $6,$6,$5     // gcd: q:rR = rD:q /% p
            SET    $6,$5        // q = p
            GET    $5,rR        // p = rR
            PBNZ   $5,1B        // iflikely(p) goto gcd
            SUBU   $6,$6,1      // q--
            BZ     $6,0B        // if(!q) goto loop
            SET    $6,$1        // fa1 = d
            SET    $7,$4        // fa2 = i
            PUSHGO $5,$2,0      // f(fa1,fa2)
            JMP    0B           // goto loop

I don't have a good way to output a sequence, so I just went with the tried and true callback method. Works for any n from \$1\$ to \$2^{63}-1\$.

Factor, 40 bytes
[ dup iota [ gcd nip 1 = ] with filter ]

Try it online!

Arturo, 31 bytes
$->n[select..1n'x->1=gcd@[x,n]]

Try it

Nekomata, 4 bytes
rG1Ĩ

Attempt This Online!
r       Range from 0 to input - 1
 G      GCD with input
  1Ĩ    Find indices of 1s (0-indexed)

Thunno 2 v, 3 bytes
æĠḅ

Try it online!
Explanation
æĠḅ  # Implicit input
æ    # Filter (implicit cast to range) by:
 Ġ   #  GCD of this number and the input
  ḅ  #  Equals one?
     # Implicit output

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

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