text:
Array indexes to number and number reversed
Given an input array having minimum length 2 and maximum length 9 having any initial values output an array having length 2 consisting of the 1-based indexes of the array represented as either an integer or string in forward and reverse order.
The values of the array or string do not matter and are ignored. For example:
[undefined,null] -> [12,21]

Test cases
Input -> Output
["a","e","i","o","u"] -> [12345,54321] // valid
[{"a":1},{"b":2},{"c":3}] -> [123,321] // valid
[-1,22,33,44,55,66,77,88,99] -> ["123456789","987654321"] // valid
[0,1] -> [01,10] // invalid, not a 1-based index, `01` is not a valid integer
[1999,2000] -> [12,"21"] invalid, output either integers or strings

Winning criteria
Least bytes.

Isn't this just, "Count up to the array length, then back down?"

Can we output an array containing 2 arrays?

@Quintec Not ideally. That is an unnecessary complication. Though if that is the only way to achieve the approach that you are considering, then do so and provide a note to that caveat of the approach at the answer.

@guest271314 Well remember, this is code golf. If I can output a 2d array if saves me a few bytes.

Although the question is boring and trivial, it should not be closed just because of that...

Python 2, 53 bytes
n=len(input())+1
b=10**n/81-n/9
print[b,10**n/90*n-b]

Try it online!
For example, for \$n=5\$:
\begin{align}
12345 &= 11111 + 1111 + 111 + 11 + 1
\\ &= (11111.\bar1 + 1111.\bar1 + \dots + 1.\bar1) - (0.\bar1 \times 5)
\\ &= \frac{10}{9} \left( \sum_{k=0}^{n-1} 10^{k} \right) - \frac n9
\\ &= \frac{10}{9} \left( \frac{1-10^n}{1-10} \right) - \frac{n}{9}
\\ &= \frac{10^{n+1}-1}{81}-\frac{n+1}{9}
\end{align}
We use integer (floor) division, so the surplus \$\frac{1}{81}\$ gets rounded away.
For the descending part, if b=12345 we compute something like 66666-12345 == 54321.

Can you provide an explanation of the approach?

b=10**n/81-n/9 saves 2

Python 2, 44 bytes
s='123456789'[:len(input())]
print s,s[::-1]

Try it online!

Python 2, 55 52 bytes
a=''
for i in input():a+=`-~len(a)`
print[a,a[::-1]]

Try it online!
Explanation:
# initial value: empty string
a=''
# iterate over input
# will work with any iterable object: list, tuple, dict, set, string, etc.
for i in input():
# add to a string representation of its length+1
    a+=`-~len(a)`
# print list, composed from a and its reversed version
print[a,a[::-1]]

Python 2, 66 bytes
lambda i:`map(abs,range(-len(i),-~len(i)))`[1::3].split('0')[::-1]

Try it online!
Explanation:
lambda i:`map(abs,range(-len(i),-~len(i)))`[1::3].split('0')[::-1]

# unnamed lambda
# example input: ['q', 'w', 'e', 'r', 't']

# create range from minus length of input to length+1
# ['q', 'w', 'e', 'r', 't'] -> [-5,-4,-3,-2,-1,0,1,2,3,4,5]
                  range(-len(i),-~len(i))
# change every value in range to its absolute value
# [-5,-4,-3,-2,-1,0,1,2,3,4,5] -> [5,4,3,2,1,0,1,2,3,4,5]
          map(abs,range(-len(i),-~len(i)))
# get string representaion of list
# [5,4,3,2,1,0,1,2,3,4,5] -> '[5, 4, 3, 2, 1, 0, 1, 2, 3, 4, 5]'
         `map(abs,range(-len(i),-~len(i)))`
# get each third element from string, starting from index 1, returns string
# '[5, 4, 3, 2, 1, 0, 1, 2, 3, 4, 5]' -> '54321012345'
         `map(abs,range(-len(i),-~len(i)))`[1::3]
# split string over '0', returns list of 2 values
# '54321012345' -> ['54321','12345']
         `map(abs,range(-len(i),-~len(i)))`[1::3].split('0')
# reverse list
# ['54321','12345'] -> ['12345','54321']
         `map(abs,range(-len(i),-~len(i)))`[1::3].split('0')[::-1]

Can you provide an explanation of the approach?

@guest271314 Done

Jelly, 6 bytes
J,JṚ$Ḍ

Explanation
J      # Converts an array to [1, ...len(arr)]
 ,     # Paired with
  JṚ$  # The same array as before, reversed.
     Ḍ # Convert the digits to integers.

I'm no Jelly master, so likely sub-optimal.
Try it online!

Alternative equal answer: Jm0ŒHḌ

Hint: can you remove the duplication in the code?

Dunno why it works, but 5 bytes.

@totallyhalloween because $ combines the two links to it's left into a monadic function, so it's a bit like let f(x)=[x,reverse(x)];v=J(leftArgument);v=f(v);v=fromDecimal(v)

05AB1E, 4 bytes
āÂ‚J

Try it online or verify all test cases.
Explanation:
ā       # List in the range [1, length of (implicit) input-list]
        #  i.e. ["a","e","i","o","u"] → [1,2,3,4,5]
 Â      # Bifurcated (short for Duplicate & Reverse copy)
  ‚     # Pair both list into a single list of lists
        #  i.e. [1,2,3,4,5] and [5,4,3,2,1] → [[1,2,3,4,5],[5,4,3,2,1]]
   J    # Join the individual items of the inner lists together (and output implicitly)
        #  i.e. [[1,2,3,4,5],[5,4,3,2,1]] → ["12345","54321"]

Python 2, 64 60 bytes
a=''.join(map(str,range(1,-~len(input()))))
print[a,a[::-1]]

Try it online!
-1 with thanks to @KevinCruijssen
-3 with thanks to @DeadPossum

You can remove the space at print[a] to save a byte.

60 bytes

@KevinCruijssen - I shouldn't have missed that one :-/

Husk, 6 bytes
S¤,d↔ŀ

Try it online!
Explanation
S¤,d↔ŀ  -- input xs (list)
     ŀ  -- indices [1..length xs]
S   ↔   -- do the following with itself and itself reversed:
 ¤,d    -- | undigits and join as tuple

Java (JDK), 76 bytes
a->{String[]r={"",""};int i=1;for(var x:a){r[1]=i+r[1];r[0]+=i++;}return r;}

Try it online!

Tried to find something shorter, but to no avail.. Got 84 bytes by using substrings and 89 by using integer division and modulo.

@KevinCruijssen Hmmm, I tried other versions as well before posting this one, but all used explicit loops. So your ideas were quite different from mine and that's nice :)

That's why I commented it. :) Normally I wouldn't really bother. I also tried oeis.org formulas like floor(10/81 * 10^n - n/9) or (10^n * (9*n-1)+1)/81, but as expected it's way too long due to all the casts and Math.pow: 104 bytes.

MathGolf, 6 bytes
£╒y_xα

Try it online!
£╒y_xα
£       Length of input array
 ╒      Range from 1 to n
  y     Join
   _x   Duplicate and reverse
     α  Wrap top two elements in array

JavaScript (ES6), 43 bytes
Returns an array of 2 strings.
a=>a.map(_=>(a+=++i,b=i+b),i=a=b='')&&[a,b]

Try it online!

Haskell, 42 bytes
-4 bytes thanks to ovs.
((,)=<<reverse).(`take`"123456789").length

Try it online!

((,)=<<reverse).(`take`"123456789").length works for 42 bytes.

((,)<*>reverse).map fst.zip['1'..]

That's a fairly different approach, you can go ahead and post that.

Nah, not that different, feel free to edit it in your post.

Python 2, 52 bytes
x=0
for _ in input():x=x*10+x%10+1
print x,`x`[::-1]

Try it online!

Japt, 9 8 bytes
Êõ ¬pÔò¶

Try it

Explanation
Ê            :Length
 õ           :Range [1,Ê]
   ¬         :Join
    p        :Concatenate
     Ô       : Reverse
      ò      :Partition
       ¶     : Between equal characters

@Downvoter, please have the decency to leave a comment.

Whoever did it downvoted every single answer, so they don't have a reason except being a jerk..

Jelly, 4 bytes
JṚƬḌ

Try it online!
How?
JṚƬḌ - Link: list L    e.g. ['ant','bee','cat','dog','elk','frog']
J    - range of length      [1,2,3,4,5,6]
  Ƭ  - 'till (collect up until results are no longer unique):
 Ṛ   -   reverse                         1:[6,5,4,3,2,1] , 2:[1,2,3,4,5,6]=1st
     -                  ->  [[1,2,3,4,5,6],[6,5,4,3,2,1]]
   Ḍ - from base ten        [123456,654321]

Whoever downvoted all the answers: poor show.

Charcoal, 10 bytes
⟦⭆θ⊕κ⮌⭆θ⊕κ

Try it online! Link is to verbose version of code. Explanation:
  θ    θ    Input array
 ⭆    ⭆     Map over elements and join
    κ    κ  Current index (0-indexed)
   ⊕    ⊕   Increment
     ⮌      Reverse
⟦           Collect into an array

PowerShell, 39 bytes
-join(1..($x=$args.count));-join($x..1)

Try it online!
Takes input via splatting, which on the command-line prompt looks like, e.g., $a=(4,3,2); .\array-to-indices.ps1 @a, and on TIO manifests as separate arguments for each entry.
We take the .count of the input $args, store that into $x. Then construct a range .. from 1 up to $x and -join it into a string. Finally we -join the range the other direction. Those two strings are left on the pipeline and output is implicit.

Clean, 53 bytes
import StdEnv
$l#n=take(size l)['1'..]
=[n,reverse n]

Try it online!

Scala (60 bytes)
def%(s:Seq[Any])={val a=(1 to s.size)mkString;(a,a.reverse)}

Try it online

J, 15 bytes
4(,:|.)@u:48+#\

Try it online!
How it works
4(,:|.)@u:48+#\
             #\  Generate 1-based indices of given array
          48+    Convert digits to ASCII value
4      @u:       Convert to string
 (,:|.)          Append its reverse

JavaScript, 58 bytes
_=>[_.map((_,i)=>t.unshift(++i),t=[]),t].map(_=>+_.join``)

Try it online!
Pass current index of array plus 1 to .unshift() to fill first array with a second array's .length, .join() each resulting array without any characters separating elements and convert to integer. Returns an array of two integers.


text:
Read out the C variable declaration
Background
Variable declaration statement in C consists of three parts: the name of the variable, its base type, and the type modifier(s).
There are three kinds of type modifiers:

Pointer * (prefix)
Array [N] (postfix)
Function () (postfix)

You can specify a list of function arguments inside the parens, but for the sake of this challenge, let's ignore it and just use () (which technically means "the function can take any kind of arguments").

And a way to read out the notations is as follows:
int i;             // i is an int
float *f;          // f is a pointer to a float
my_struct_t s[10]; // s is an array of 10 my_struct_t
int func();        // func is a function returning an int

The catch is that we can mix all of these to form a more complicated type, such as array of arrays or array of function pointers or pointer to array of pointers:
int arr[3][4];
// arr is an array of 3 arrays of 4 ints

int (*fptrs[10])();
// fptrs is an array of 10 pointers to functions returning an int

float *(*p)[16];
// p is a pointer to an array of 16 pointers to float

How did I read these complicated statements?

Start from the variable name. (name) is ...
Select the modifier with the highest precedence.
Read it:

[N] -> array of N ...
() -> function returning ...
* -> pointer to ...

Repeat 2 and 3 until the modifiers are exhausted.
Finally, read the base type. ... (base type).

In C, postfix operators take precedence over prefix operators, and type modifiers are no exception. Therefore, [] and () bind first, then *. Anything inside a pair of parens (...) (not to be confused with function operator) binds first over anything outside.
Illustrated example:
int (*fptrs[10])();
      fptrs           fptrs is ...
           [10]       array of 10 ... // [] takes precedence over *
    (*         )      pointer to ...
                ()    function returning ...
int                   int

Task
Given a line of variable declaration statement written in C, output the English expression that describes the line, using the method shown above.
Input
The input is a single C statement that includes a single base type, a single variable name, zero or more type modifiers and the ending semicolon. You have to implement all the syntax elements covered above, plus:

Both the base type and the variable name match the regular expression [A-Za-z_][A-Za-z0-9_]*.
Theoretically, your program should support unlimited number of type modifiers.

You can simplify other C syntax elements in the following ways (full implementation is also welcome):

The base type is always a single word, e.g. int, float, uint32_t, myStruct. Something like unsigned long long won't be tested.
For the array notation [N], the number N will always be a single positive integer written in base 10. Things like int a[5+5], int a[SIZE] or int a[0x0f] won't be tested.
For the function notation (), no parameters will be specified at all, as pointed out above.
For whitespaces, only the space character 0x20 will be used. You can restrict your program to specific usage of whitespaces, e.g.

Use only one space after the base type
Use a space everywhere between tokens

However, you cannot use two or more consecutive spaces to convey more information than being a token separator.

According to C syntax, the following three combinations are invalid, and thus won't be tested:

f()() Function returning function
f()[N] Function returning array
a[N]() Array of N functions

C developers use these equivalent forms instead (and all of these are covered in the test cases):

(*f())() Function returning pointer to function
*f() Function returning pointer to array's first element
(*a[N])() Array of N pointers to function

Output
The output is a single English sentence. You don't need to (but you can if you wish) respect English grammar, e.g. the use of a, an, the, singular/plural forms, and the ending dot (period). Each word should be separated by one or more whitespaces (space, tab, newline) so the result is human-readable.
Again, here is the conversion process:

Start from the variable name. (name) is ...
Select the modifier with the highest precedence.
Read it:

[N] -> array of N ...
() -> function returning ...
* -> pointer to ...

Repeat 2 and 3 until the modifiers are exhausted.
Finally, read the base type. ... (base type).

Test cases
int i;              // i is int
float *f;           // f is pointer to float
my_struct_t s[10];  // s is array of 10 my_struct_t
int func();         // func is function returning int
int arr[3][4];      // arr is array of 3 array of 4 int
int (*fptrs[10])(); // fptrs is array of 10 pointer to function returning int
float *(*p)[16];    // p is pointer to array of 16 pointer to float

_RANdom_TYPE_123 (**(*_WTH_is_TH15)())[1234][567];
/* _WTH_is_TH15 is pointer to function returning pointer to pointer to array of
   1234 array of 567 _RANdom_TYPE_123 */

uint32_t **(*(**(*(***p)[2])())[123])[4][5];
/* p is pointer to pointer to pointer to array of 2 pointer to function returning
   pointer to pointer to array of 123 pointer to array of 4 array of 5 pointer to
   pointer to uint32_t */

uint32_t (**((*(**(((*(((**(*p)))[2]))())))[123])[4])[5]);
// Same as above, just more redundant parens

some_type (*(*(*(*(*curried_func())())())())())();
/* curried_func is function returning pointer to function returning pointer to
   function returning pointer to function returning pointer to
   function returning pointer to function returning some_type */

Scoring & Winning criterion
This is a code-golf challenge. The program with the smallest number of bytes wins.

Related: https://cdecl.org

int arr[3][4]; is an array of 3 arrays of 4 ints (as you say), or an array of 4 arrays of 3 ints?

@Charlie The former is correct. sizeof(arr[0]) == sizeof(int[4]), so an item of arr contains four ints.

Does the input contain the ; at the end of the line?

Which types do we need to support?

@12431234123412341234123 Everything that matches the regex [A-Za-z_][A-Za-z0-9_]*

You may want to specify that you have to return a sentence as displayed in your description: * to pointer to, [##] to array of ##, () to function returning (with optionally a/an/the to make the sentences more correct). Currently your "The output is a single English sentence." seems to allow any English sentence.

The question states that the syntax []() doesn't need to be supported. However, one of the test cases is int (*fptrs[10])();. Is this test case made valid because there is a ) between the array and the function, or because the * causes it to become "array of pointer to function" instead of "array of function"?

Ew. Nested arrays.

@KamilDrakari It's the latter. "array of pointer to function" is essentially "array of pointer", which is perfectly valid in C.

Just to clarify: will we ever encounter something of the form int x[]; with empty square brackets?

@DLosc No, the square brackets will always contain a positive integer.

K&R book on C I remember has one exercise on this argument

Doesn’t this challenge run the risk of being useful?

I'm reading "Expert C Programming" and came upon the following diagram explaining this process (worth looking at if only for the word boustrophedonically), and immediately thought it would make a good challenge.  You beat me to it by 4 years.

Python 3, 331 312 294 261 240 bytes
from re import*
class V(str):__pos__=lambda s:V(s+'pointer to ');__call__=lambda s:V(s+'function returning ');__getitem__=lambda s,i:V(s+'array of %i '%i)
t,e=input().split()
print(eval(sub('\*','+',sub('(\w+)',r'V("\1 is ")',e[:-1],1)))+t)

Try it online!
-19 bytes by switching to python 2 and putting the class definition into an exec
-18 bytes by changing the regex from [a-zA-Z_][a-zA-Z0-9_]* to \\w+, thanks to Kevin Cruijssen
-33 bytes by working some class definition magic and utilising str, thanks to Lynn, changing back to python 3
-21 bytes by merging together multiple regexes, thanks to infmagic2047
Requires that only one space is contained in the input (between the type and the expression).
I think this is a pretty unique approach to the problem. This mostly uses the fact that Python itself can evaluate strings like (**((*(**(((*(((**(*p)))[2]))())))[123])[4])[5]) and gets the correct sequence of function calls, array indexes and pointers - and that the user can overload these.

Nice approach, +1 from me! You can golf [a-zA-Z_][A-Za-z0-9_]* to [a-zA-Z_]\\w* to save a few bytes. EDIT: Actually, I think you can just use \\w+ instead of [a-zA-Z_][A-Za-z0-9_]*.

I like this approach :) here it is in 253 bytes

That's a good point. 261 it is then.

You can use [0] instead of .group() since Python 3.6.

And here is a 240 bytes version.

Retina 0.8.2, 142 138 128 117 bytes
(\w+) (.+);
($2) $1
\(\)
 function returning
\[(\d+)?]
 array of$#1$* $1
+`\((\**)(.+)\)
$2$1
\*
 pointer to
1`
 is

Try it online! Link includes test cases. Better grammar. Edit: Saved 10 21 bytes by porting @DLosc's Pip solution. Explanation:
(\w+) (.+);
($2) $1

Move the type to the end and wrap the rest of the declaration in ()s in case it contains an outer *.
\(\)
 function returning

Process any functions.
\[(\d+)?]
 array of$#1$* $1

Process any arrays.
+`\((\**)(.+)\)
$2$1

Move any pointers to the end of their brackets, and delete the brackets, repeatedly working from the outermost set of brackets inwards.
\*
 pointer to

Process any pointers.
1`
 is

Insert the is.

Bash + cdecl + GNU sed, 180
cdecl is a venerable Unix utility that does most of what is required here, but in order to match I/O requirements, some sed pre- and post-processing is required:
sed -r 's/^/explain struct /;s/struct (int|char double|float|void) /\1 /;s/\bfunc/_func/g'|cdecl|sed -r 's/^declare //;s/as/is/;s/struct //g;s/([0-9]+) of/of \1/g;s/\b_func/func/g'

No attempts made to correct grammar.

sed Pre-processing:

s/^/explain struct / - Add "explain struct " to the start of every line
s/struct (int|char double|float|void) /\1 / - Remove struct when dealing with C language types
s/\bfunc/_func/g - "func" is recognized as a keyword by cdecl - suppress this

sed Post-processing:

s/^declare // - remove "declare" at start of line
s/as/is/ - self-explanatory
s/struct //g - remove all "struct" keywords
s/([0-9]+) of/of \1/g - correct ordering of "of "
s/\b_func/func/g - revert any "_func" that was replaced in pre-processing

In action:
$ < cdecls.txt sed -r 's/^/explain struct /;s/struct (int|char double|float|void) /\1 /;s/\bfunc/_func/g'|cdecl|sed -r 's/^declare //;s/as/is/;s/struct //g;s/([0-9]+) of/of \1/g;s/\b_func/func/g'
i is int
f is pointer to float
s is array of 10 my_struct_t
func is function returning int
arr is array of 3 array of 4 int
fptrs is array of 10 pointer to function returning int
p is pointer to array of 16 pointer to float
_WTH_is_TH15 is pointer to function returning pointer to pointer to array of 1234 array of 567 _RANdom_TYPE_123
p is pointer to pointer to pointer to array of 2 pointer to function returning pointer to pointer to array of 123 pointer to array of 4 array of 5 pointer to pointer to uint32_t
p is pointer to pointer to pointer to array of 2 pointer to function returning pointer to pointer to array of 123 pointer to array of 4 array of 5 pointer to pointer to uint32_t
curried_func is function returning pointer to function returning pointer to function returning pointer to function returning pointer to function returning pointer to function returning some_type
$

Would it be sufficient to do s/\bfu/_fu/g and save the bytes of the full func replacement?

wait it's a real utility? I've always thought that it's the name of the website

@phuclv cdecl is a real utility, and really useful for checking C declarations.

@phuclv Cdecl was written before the ANSI C standard was completed...

Fails for a variable named as (+4 bytes for spaces to fix). I don't have access to cdecl but I think you can save 64 bytes using sed -r 's/^(\w+)(\W+)/explain struct \1_\2_/'|cdecl|sed -r 's/^declare struct _|_$//;s/ as / is /;s/([0-9]+) of/of \1/g'.

Pip -s, 152 150 148 139 137 126 125 123 120 bytes
Third approach!
YaRs" ("R`\[(\d+)]`` array of \1`R"()"" function returning"L#aYyR`\((\**)(.+)[);]`{c." pointer to"X#b}{[b"is"g@>2a]}Vy^s

Takes the declaration as a command-line input. Try it online!
Explanation
The code is in three parts: initial setup and handling of functions and arrays; a loop that handles parentheses and pointers; and a final rearrangement.
Setup, functions & arrays
We want the whole declaration to be parenthesized (this helps with the loop later on), so we change type ... into type (.... Then, observe that no reordering is done with the descriptions of functions and arrays, so we can perform all those replacements first without affecting the final output.
Y                         Yank into y variable...
 a                        The result of a (the cmdline arg)...
  R s                     Replace the space
   " ("                    with " ("
  R `\[(\d+)]`            Replace digits in square brackets
   ` array of \1`          with " array of <digits>"
  R "()"                  Replace function parens
   " function returning"   with " function returning"

If our original input was float *((*p()))[16];, we now have float (*((*p function returning)) array of 16;.
Parentheses and pointers
We run a loop replacing the outermost pair of parentheses and any asterisks that are immediately inside the opening paren.
L#a                     Loop len(a) times (enough to complete all replacements):
 Y                      Yank into y variable...
  y                     The result of y...
   R `\((\**)(.+)[);]`  Replace open paren, 0 or more asterisks (group 1), 1 or more
                        characters (group 2), and close paren or semicolon
    {                    with this callback function (b = group 1, c = group 2):
     c .                 The stuff in the middle, concatenated to...
      " pointer to"      that string
       X #b              repeated len(asterisks) times
    }

Example steps:
float (*((*p function returning)) array of 16;
float ((*p function returning)) array of 16 pointer to
float (*p function returning) array of 16 pointer to
float p function returning pointer to array of 16 pointer to

Cleanup
The only thing remaining is to move the type to the end and add "is":
{[b"is"g@>2a]}Vy^s
               y^s  Split y on spaces
{            }V     Use the resulting list as arguments to this function:
 [          ]        Return a list of:
  b                   2nd argument (the variable name)
   "is"               That string
       g@>2           All arguments after the 2nd
           a          1st argument (the type)
                    The resulting list is printed, joining on spaces (-s flag)

For definitions like int x;, this approach will result in an extra space, which is permitted by the challenge.

Java 11, 469 467 463 450 bytes
s->{String r="",t,S[];for(s=s.replace("()","~");s.contains("(");s=s.replace(t,"").replace("()",""),r+=t+";")t=s.replaceAll(".*(\\([^()]+\\)).*","$1");S=s.split(" ");t=S[0];r+=r.isEmpty()?S[1]:s;S=r.split(";");r=S[0].replaceAll(".*?(\\w+).*","$1 is ");for(var p:S)r+=p.replaceAll("[A-Za-z_]+\\d+|[^\\[\\d]","").replaceAll("\\[(\\d+)","array of $1 ")+(p.contains("~")?"function returning ":"")+"pointer to ".repeat(p.split("\\*").length-1);return r+t;}

Try it online.
Explanation:
s->{               // Method with String as both parameter and return-type
  String r="",     //  Result-String, starting empty
         t,        //  Temp-String, starting uninitialized
         S[];      //  Temp String-array, starting uninitialized
  for(s=s.replace("()","~");
                   //  Replace all "()" in the input `s` with "~"
      s.contains("(");
                   //  Loop as long as the input `s` still contains "("
      ;            //    After every iteration:
       s=s.replace(t,"")
                   //     Remove `t` from `s`
          .replace("()",""),
                   //     And also remove any redundant parenthesis groups
       r+=t+";")   //     Append `t` and a semi-colon to the result-String
    t=s.replaceAll(".*(\\([^()]+\\)).*","$1");
                   //   Set `t` to the inner-most group within parenthesis
  S=s.split(" ");  //  After the loop, split the remainder of `s` on the space
  t=S[0];          //  Set `t` to the first item (the type)
  r+=              //  Append the result-String with:
    r.isEmpty()?   //   If the result-String is empty
                   //   (so there were no parenthesis groups)
     S[1]          //    Set the result-String to the second item
    :              //   Else:
     s;            //    Simple append the remainder of `s`
  S=r.split(";");  //  Then split `r` on semi-colons
  r=S[0].replaceAll(".*?(\\w+).*",
                   //  Extract the variable name from the first item
     "$1 is ");    //  And set `r` to this name appended with " is "
  for(var p:S)     //  Loop over the parts split by semi-colons:
    r+=            //   Append the result-String with:
      p.replaceAll("[A-Za-z_]+\\d+
                   //    First remove the variable name (may contain digits)
         |[^\\[\\d]","")
                   //    And then keep only digits and "["
       .replaceAll("\\[(\\d+)",
                   //    Extract the number after "["
         "array of $1 ")
                   //    And append the result-String with "array of " and this nr
      +(p.contains("~")?
                   //    If the part contains "~"
         "function returning "
                   //     Append the result-String with "function returning "
       :           //    Else:
        "")        //     Leave the result-String the same
      +"pointer to ".repeat(
                   //    And append "pointer to " repeated
         p.split("\\*").length-1);
                   //    the amount of "*" in the part amount of time
  return r         //  Then return the result-String
          +t;}     //  appended with the temp-String (type)

Fails on the test case with redundant parentheses.

@Bubbler Ah, didn't notice that new test case. Luckily it's an easy fix.

JavaScript (ES6), 316 ... 268 253 bytes
s=>(g=s=>[/\d+(?=])/,/\*/,/!/,/.+ /,/\w+/].some((r,i)=>(S=s.replace(r,s=>(O=[O+`array of ${s} `,O+'pointer to ','function returning '+O,O+s,s+' is '+O][i],'')))!=s)?g(S):'',F=s=>(O='',S=s.replace(/\(([^()]*)\)/,g))!=s?O+F(S):g(s)+O)(s.split`()`.join`!`)

Try it online!
Commented
Helper function
g = s =>                             // s = expression to parse
  [                                  // look for the following patterns in s:
    /\d+(?=])/,                      //   array
    /\*/,                            //   pointer
    /!/,                             //   function
    /.+ /,                           //   type
    /\w+/                            //   variable name
  ].some((r, i) =>                   // for each pattern r at index i:
    ( S = s.replace(                 //   S = new string obtained by removing
      r,                             //       the pattern matching r from s
      s => (                         //     using the first match s and the index i,
        O = [                        //     update the output O:
          O + `array of ${s} `,      //       array
          O + 'pointer to ',         //       pointer
          'function returning ' + O, //       function
          O + s,                     //       type
          s + ' is ' + O             //       variable name
        ][i],                        //
        ''                           //     replace the match with an empty string
    )))                              //   end of replace()
    != s                             //   make some() succeed if S is not equal to s
  ) ?                                // end of some(); if truthy:
    g(S)                             //   do a recursive call with S
  :                                  // else:
    ''                               //   stop recursion and return an empty string

Main part
s => (                 // s = input
  g = …,               // define the helper function g (see above)
  F = s => (           // F = recursive function, taking a string s
    O = '',            //   O = iteration output, initialized to an empty string
    S = s.replace(     //   S = new string obtained by removing the next expression from s
      /\(([^()]*)\)/,  //     look for the deepest expression within parentheses
      g                //     and process it with the helper function g
    )                  //   end of replace()
  ) != s ?             // if S is not equal to s:
    O + F(S)           //   append O to the final output and do a recursive call with S
  :                    // else (we didn't find an expression within parentheses):
    g(s) + O           //   process the remaining expression with g and return O
)(s.split`()`.join`!`) // initial call to F with all strings '()' in s replaced with '!'

I was wondering why you used [...s.split`()`.join`!`] instead of just [...s.replace('()','!')], but I realized it's the exact same byte-count.. :)

@KevinCruijssen The primary reason is that s.replace('()','!') would only replace the first occurrence.

Ah, of course. Forgot JS replace isn't the same as Java's. In Java .replace replaces all occurrences, and .replaceAll replaces all occurrences with regex enabled. Always thought the naming was quite bad for these two methods in Java, as I would have called them .replaceAll and .regexReplaceAll or something along those lines, but I guess for codegolf it's shorter as .replace and .replaceAll.

BTW, I noticed that you were using the same technique (with ~) just after posting the first version of my own answer. Great minds think alike, I suppose. :p

Perl 6, 209 190 171 162 153 bytes
{~({(.[1]Z'is'),.<e>.&?BLOCK,('array of'X .[2]),('function returning','pointer to'Zxx.[3,0])if $_}(m:g/(\*)*[(\w+)+|\(<e=~~>.][\[(\d+).]*(\(.)*/[1]),$0)}

Try it online!
Recursive regex approach. Produces some extra space characters which can be avoided at the cost of 3 bytes.
Explanation
{     # Anonymous block
 ~(   # Convert list to string
   {  # Block converting a regex match to a nested list
     (.[1]            # Array of 0 or 1 variable names
       Z'is'),        # zipped with string "is"
     .<e>.&?BLOCK,    # Recursive call to block with subexpression
     ('array of'      # String "array of"
       X .[2]),       # prepended to each array size
     ('function returning',  # Strings "function returning"
      'pointer to'           # and "pointer to"
      Zxx             # zipped repetition with
      .[3,0])         # number of function and pointer matches
     if $_            # Only if there's an argument
   }
   (             # Call block
     m:g/        # Input matched against regex
      (\*)*      # Sequence of asterisks, stored in [0]
      [          # Either
       (\w+)+    # the variable name, stored as 1-element array in [1]
       |         # or
       \(        # literal (
         <e=~~>  # the same regex matched recursively, stored in <e>
       .         # )
      ]
      [\[(\d+).]*  # Sequence of "[n]" with sizes stored in [2]
      (\(.)*       # Sequence of "()" stored in [3]
     /
     [1]  # Second match
   ),
   $0     # First match (base type)
 )
}

Clean, 415 bytes
import StdEnv,Text
$s#(b,[_:d])=span((<>)' ')(init s)
=join" "(?d++[""<+b])
?[]=[]
?['()':s]=["function returning": ?s]
?['*':s]= ?s++["pointer to"]
?['[':s]#(n,[_:t])=span((<>)']')s
=["array of "<+n: ?t]
?s=case@0s of(['(':h],t)= ?(init h)++ ?t;(h,t)|t>[]= ?h++ ?t=[h<+" is"]
~c=app2((++)[c],id)
@n[c:s]=case c of'('= ~c(@(n+1)s);')'|n>1= ~c(@(n-1)s)=([c],s);_|n>0= ~c(@n s)=span(\c=c<>'('&&c<>'[')[c:s]
@_ e=(e,e)

Try it online!

R, 225 218 bytes
g=gsub
"&"="@"=paste
"["=function(a,b)a&"array of"&b
"+"=function(a)a&"pointer to"
eval(parse(t=g('\\(\\)','@"function returning"',g('(\\w+) (.*?)([A-Za-z_]\\w*)(.*);','\\2"\\3 is"\\4&"\\1"',g('\\*','+',readline())))))

Try it online!
Full program, wrapped in a function on TIO for convenient testing of all test cases at once.
First, we use Regex to convert the input of the form type ...name...; to ..."name is"..."type". Function notation () is then converted to text with a high-precedence concatenation operator. Unfortunately, we also have to replace * with + as the former is not acceptable as an unary operator. The rest is done by R's eval with overloaded operators.

APL (Dyalog Unicode), 192 190 bytes
Saved 2 bytes thanks to @Razetime
'(\w+) is(.+);'⎕R'\2 \1'((('\*',z)⎕R'\1 pointer to'((∊'\('z'\)')(z,'\[(\d+)\]')('\(\)',⍨z←'([A-Za-z0-9_ ]+)')⎕R'\1' '(\1 array of \2)' '(\1 function returning)'))⍣≡'(\w+)(?!\]|\w)'⎕R'\1 is')

Try it online!
This came out longer than I thought. I may have to go back to using parser combinators instead of just plain regex again.
z matches an English phrase such as "foo is pointer to". The parentheses allow the capturing group to be used later.
The main train first adds " is" to such phrases, so int (*p[3])() becomes int is(*p is[3])(). The negative lookahead (?!\]|\w) is used to avoid matching array dimensions.
Then ⍣≡ keeps applying the substitutions to the left of it until there is nothing left to replace. First, parentheses around phrases are removed, z[d] is replaced with (z array of d), and z() is replaced with (z function returning). The parentheses are necessary in case there are multidimensional arrays - we don't want *z to be replaced before we come back to the rest of the dimensions. Then *z is replaced with z pointer to. So int is(*p is[3])() becomes int is(*(p is array of 3))() -> int is(p is array of 3 pointer to)() -> int isp is array of 3 pointer to function returning.
The last part matches the pattern TYPE isFIRST_PART; and rearranges it to become FIRST_PART TYPE.

A reminder in case you forgot to apply for my APL bounty.

I was going to try to shorten it first, just haven’t had the time for it.

Looks like this isn't going to be golfed any further.

you can use ∊'\('z'\)' instead of '\(',z,'\)' for -1. Inlining the declaration of z as ('\(\)',⍨z←'([A-Za-z0-9_ ]+)') should also reduce a byte.

@Razetime Thanks! I should have thought of inlining z

Red, 418 410 bytes
func[s][n: t:""a: charset[#"a"-#"z"#"A"-#"Z"#"0"-#"9""_"]parse s[remove[copy x thru" "(t: x)]to a
change[copy x[any a](n: x)]"#"]b: copy[]until[c: next find s"#"switch c/1[#"("[append
b"function returning"take/part c 2]#"["[parse c[remove[skip copy d to"]"(append b
reduce["array of"d])skip]]]#")"#";"[take c c: back back c while[#"*"= c/1][take c
c: back c append b"pointer to"]take c]]s =""]reduce[n"is"b t]]

Try it online!
Explanation:
f: func [ s ] [
    n: t: 0                                         ; n is the name, t is the type
    a: charset [ #"a"-#"z" #"A"-#"Z" #"0"-#"9" "_" ]; characters set for parsing
    parse s[                                        ; parse the input with the following rules
        remove [ copy x thru " " ](t: x)            ; find the type, save it to t and remove it from the string
        to a                                        ; skip to the next alphanumerical symbol
        change [ copy n [ any a ] (n: x) ] "#"      ; save it to n and replace it with '#'
    ]
    b: copy [ ]                                     ; block for the modifiers
    until [                                         ; repeat
       c: next find s "#"                           ; find the place of the name
       switch c/1 [                                 ; and check what is the next symbol
           #"(" [ append b "function returning"     ; if it's a '('- it's a function - add the modifier
                  take/part c 2                     ; and drop the "()"
                ]
           #"[" [ parse c [                         ; '[' - an array
                     remove [ skip copy d to "]"    ; save the number
                             (append b reduce [     ; and add the modifier
                                  "array of" d
                              ] )
                             skip ]                 ; and remove it from the string
                     ]
                ]
           #")"                                     ; a closing bracket
           #";" [ take c                            ; or ';' - drop it
                    c: back back c                  ; go to the left
                    while [ #"*" = c/1 ]            ; and while there are '*'
                    [
                        take c                      ; drop them
                        c: back c                   ; go to the left
                        append b "pointer to"       ; add the modifier
                    ]
                    take c                          ; drop '(' (or space)
                 ]
       ]
       s = ""                                       ; until the string is exhausted
    ]
    reduce [ n "is" b t ]                     ; display the resul
]

JavaScript 250 Bytes [249?]
This uses 250 Bytes:
k=>(a=k.match(/\W|\w+/g),s=[v=j=r=""],f=y=>!j&!a[i+1]||(m=a[i],v?(r+=v=m=='['?`array of ${a[i+=3,i-2]} `:m<')'?(i+=2,"function returning "):s[j-1]=='*'?j--&&"pointer to ":""):m==')'?v=j--|i++:m<'+'?s[j++]=a[i++]:r+=a[v=i++]+" is ",f(),r+a[0]),f(i=2))

Explanation:
Basically, it's reading from a buffer a, which is the tokenized input. It continuously moves tokens from the buffer a to a stack s, until evaluation mode is triggered. Evaluation mode will consume postfix operations first (), [] from the buffer, and then it will consume the prefix operator * from the stack. Evaluation mode is triggered when the state is where a word would be (Either the typename is found and consumed, or an ending ) is found and removed). Evaluation mode is deactivated when no more prefix/postfix operators are found.
k=>( // k is input
    a=k.match(/\W|\w+/g), // split by symbol or word
    s=[v=j=r=""], // j=0, v=false, r="", s=[]
    // s is the stack, r is the return string,
    // v is true if we're in evaluation mode (Consume (), [], *)
    // v is false if we're waiting to see a ) or token, which triggers evaluation
    // j is the index of the top of the stack (Stack pointer)
    f=y=>!j&!a[i+1]||( // !j means stack is empty, !a[i+1] means we're at the ;
        m=a[i], // Save a[i] in a variable
        v // Are we evaluating?
        ?(
        r+=v=
            m=='[' // Array
            ?`array of ${a[i+=3,i-2]} ` // Skip three tokens: "[", "10", "]"
                                        // a[i-2] is the "10"
            :m<')' // m == '('
                ?(i+=2,"function returning ") // Skip two tokens: "(", ")"
                :s[j-1]=='*' // Stack has a pointer
                    ?j--&&"pointer to " // Pop the stack
                    :"" // Set v to be false, r+=""
        )
        :m==')'
            ?v=j--|i++ // Pop the '(', skip over the ')', v = Evaluation mode
            :m<'+' // m == '*' || m == '('
                ?s[j++]=a[i++] // push(s, pop(a))
                :r+=a[v=i++]+" is " // Otherwise we have the token
        , f(), r+a[0] // Recurse f(), and return r+a[0]. a[0] is the type.
    ),
    f(i=2) // Set i=2, and call f(), which returns the final value r + type
    // a = ["type", " ", ...], so i=2 give the first real token
    // This soln assumes there is only one space, which is an allowed assumption
)

NOTE
If I understand "Use a space everywhere between tokens" correctly:
k=>(a=k.split(" "),s=[v=j=r=""],f=y=>!j&!a[i+1]||(v?(r+=v=a[i]=='['?`array of ${a[i+=3,i-2]} `:a[i]<')'?(i+=2,"function returning "):s[j-1]=='*'?j--&&"pointer to ":""):a[i]==')'?v=j--|i++:a[i]<'+'?s[j++]=a[i++]:r+=a[v=i++]+" is ",f(),r+a[0]),f(i=1))

is technically valid, and uses
249 Bytes
Assuming that there's a space between every token.

This took me many many hours, despite it looking straightforward. I probably knocked 5-10 bytes / hour, starting with 350 chars. I do indeed have no life.

I was at about 325 when I thought "I hit optimality with my current algorithm - rip", but then for some reason I was still able to knock 5-10 / hour, despite each knock being followed by "Okay, this is definitely the optimal result". Hitting 250 was arbitrary since it was the first to beat the reigning 253, so even though I still say "Okay, this is definitely the optimal result", there might still be more to optimize.

APL(NARS), chars 625, bytes 1250
CH←⎕D,⎕A,⎕a,'_'⋄tkn←nm←∆←''⋄in←⍬⋄⍙←lmt←lin←0
eb←{∊(1(0 1 0)(0 1)(1 0))[⍺⍺¨⍵]}
tb←{x←({⍵='[':3⋄⍵=']':4⋄⍵∊CH,' ':1⋄2}eb⍵)\⍵⋄(x≠' ')⊂x}

gt
tkn←''⋄→0×⍳⍙>lin⋄tkn←∊⍙⊃in⋄⍙+←1⋄→0×⍳(⍙>lin)∨'('≠↑tkn⋄→0×⍳')'≠↑⍙⊃in⋄tkn←tkn,⍙⊃in⋄⍙+←1

r←dcl;n
   n←0
B: gt⋄→D×⍳'*'≠↑tkn⋄n+←1⋄→B×⍳tkn≢''
D: r←ddcl⋄∆←∆,∊n⍴⊂'pointer to '

r←ddcl;q
   r←¯1⋄→0×⍳0>lmt-←1
   →A×⍳∼'('=↑tkn⋄q←dcl⋄→F×⍳')'=↑tkn⋄→0
A: →B×⍳∼(↑tkn)∊CH⋄nm←tkn⋄→F
B: r←¯2⋄→0
F: gt⋄→G×⍳∼tkn≡'()'⋄∆←∆,'function that return '⋄→F
G: →Z×⍳∼'['=↑tkn⋄∆←∆,'array of ',{''≡p←(¯1↓1↓tkn):''⋄p,' '}⋄→F
Z: r←0

r←f w;q
   nm←∆←''⋄in←tb w⋄⍙←1⋄lin←↑⍴in⋄lmt←150⋄gt⋄→A×⍳∼0>q←dcl⋄r←⍕q⋄→0
A: r←nm,' is a ',∆,1⊃in

this is just one traslation from C language to APL from code in the book: "Linguaggio C"
by Brian W. Kerninghan and Dennis M. Ritchie chapter 5.12. I don't know how reduce all that
because i had not understood 100% that code, and because I do not know too much on APL...
The function for exercise it is f; i think are only allowed 150 nested parentesis '(' ')'
for error return one strign with one negative value in that or the string descrition
if all is ok. It seems this is not better than the other version even if less chars because
the other sees the errors better. Some test:
  f 'int f()()'
f is a function that return function that return int
  f 'int a[]()'
a is a array of function that return int
  f 'int f()[]'
f is a function that return array of int
  f 'int i;'
i is a int
  f 'float *f;'
f is a pointer to float
  f 'my_struct_t s[10];'
s is a array of 10 my_struct_t
  f 'int func();'
func is a function that return int
  f 'int arr[3][4];'
arr is a array of 3 array of 4 int
  f 'int (*fptrs[10])();'
fptrs is a array of 10 pointer to function that return int
  f 'float *(*p)[16]; '
p is a pointer to array of 16 pointer to float
  f '_RANdom_TYPE_123 (**(*_WTH_is_TH15)())[1234][567];'
_WTH_is_TH15 is a pointer to function that return pointer to pointe
  r to array of 1234 array of 567 _RANdom_TYPE_123
  f 'uint32_t (**((*(**(((*(((**(*p)))[2]))())))[123])[4])[5]);'
p is a pointer to pointer to pointer to array of 2 pointer to funct
  ion that return pointer to pointer to array of 123 pointer to
   array of 4 array of 5 pointer to pointer to uint32_t

source: Stack Exchange

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

sort: votes


text:
Smoothing a pair of arrays
Input
Two lists with binary values (list_a, list_b) of equal length=>3.
Output
Two lists with binary values (smoothed_a, smoothed_b) with minimal Forward Difference while keeping the same sum before and after processing sum(list_a) + sum(list_b) == sum(smoothed_a) + sum(smoothed_b).
Forward Difference being the absolute difference between items. For example:

[0, 1, 0] would be sum(abs([1, -1])) => 2
[1, 1, 1] would be sum(abs([0, 0])) => 0

Illustrative test cases
Formatted as (list_a, list_b) => (smoothed_a, smoothed_b)
([0, 0, 1, 0, 0],
 [1, 1, 0, 1, 1])
=>
([0, 0, 0, 0, 0],
 [1, 1, 1, 1, 1])

The sum of both arrays pairs is 5. The forward difference was minimized to 0.
([1, 0, 1, 0, 1],
 [0, 0, 0, 1, 0])
=>
([0, 1, 1, 1, 1],
 [0, 0, 0, 0, 0])

The sum of both arrays pairs is 4. The forward difference was minimized to 1.
Test cases
Formatted as (list_a, list_b): forward_diff => (smoothed_a, smoothed_b): min_diff where (smoothed_a, smoothed_b) are potential solutions.
([0, 0, 1],
 [0, 1, 0]): 3
([0, 0, 0],
 [0, 1, 1]): 1

([1, 1, 1],
 [0, 0, 0]): 0
([1, 1, 1],
 [0, 0, 0]): 0

([0, 1, 0],
 [1, 0, 1]): 4
([0, 0, 0],
 [1, 1, 1]): 0

([1, 1, 1, 1],
 [0, 0, 0, 0]): 0
([1, 1, 1, 1],
 [0, 0, 0, 0]): 0

([1, 0, 1, 1],
 [0, 0, 0, 1]): 3
([1, 1, 1, 1],
 [0, 0, 0, 0]): 0

([1, 0, 0, 1],
 [0, 0, 0, 1]): 2
([1, 1, 1, 0],
 [0, 0, 0, 0]): 1

([1, 1, 0, 1],
 [1, 0, 1, 0]): 3
([1, 1, 1, 1],
 [1, 0, 0, 0]): 1

So, if I understand right, "forward difference" means $\sum_{i} | x_i - x_{i+1} |$?

@Rogem that is correct

Jelly, 3 bytes
FṢṁ

Try it online!
Explanation:

Flatten the list
Ṣort the flattened list
ṁold the sorted flatten list in the shape of the input.

Retina, 4 bytes
O`\d

My shortest Retina answer thus far.
Try it online or verify all test cases.
Explanation:
Sorts all digits in the input, and leaves every other character unchanged (including their positions).

Python 2, 51 bytes
def f(a,b):s=sorted(a+b);l=len(a);print s[:l],s[l:]

Try it online!
Function that prints to STDOUT.

Husk, 3 bytes
½OΣ

Try it online!

½OΣ – Full program. Takes a list of two lists from the first CLA, outputs to STDOUT.
  Σ – Flatten (i.e. concatenate the contents of the 2 lists together).
 O  – Sort.
½   – Divide list in two halves (i.e. partition it into two equal-length sublists).

J, 7 bytes
$$/:~@,

explanation
$            NB. use the input shape
  $          NB. to shape the result of...
    /:~      NB. sorting the input
        @,   NB. after flattening it

Try it online!

R, 57 bytes
function(a,b,s=1:sum(a|1),x=sort(c(a,b)))list(x[s],x[-s])

Try it online!

Scala, 60 bytes
def^(a:List[Int],b:List[Int])=(a:::b).sorted.splitAt(a.size)

Try it online!

C gcc compile flag 64bit, 31 bytes by Rogem
-Df(a,n)=qsort(a,n+n,4,"\x8b\x07+\x06\xc3")

Try it online!
C gcc 32bit, 37 bytes
f(a,n){qsort(a,n+n,4,"YXZ\x8B\x00+\x02QQQ\xC3");}
struct {
    int a[5], b[5];
} test;
int main() {
    test.a[0] = test.a[2] = test.b[1] = 1;
    f(&test, 5);
    printf ("%d%d%d%d%d\n", test.a[0], test.a[1], test.a[2], test.a[3], test.a[4]);
    printf ("%d%d%d%d%d\n", test.b[0], test.b[1], test.b[2], test.b[3], test.b[4]);
    return 0;
}

Written non-ASCII to \x?? so se won't eat

Should probably mention that the input should be provided as a pointer to the first element of the list of lists.

@Rogem x86 and x64 use different calling method, so they can't have same asm  code

unfortunately, I do not have a 32-bit x86 to test it with, but the instructions 8b (MOV), 2b (SUB), c3 (RET) are shared between the two. This google hit seems to suggest that the registers would also be shared (in this case: eax, rdi, rsi)

@Rogem No. x86 use cdecl that push everything via stack

Alright, won't argue since I don't know.

Suggest adding -zexecstack to both versions, replacing \x0n with \n and adding -m32 to the compiler argument of the i386 version.

05AB1E, 4 bytes
˜{2ä

Try it online or verify all test cases.
Explanation:
˜       # Flatten the (implicit) input list of lists
 {      # Sort it
  2ä    # Split it into two equal-sized lists (and output implicitly)

Charcoal, 14 bytes
⪪⭆⊗Ｌθ‹ι№⁺θη¹Ｌθ

Try it online! Link is to verbose version of code. Explanation: Charcoal doesn't have a sort atom, but all we need to do is to put all the 1s at the front of the list, which is done by counting them and then setting that many list entries to 1 and the remaining ones to 0:
    θ           First input
   Ｌ            Length
  ⊗             Doubled
 ⭆              Map over implicit range and join
         θ      First input
          η     Second input
        ⁺       Concatenate
           ¹    Literal 1
       №        Count matches
      ι         Current index
     ‹          Less than
             θ  First input
            Ｌ   Length
⪪               Split into strings of that length
                Implcitly print each string on its own line

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


text:
Choose the Most Dramatic Outcome
The premise of this is simple: A 10% chance is pretty unlikely, but everyone knows that a one-in-a-million chance is a sure thing!
So, write code that implements the following "dramatic" probability rules:

Take in a floating point P from 0 to 1 representing the unmodified chance of some plot-related event, and a boolean representing whether we're in the climax or not.
Determine P' on these conditions:

If 0 < P ≤ 10-3 then P' = 1.
If .999 ≤ P < 1 then P' = 0.
If P = 0 and we're in the climax, then the heroes will likely get a last-minute sudden advantage and P' = .9.
If P = 1 and we're in the climax, then the villain will unveil an as-yet-unseen superweapon and P' = .1.
Otherwise, P' = P.

Return truthy or falsey based on P' as the chance of truth. For example, if P' = .7, then you should return truthy 70% of the time and falsey 30% of the time.

Shortest code in bytes wins!

See also Million-to-one chance quote.

@Neil Discworld has literal Random Number Gods?

Discworld has all possible Gods, but only the ones that get believed in have any power.

Alternative title: "Does your language have a terse if-else ternary operator?"

05AB1E,  44  42 bytes
Crossed out  44  is no longer 44 :)
_i90*ë¹₄*©1›i1₄®-‹i¹т*ë¹iiTëтë0ëт]5°<Ý₄/Ω›

Port of my Java 8 answer.
First input is P, second input is 0/1 for truthy/falsey whether there is a climax.
Try it online.
Explanation:
_i                     # If the first (implicit) input is exactly 0:
  90                   #  Push 90
    *                  #  Multiply it with the second (implicit) input (0 if 0, 90 if 1)
 ë                     # Else:
  ¹₄*                  #  Push the first input, and multiply it by 1000
     ©                 #  Save it in the register (without popping)
      1›i              #  If it's larger than 1 (so input larger than 0.001):
          ₄®-          #   Push 1000, and subtract the value from the register
         1   ‹i        #   If it's smaller than 1 (so input smaller than 0.999):
               ¹т*     #    Push the first input multiplied by 100
              ë        #   Else:
               ¹i      #    If the first input is exactly 1:
                 i     #     If the second (implicit) input is 1:
                  T    #      Push 10
                 ë     #     Else:
                  т    #      Push 100
                ë      #    Else:
                 0     #     Push 0
          ë            #  Else:
           т           #   Push 100
   ]                   # Close all if-else clauses
    5°                 # Push 100000 (10**5)
      <                # Decrease it by 1: 99999
       Ý               # Create a list in the range [0,99999]
        ₄/             # Divide it by 1000: [0,0.001,0.002,...,99.997,99.998,99.999]
          Ω            # Take a random value from the list
           ›           # Check if the earlier value is larger than this random value
                       # (and output implicitly)

05AB1E has no builtin for a random decimal value in the range [0, 1), so I use 5°<Ý₄/ to generate a list in the range [0,99.999] in steps of 0.001 and then Ω to take a random value from that list (and I use percentages [0, 100] instead of decimals [0, 1] in the rest of my code).

R, 86 bytes
function(a,b,d=a*(1-a))runif(1)<="if"(d,"if"(d>999e-6,a,1-round(a)),"if"(b,.9-.8*a,a))

Try it online!
a is P' and b is 1 or 0 for "in the climax" or not.
If a is 0 or 1, then d will be 0, in which case if b is 0 just return a, otherwise .9 minus .8*a.
Otherwise if a is not near 0 or 1, d will be "far" from 0 so return a. Otherwise 1-round(a) will take a to the "opposite" 0 or 1.
Then see if a random selection from [0,1] is less than or equal to the resulting probability.
The link does a little simulation for all the possible scenarios to demonstrate that it all seems to work.

Where did you get the 999e-6 from?

Since 0 <= a <= 1, d will be bigger than 999e-6 = 0.000999 exactly when a < 0.001 or a  > 0.999.

Huh, I was wondering how you could take advantage of the symmetry in the sandbox, you seem to have figured it out.

Also, you can save bytes on parentheses by setting d to a-a*a.

C (gcc), 82 bytes
Zero bytes of source code. Use the preprocessor directive:
-Df(p,c)=rand()<~(1<<31)*(c&p==0?.9:p==1&c?.1:(p<=1e-3|p>=.999)&p!=1&p!=0?p<.1:p)

Try it online!
Very little to explain about it; p is the probability, c the climax boolean. Main golfing trick is ~(1<<31), which seems to be the equivalent to RAND_MAX for gcc. The usual C golfing tricks go straight out the window with floating points.

Java 8, 65 bytes
P->C->Math.random()<(P==0?C?.9:0:P>.001?P<.999?P:P==1?C?.1:1:0:1)

Try it online.
Explanation:
We have the following scenario combinations to consider:
P=0, C=falsey             → 100% falsey
P=0, C=truthy             → 90% truthy; 10% falsey
P=(0,0.001], C=either     → 100% truthy
P=(0.001,0.999), C=either → (P*100)% truthy; (100-P*100)% falsey
P=[0.999,1), C=either     → 100% falsey
P=1, C=truthy             → 10% truthy; 90% falsey
P=1, C=falsey             → 100% truthy

Which gives us the following code:
P->C->           // Method with double and boolean parameters and boolean return-type
  Math.random()  //  Random value in the range [0, 1)
   <(P==0?       //  If P is 0:
      C?         //   And there is a climax:
       .9        //    Check if the random value is smaller than 0.9 (90% true)
      :          //   Else:
       0         //    Check if the random value is smaller than 0 (0% true)
    :P>.001?     //  Else-if P is larger than 0.001:
      P<.999?    //   If P is smaller than 0.999, so in range (0.001,0.999):
       P         //    Check if the random value is smaller than P (P*100% true)
      :P==1?     //   Else-if P is 1:
       C?        //    And there is a climax:
        .1       //     Check if the random value is smaller than 0.1 (10% true)
       :         //    Else:
        1        //     Check if the random value is smaller than 1 (100% true)
      :          //   Else, so P is in the range [0.999,1):
       0         //    Check if the random value is smaller than 0 (0% true)
    :            //  Else, so P is in the range (0,0.001]:
     1)          //   Check if the random value is smaller than 1 (100% true)

Perl 6, 54 bytes
{(($/=1-$^p min$p)??.001>=$/||$/!!$^c*.9)>rand^^$p>.5}

Try it online!
Explanation
{
 (
  ($/=1-$^p min$p)    # Compute min(p,1-p) and store in $/
  ??                  # if $/ > 0
    .001>=$/||        #   if $/ <= 0.001 then 1
    $/                #   else $/
  !!$^c*.9            # else 0.9 * climax
 )>rand               # Random Bool with given probability
 ^^$p>.5              # Flip if p > 0.5
}

Perl 5 -pl, 61 bytes
$_=(!$_?<>?.9:0:$_==1?<>?.1:1:$_<=.001||($_<.999&&$_))>rand<>

Try it online!
Input is on two lines.  First line is P; second line is 0 if not in climax, 1 if in climax.

Python 3, 118 bytes
from random import *
def f(p,c):
if c:
 if p==1:p=.9
 if p==0:p=.1
if p<1e-3:p=1
if p>.999:p=0
return random()<p

Inputs: p is initial probability, c is climax


text:
New Neighbour Sequence
The non-negative integers are bored of always having the same two* neighbours, so they decide to mix things up a little. However, they are also lazy and want to stay as close as possible to their original position.
They come up with the following algorithm:

The first element is 0.
The \$n^{th}\$ element is the smallest number which is not yet present in the sequence and which is not a neighbour of the \$(n-1)^{th}\$ element.

This generates the following infinite sequence:
0,2,4,1,3,5,7,9,6,8,10,12,14,11,13,15,17,19,16,18,20,22,24,21,23,25,27,29,26,28 ...

0 is the first element. 1 is the smallest number not yet in the sequence, but it is a neighbour of 0. The next smallest number is 2, so it is the second element of the sequence. Now the remaining numbers are 1,3,4,5,6,..., but as both 1 and 3 are neighbours of 2, 4 is the third member of the sequence. As 1 is not a neighbour of 4, it can finally take its place as fourth element.
The Task
Write a function or program in as few bytes as possible which generates the above sequence.
You may

output the sequence infinitely,
take an input \$n\$ and return the \$n^{th}\$ element of the sequence, or
take an input \$n\$ and return the first \$n\$ elements of the sequence.

Both zero- or one-indexing is fine in case you choose one of the two latter options.
You don't need to follow the algorithm given above, any method which produces the same sequence is fine.

Inspired by Code golf the best permutation. Turns out this is A277618.
* Zero has literally only one neighbour and doesn't really care.

Sandbox post (deleted)

JavaScript (ES6), 13 bytes
Returns the \$n\$th term of the sequence.
n=>n-2-~++n%5

Try it online!
How?
This computes:
$$n-2+((n+2) \bmod 5)$$
           n |  0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 ...
-------------+--------------------------------------------------
       n - 2 | -2 -1  0  1  2  3  4  5  6  7  8  9 10 11 12 ...
 (n+2) mod 5 |  2  3  4  0  1  2  3  4  0  1  2  3  4  0  1 ...
-------------+--------------------------------------------------
         sum |  0  2  4  1  3  5  7  9  6  8 10 12 14 11 13 ...

Python 2, 20 bytes
lambda n:2*n%5+n/5*5

Try it online!

MathGolf, 5 bytes
⌠5%+⌡

Try it online!
Some nice symmetry here. Returns the nth element of the sequence.
Explanation:
⌠      Increment input by 2
 5%    Modulo by 5
   +   Add to copy of input
    ⌡  Decrement by 2

Jelly, 5 bytes
æ%2.+

Try it online!
Go go gadget obscure built-in!
æ%2.      Symmetric modulo 5: map [0,1,2,3,4,5,6,7,8,9] to [0,1,2,-2,-1,0,1,2,-2,-1]
    +     Add to input

Wolfram Language (Mathematica), 14 bytes
#+Mod[#,5,-2]&

Try it online!
Prints the n-th, zero-indexed, integer in the sequence.

R, 25 23 21 bytes
-2 bytes thanks to Jo King
n=scan();n-2+(n+2)%%5

Try it online!
Outputs nth element in sequence.

dzaima/APL, 9 bytes
2-⍨⊢+5|2+

Port of Arnauld's answer.
Try it online!

Pip, 14 bytes
02413@a+a//5*5

Takes \$n\$ (0-based) as a command-line argument and outputs \$a_n\$. Try it online!
Observe that \$a_{n+5} = a_n+5\$. We hard-code the first five values and offset from there.

Or, the formula everyone's using, for 12 bytes:
a-2+(a+2)%5

Common Lisp, 67 bytes
(defun x(n)(loop for a from 0 to n collect(+(mod(+ a 2)5)(- a 2))))

Try it online!

I think just (defun x(n)(+(mod(+ n 2)5)(- n 2))), or (lambda(n)(+(mod(+ n 2)5)(- n 2))) is enough: returning the n-th term, rather than a sequence of terms.

Japt, 8 bytes
U-2Ò°U%5

Japt Interpreter
A straight port of Arnauld's Javascript answer. The linked version runs through the first n elements, but if the -m flag is removed it is still valid and prints the nth element instead.
For comparison's sake, here is the naive version which implements the algorithm provided in the question:
@_aX É«NøZ}a}gNhT

I'll give an explanation for this one:
              NhT    Set N to [0]
@           }g       Get the nth element of N by filling each index with:
 _        }a          The first integer that satisfies:
  aX É                 It is not a neighbor to the previous element
      «NøZ             And it is not already in N

-3 bytes on your second solution, and can probably be improved further.

05AB1E, 5 bytes
Ì5%+Í

Port of @JoKing's MathGolf answer.
Try it online or verify the first 100 numbers.
Explanation:
Ì        # Increase the (implicit) input by 2
 5%      # Take modulo-5
   +     # Add the (implicit) input to it
    Í    # Decrease by 2 (and output implicitly)

Clean, 31 bytes
The formula everyone's using.
import StdEnv
?n=n-2+(n+2)rem 5

Try it online!
Clean, 80 bytes
My initial approach, returning the first n items.
import StdEnv
$n=iter n(\l=l++[hd[i\\i<-[0..]|all((<>)i)l&&abs(i-last l)>1]])[0]

Try it online!

Pari/GP, 14 bytes
n->2*n%5+n\5*5

Try it online!

Pari/GP, 14 bytes
n->n-2+(n+2)%5

Try it online!

J, 30 bytes
{.2}.[:,_5,./\2(i.-4 0$~])@,~]

Try it online!
Returns a list of first n numbers
This solution is obviously non-competitve, but I wanted to try an array-based method.
Explanation:
The argument is n
2     ,] - append 2 to the input
   (2,~]) 10
10 2

()@ - and use this list to:
i. - create a matrix n x 2 with the numbers in the range 0..2n-1:
   i.10 2
 0  1
 2  3
 4  5
 6  7
 8  9
10 11
12 13
14 15
16 17
18 19

4 0$~] - ~ reverses the arguments, so it is ]$4 0 - creates matrix n x 2 repeating 4 0
   4 0$~10 2
4 0
4 0
4 0
4 0
4 0
4 0
4 0
4 0
4 0
4 0

- subtract the second matrix from the first one, so that the first column is "delayed" with 2 positions
   2(i.-4 0$~])@,~] 10
_4  1
_2  3
 0  5
 2  7
 4  9
 6 11
 8 13
10 15
12 17
14 19

_5,./\ traverse the matrix in non-overlapping groups of 5 rows and stitch the columns
   _5,./\2(i.-4 0$~])@,~] 10
_4 _2  0  2  4
 1  3  5  7  9

 6  8 10 12 14
11 13 15 17 19

[:, ravel the entire array
   ,_5,./\2(i.-4 0$~])@,~] 10
_4 _2 0 2 4 1 3 5 7 9 6 8 10 12 14 11 13 15 17 19

2}. - drop the first 2 numbers
   2}.,_5,./\2(i.-4 0$~])@,~] 10
0 2 4 1 3 5 7 9 6 8 10 12 14 11 13 15 17 19

{. take the first n numbers
   ({.2}.[:,_5,./\2(i.-4 0$~])@,~]) 10
0 2 4 1 3 5 7 9 6 8

J, 9 bytes
+_2+5|2+]

Try it online!
Returns the nth element.
Port of Arnauld's answer

K (ngn/k), 12 bytes
{-2+x+5!x+2}

Try it online!

-2+x+ -> x-2-

Pepe, 65 bytes
REeeeeeeEerEeERRrEEEEEERREeeeeeEeErEEeEeErRrEEEEEEEErRrEEEEEereEE

Try it online!
Port of Jo King's answer.

x86 machine code, 16 bytes
00000000: 31d2 89c8 4949 4040 b305 f7f3 9201 c8c3 1...II@@........

Assembly:
section .text
	global func
func:	;function uses fastcall conventions, 1st arg in ecx, returns in eax
	;reset edx to 0 so division works
	xor edx, edx

	mov eax, ecx
	;calculate ecx (1st func arg) - 2
	dec ecx
	dec ecx

	;calculate (ecx+2) mod 5
	inc eax
	inc eax
	mov bl, 5
	div ebx
	xchg eax, edx

	;add (ecx-2) and ((ecx+2) mod 5), returning in eax
	add eax, ecx
	ret

Try it online!

Red, 26 bytes
func[n][n + 2 % 5 + n - 2]

Try it online!
Port of Arnauld's answer

Excel, 17 bytes
=A1-2+MOD(A1+2,5)

Nothing smart.  Implements the common formula.

C (gcc) POSIX, 20 bytes
f(n){n=n-2+(n+2)%5;}

Try it online!

QBasic, 30 bytes
INPUT x
x=x+2
?-4+x*2-(x\5)*5

Gives the 0-indexed entry of the list at pos x.
Try it online! (Note that ? was expanded to PRINT because the interpreter fails otherwise...)

C# (Visual C# Interactive Compiler), 14 bytes
n=>2*n%5+n/5*5

Try it online!
Same logic than others answers: 1 2

TI-BASIC, 11 bytes
Ans-2+remainder(Ans+2,5

Input is in Ans.
Outputs \$a(n)\$.
A simple port of the other answers.

Note:  TI-BASIC is a tokenized language.  Character count does not equal byte count.

R, 25 bytes
n=1:scan()-1;n-2+(n+2)%%5

Try it online!
Port of Robert S.'s answer (and only by adding just 4 bytes) thanks to R being excellent at handling vectors.
Outputs the first n values.

dc, 9 bytes
d2+5%+2-p

Try it online!
Same method as most. Duplicate top-of-stack, add 2, mod 5, add to original (duplicated earlier), subtract 2, print.